method2testcases
stringlengths 118
6.63k
|
---|
### Question:
Requests { public static LiveHttpRequest doOnComplete(LiveHttpRequest request, Runnable action) { return request.newBuilder() .body(it -> it.doOnEnd(ifSuccessful(action))) .build(); } private Requests(); static LiveHttpRequest doFinally(LiveHttpRequest request, Consumer<Optional<Throwable>> action); static LiveHttpResponse doFinally(LiveHttpResponse response, Consumer<Optional<Throwable>> action); static LiveHttpRequest doOnComplete(LiveHttpRequest request, Runnable action); static LiveHttpResponse doOnComplete(LiveHttpResponse response, Runnable action); static LiveHttpRequest doOnError(LiveHttpRequest request, Consumer<Throwable> action); static LiveHttpResponse doOnError(LiveHttpResponse response, Consumer<Throwable> action); static LiveHttpRequest doOnCancel(LiveHttpRequest request, Runnable action); static LiveHttpResponse doOnCancel(LiveHttpResponse response, Runnable action); }### Answer:
@Test public void requestDoOnCompleteActivatesWhenSuccessfullyCompleted() { Requests.doOnComplete(request, () -> completed.set(Optional.empty())) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.complete(); assertThat(completed.get(), is(Optional.empty())); }
@Test public void responseDoOnCompleteActivatesWhenSuccessfullyCompleted() { Requests.doOnComplete(response, () -> completed.set(Optional.empty())) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.complete(); assertThat(completed.get(), is(Optional.empty())); }
@Test public void requestDoOnCompleteDoesNotActivatesWhenErrors() { RuntimeException cause = new RuntimeException("help!!"); Requests.doOnComplete(request, () -> completed.set(Optional.empty())) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.error(cause); assertThat(completed.get(), is(nullValue())); }
@Test public void responseDoOnCompleteDoesNotActivatesWhenErrors() { RuntimeException cause = new RuntimeException("help!!"); Requests.doOnComplete(response, () -> completed.set(Optional.empty())) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.error(cause); assertThat(completed.get(), is(nullValue())); } |
### Question:
Requests { public static LiveHttpRequest doOnError(LiveHttpRequest request, Consumer<Throwable> action) { return request.newBuilder() .body(it -> it.doOnEnd(ifError(action))) .build(); } private Requests(); static LiveHttpRequest doFinally(LiveHttpRequest request, Consumer<Optional<Throwable>> action); static LiveHttpResponse doFinally(LiveHttpResponse response, Consumer<Optional<Throwable>> action); static LiveHttpRequest doOnComplete(LiveHttpRequest request, Runnable action); static LiveHttpResponse doOnComplete(LiveHttpResponse response, Runnable action); static LiveHttpRequest doOnError(LiveHttpRequest request, Consumer<Throwable> action); static LiveHttpResponse doOnError(LiveHttpResponse response, Consumer<Throwable> action); static LiveHttpRequest doOnCancel(LiveHttpRequest request, Runnable action); static LiveHttpResponse doOnCancel(LiveHttpResponse response, Runnable action); }### Answer:
@Test public void requestDoOnErrorDoesNotActivatesWhenSuccessfullyCompleted() { Requests.doOnError(request, (cause) -> completed.set(Optional.of(cause))) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.complete(); assertThat(completed.get(), is(nullValue())); }
@Test public void responseDoOnErrorDoesNotActivatesWhenSuccessfullyCompleted() { Requests.doOnError(response, (cause) -> completed.set(Optional.of(cause))) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.complete(); assertThat(completed.get(), is(nullValue())); }
@Test public void requestDoOnErrorActivatesWhenErrors() { RuntimeException cause = new RuntimeException("help!!"); Requests.doOnError(request, (it) -> completed.set(Optional.of(it))) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.error(cause); assertThat(completed.get(), is(Optional.of(cause))); }
@Test public void responseDoOnErrorActivatesWhenErrors() { RuntimeException cause = new RuntimeException("help!!"); Requests.doOnError(response, (it) -> completed.set(Optional.of(it))) .consume(); publisher.next(new Buffer("content", UTF_8)); assertThat(completed.get(), is(nullValue())); publisher.error(cause); assertThat(completed.get(), is(Optional.of(cause))); } |
### Question:
PluginsMetadata implements Iterable<SpiExtension> { public List<Pair<String, SpiExtension>> activePlugins() { return activePluginsNames.stream() .map(name -> pair(name, plugins.get(name))) .collect(toList()); } PluginsMetadata(@JsonProperty("active") String active,
@JsonProperty("all") Map<String, SpiExtension> plugins); List<Pair<String, SpiExtension>> plugins(); List<Pair<String, SpiExtension>> activePlugins(); @Override String toString(); @Override Iterator<SpiExtension> iterator(); }### Answer:
@Test public void pluginsAreProvidedInOrderSpecifiedByActivePluginsCommaSeparatedList() { Map<String, SpiExtension> plugins = new LinkedHashMap<>(); Stream.of("two", "four", "three", "one") .forEach(key -> plugins.put(key, pluginMetadata())); PluginsMetadata pluginsMetadata = new PluginsMetadata("one,two,three,four", plugins); List<String> activePlugins = pluginsMetadata.activePlugins().stream() .map(Pair::key) .collect(toList()); assertThat(activePlugins, contains("one", "two", "three", "four")); } |
### Question:
SlidingWindowHistogram { public synchronized void recordValue(long msValue) { checkArgument(msValue >= 0, "Recorded value must be a positive number."); long currentTime = clock.tickMillis(); purgeOldHistograms(currentTime); int bucket = bucketFromTime(currentTime); window[bucket].recordValue(msValue); lastUpdateTime = currentTime; } private SlidingWindowHistogram(Builder builder); synchronized void recordValue(long msValue); synchronized double getMean(); synchronized double getValueAtPercentile(double percentile); synchronized double getStdDeviation(); synchronized Histogram copy(); int windowSize(); long timeIntervalMs(); }### Answer:
@Test public void doesNotAcceptNegativeValues() { assertThrows(IllegalArgumentException.class, () -> newHistogram(2, 2).recordValue(-1)); } |
### Question:
SlidingWindowHistogramReservoir implements Reservoir { @Override public synchronized Snapshot getSnapshot() { if (updated || snapshotExpired(clock.tickMillis())) { snapshot = new HistogramSnapshot(histogram); updated = false; snapshotCreationTime = clock.tickMillis(); } return snapshot; } SlidingWindowHistogramReservoir(); SlidingWindowHistogramReservoir(SlidingWindowHistogram histogram); SlidingWindowHistogramReservoir(SlidingWindowHistogram histogram, Clock clock); @Override int size(); @Override synchronized void update(long value); @Override synchronized Snapshot getSnapshot(); }### Answer:
@Test public void snapshotComputesPercentiles() { SlidingWindowHistogramReservoir reservoir = reservoirWithSamples(1, 100); assertThat(reservoir.getSnapshot().getMin(), is(1L)); assertThat(reservoir.getSnapshot().getMax(), is(100L)); assertThat(reservoir.getSnapshot().getMean(), is(closeTo(50.5, 1))); assertThat(reservoir.getSnapshot().get75thPercentile(), is(closeTo(75, 0.5))); assertThat(reservoir.getSnapshot().get95thPercentile(), is(closeTo(95, 0.5))); assertThat(reservoir.getSnapshot().get98thPercentile(), is(closeTo(98, 0.5))); assertThat(reservoir.getSnapshot().get99thPercentile(), is(closeTo(99, 0.5))); assertThat(reservoir.getSnapshot().getMedian(), is(closeTo(50L, 1))); }
@Test public void snapshotExposesSamplesAsArray() { SlidingWindowHistogramReservoir reservoir = reservoirWithSamples(1, 100); assertThat(reservoir.getSnapshot().getValues(), is(toArray(Range.closed(1L, 100L)))); } |
### Question:
CodaHaleMetricRegistry implements MetricRegistry { @Override public Timer timer(String name) { Map<String, Metric> metrics = metricRegistry.getMetrics(); Metric metric = metrics.get(name); if (metric instanceof Timer) { return (Timer) metric; } if (metric == null) { try { return register(name, newTimer()); } catch (IllegalArgumentException e) { Metric added = metrics.get(name); if (added instanceof Timer) { return (Timer) added; } } } throw new IllegalArgumentException(name + " is already used for a different type of metric"); } CodaHaleMetricRegistry(com.codahale.metrics.MetricRegistry metricRegistry); CodaHaleMetricRegistry(); com.codahale.metrics.MetricRegistry getMetricRegistry(); @Override MetricRegistry scope(String name); @Override T register(String name, T metric); @Override boolean deregister(String name); @Override Counter counter(String name); @Override Histogram histogram(String name); @Override Meter meter(String name); @Override Timer timer(String name); @Override void addListener(MetricRegistryListener listener); @Override void removeListener(MetricRegistryListener listener); @Override SortedSet<String> getNames(); @Override SortedMap<String, Gauge> getGauges(); @Override SortedMap<String, Gauge> getGauges(MetricFilter filter); @Override SortedMap<String, Counter> getCounters(); @Override SortedMap<String, Counter> getCounters(MetricFilter filter); @Override SortedMap<String, Histogram> getHistograms(); @Override SortedMap<String, Histogram> getHistograms(MetricFilter filter); @Override SortedMap<String, Meter> getMeters(); @Override SortedMap<String, Meter> getMeters(MetricFilter filter); @Override SortedMap<String, Timer> getTimers(); @Override SortedMap<String, Timer> getTimers(MetricFilter filter); static String name(String name, String... names); static String name(Class<?> klass, String... names); @Override SortedMap<String, Metric> getMetrics(); }### Answer:
@Test public void retrievesPreviouslyRegisteredTimer() { Timer timer = metricRegistry.timer("newTimer"); assertThat(timer, is(notNullValue())); assertThat(metricRegistry.timer("newTimer"), is(sameInstance(timer))); }
@Test public void createsTimerBackedByLatencyStats() { Timer timer = metricRegistry.timer("timer"); assertThat(timer.getSnapshot(), is(instanceOf(SlidingWindowHistogramReservoir.HistogramSnapshot.class))); } |
### Question:
Announcer { public static <T extends EventListener> Announcer<T> to(Class<? extends T> listenerType) { return new Announcer<>(listenerType); } Announcer(Class<? extends T> listenerType); static Announcer<T> to(Class<? extends T> listenerType); void addListener(T listener); void removeListener(T listener); T announce(); List<T> listeners(); }### Answer:
@Test public void createsAnnouncerForType() { Announcer<AnnouncerTestListener> announcer = Announcer.to(AnnouncerTestListener.class); assertThat(announcer, is(notNullValue())); } |
### Question:
DocumentFormat { public static Builder newDocument() { return new Builder(); } private DocumentFormat(Builder builder); void validateObject(JsonNode tree); static Builder newDocument(); }### Answer:
@Test public void discriminatedUnionSelectorMustBeString() { Exception e = assertThrows(InvalidSchemaException.class, () -> newDocument() .rootSchema(object( field("httpPipeline", object( field("type", integer()), field("config", union("type")) )) ) ).build()); assertThat(e.getMessage(), matchesPattern("Discriminator attribute 'type' must be a string \\(but it is not\\)")); } |
### Question:
FileSystemPluginFactoryLoader implements PluginFactoryLoader { @Override public PluginFactory load(SpiExtension spiExtension) { return newPluginFactory(spiExtension); } @Override PluginFactory load(SpiExtension spiExtension); }### Answer:
@Test public void pluginLoaderLoadsPluginFromJarFile() { SpiExtensionFactory factory = new SpiExtensionFactory("testgrp.TestPluginModule", pluginsPath.toString()); PluginFactory plugin = pluginFactoryLoader.load(new SpiExtension(factory, config, null)); assertThat(plugin, is(not(nullValue()))); assertThat(plugin.getClass().getName(), is("testgrp.TestPluginModule")); }
@Test public void providesMeaningfulErrorMessageWhenConfiguredFactoryClassCannotBeLoaded() { String jarFile = "/plugins/oneplugin/testPluginA-1.0-SNAPSHOT.jar"; Path pluginsPath = fixturesHome(FileSystemPluginFactoryLoader.class, jarFile); SpiExtensionFactory factory = new SpiExtensionFactory("incorrect.plugin.class.name.TestPluginModule", pluginsPath.toString()); SpiExtension spiExtension = new SpiExtension(factory, config, null); Exception e = assertThrows(ConfigurationException.class, () -> new FileSystemPluginFactoryLoader().load(spiExtension)); assertThat(e.getMessage(), matchesPattern("Could not load a plugin factory for configuration=SpiExtension\\{" + "factory=SpiExtensionFactory\\{" + "class=incorrect.plugin.class.name.TestPluginModule, " + "classPath=.*[\\\\/]components[\\\\/]proxy[\\\\/]target[\\\\/]test-classes[\\\\/]plugins[\\\\/]oneplugin[\\\\/]testPluginA-1.0-SNAPSHOT.jar" + "\\}\\}")); } |
### Question:
Schema { private Schema(Builder builder) { this.fieldNames = builder.fields.stream().map(Field::name).collect(toList()); this.fields = ImmutableList.copyOf(builder.fields); this.optionalFields = ImmutableSet.copyOf(builder.optionalFields); this.constraints = ImmutableList.copyOf(builder.constraints); this.ignore = builder.pass; this.name = builder.name.length() > 0 ? builder.name : String.join(", ", this.fieldNames); } private Schema(Builder builder); Set<String> optionalFields(); List<String> fieldNames(); List<Field> fields(); List<Constraint> constraints(); String name(); boolean ignore(); Builder newBuilder(); }### Answer:
@Test public void list_checksThatSubobjectUnionDiscriminatorAttributeExists() throws Exception { Exception e = assertThrows(InvalidSchemaException.class, () -> schema(field("name", string()), field("config", union("type")) )); assertEquals("Discriminator attribute 'type' not present.", e.getMessage()); }
@Test public void checksThatSubobjectUnionDiscriminatorAttributeIsString() throws Exception { Exception e = assertThrows(InvalidSchemaException.class, () -> schema(field("name", string()), field("type", integer()), field("config", union("type")) )); assertThat(e.getMessage(), matchesPattern("Discriminator attribute 'type' must be a string \\(but it is not\\)")); } |
### Question:
AtLeastOneFieldPresenceConstraint implements Constraint { @Override public String describe() { return description; } AtLeastOneFieldPresenceConstraint(String... fieldNames); @Override boolean evaluate(Schema schema, JsonNode node); @Override String describe(); }### Answer:
@Test public void describesItsBehaviour() { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); assertThat(constraint.describe(), is("At least one of ('http', 'https') must be present.")); } |
### Question:
AtLeastOneFieldPresenceConstraint implements Constraint { @Override public boolean evaluate(Schema schema, JsonNode node) { long fieldsPresent = ImmutableList.copyOf(node.fieldNames()) .stream() .filter(fieldNames::contains) .count(); return fieldsPresent >= 1; } AtLeastOneFieldPresenceConstraint(String... fieldNames); @Override boolean evaluate(Schema schema, JsonNode node); @Override String describe(); }### Answer:
@Test public void passesWhenOneRequiredFieldIsPresent() throws IOException { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); boolean result = constraint.evaluate( schema( field("x", integer()), field("http", integer()), field("https", integer()), atLeastOne("http", "https")), jsonNode( " http: 8080\n" )); assertThat(result, is(true)); }
@Test public void allowsSeveralFieldsToBePresent() throws IOException { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); boolean result = constraint.evaluate( schema( field("x", integer()), field("http", integer()), field("https", integer()), atLeastOne("http", "https")), jsonNode( " https: 8443\n" + " http: 8080\n" )); assertThat(result, is(true)); }
@Test public void throwsExceptionWhenNoneRequiredFieldsArePresent() throws IOException { AtLeastOneFieldPresenceConstraint constraint = new AtLeastOneFieldPresenceConstraint("http", "https"); boolean result = constraint.evaluate( schema( field("x", integer()), field("http", integer()), field("https", integer()), atLeastOne("http", "https")), jsonNode( " x: 43\n" )); assertThat(result, is(false)); } |
### Question:
HttpAggregator implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { return request.aggregate(bytes) .flatMap(aggregated -> this.delegate.handle(aggregated, context)) .map(HttpResponse::stream); } HttpAggregator(int bytes, WebServiceHandler delegate); HttpAggregator(WebServiceHandler delegate); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void aggregatesRequestAndStreamsResponses() { AtomicReference<String> result = new AtomicReference<>(); WebServiceHandler webServiceHandler = (request, ctx) -> { result.set(request.bodyAs(UTF_8)); return Eventual.of(response(OK) .body("abcdef", UTF_8) .build()); }; LiveHttpResponse response = Mono.from( new HttpAggregator(500, webServiceHandler) .handle(LiveHttpRequest.post("/") .body(ByteStream.from("ABCDEF", UTF_8)) .build(), requestContext())) .block(); assertThat(result.get(), is("ABCDEF")); assertThat(Mono.from(response.aggregate(500)).block().bodyAs(UTF_8), is("abcdef")); } |
### Question:
HttpStreamer implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { return delegate.handle(request.stream(), context) .flatMap(live -> live.aggregate(maxContentBytes)); } HttpStreamer(int maxContentBytes, HttpHandler delegate); HttpStreamer(HttpHandler delegate); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void streamsRequestAndAggregatesResponses() { HttpHandler httpHandler = (request, ctx) -> Eventual.of( LiveHttpResponse.response(OK) .body(ByteStream.from("abcdef", UTF_8)) .build()); HttpResponse response = Mono.from( new HttpStreamer(500, httpHandler) .handle(HttpRequest.post("/") .body("ABCDEF", UTF_8) .build(), requestContext())) .block(); assertThat(response.bodyAs(UTF_8), is("abcdef")); } |
### Question:
HttpMethodFilteringHandler implements WebServiceHandler { @Override public Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context) { if (!method.equals(request.method())) { return Eventual.of( HttpResponse.response(METHOD_NOT_ALLOWED) .body(errorBody, StandardCharsets.UTF_8) .build() ); } return httpHandler.handle(request, context); } HttpMethodFilteringHandler(HttpMethod method, WebServiceHandler httpHandler); @Override Eventual<HttpResponse> handle(HttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void delegatesTheRequestIfRequestMethodIsSupported() { WebServiceHandler handler = mock(WebServiceHandler.class); HttpMethodFilteringHandler post = new HttpMethodFilteringHandler(POST, handler); HttpRequest request = post("/some-uri").build(); post.handle(request, mock(HttpInterceptor.Context.class)); verify(handler).handle(eq(request), any(HttpInterceptor.Context.class)); }
@Test public void failsIfRequestMethodIsNotSupported() throws Exception { WebServiceHandler handler = mock(WebServiceHandler.class); HttpMethodFilteringHandler post = new HttpMethodFilteringHandler(GET, handler); HttpRequest request = post("/some-uri").build(); HttpResponse response = Mono.from(post.handle(request, requestContext())).block(); assertThat(response.status(), is(METHOD_NOT_ALLOWED)); } |
### Question:
FsmEventProcessor implements EventProcessor { @Override public void submit(Object event) { requireNonNull(event); try { stateMachine.handle(event, loggingPrefix); } catch (Throwable cause) { String eventName = event.getClass().getSimpleName(); LOGGER.error("{} {} -> ???: Exception occurred while processing event={}. Cause=\"{}\"", new Object[]{loggingPrefix, stateMachine.currentState(), eventName, cause}); errorHandler.accept(cause, stateMachine.currentState()); } } FsmEventProcessor(StateMachine<S> stateMachine, BiConsumer<Throwable, S> errorHandler, String loggingPrefix); @Override void submit(Object event); }### Answer:
@Test public void throwsNullPointerExceptionForNullEvents() { FsmEventProcessor<String> processor = new FsmEventProcessor<>(stateMachine, errorHandler, "prefix"); assertThrows(NullPointerException.class, () -> processor.submit(null)); }
@Test public void propagatesEventToFsm() { FsmEventProcessor<String> processor = new FsmEventProcessor<>(stateMachine, errorHandler, "prefix"); processor.submit(new TestEventOk()); assertThat(stateMachine.currentState(), is("end")); }
@Test public void handlesStateMachineExceptions() { FsmEventProcessor<String> processor = new FsmEventProcessor<>(stateMachine, errorHandler, "prefix"); processor.submit(new TestEventError()); verify(errorHandler).accept(any(RuntimeException.class), eq("start")); assertThat(logger.lastMessage(), is( loggingEvent( ERROR, "prefix start -> \\?\\?\\?: Exception occurred while processing event=TestEventError. Cause=.*", RuntimeException.class, "Test exception message"))); } |
### Question:
FileResourceIndex implements ResourceIndex { @Override public Iterable<Resource> list(String path, String suffix) { ArrayList<Resource> list = new ArrayList<>(); new FileResourceIterator(new File(path), new File(path), suffix).forEachRemaining(list::add); return list; } @Override Iterable<Resource> list(String path, String suffix); }### Answer:
@Test public void listsResourcesFromFileSystemDirectory() { Iterable<Resource> jars = resourceIndex.list(PLUGINS_FIXTURE_PATH.toString(), ".jar"); assertThat(jars, contains(resourceWithPath("oneplugin/url-rewrite-1.0-SNAPSHOT.jar"))); }
@Test public void listsResourcesFromFileSystemFile() { File file = new File(PLUGINS_FIXTURE_PATH.toFile(), "groovy/UrlRewrite.groovy"); Iterable<Resource> files = resourceIndex.list(file.getPath(), ".anything"); assertThat(files, contains(resourceWithPath( PLUGINS_FIXTURE_PATH.resolve("groovy/UrlRewrite.groovy").toString()))); } |
### Question:
ClasspathResourceIndex implements ResourceIndex { @Override public Iterable<Resource> list(String path, String suffix) { String classpath = path.replace("classpath:", ""); ResourceIteratorFactory resourceIteratorFactory = new DelegatingResourceIteratorFactory(); try { Enumeration<URL> resources = classLoader.getResources(classpath); return enumerationStream(resources) .map(url -> resourceIteratorFactory.createIterator(url, classpath, suffix)) .flatMap(ClasspathResourceIndex::iteratorStream) .collect(toList()); } catch (IOException e) { throw new RuntimeException(e); } } ClasspathResourceIndex(ClassLoader classLoader); @Override Iterable<Resource> list(String path, String suffix); }### Answer:
@Test public void listsByPathAndSuffix() { ClassLoader classLoader = ClasspathResourceIndexTest.class.getClassLoader(); ClasspathResourceIndex index = new ClasspathResourceIndex(classLoader); Iterable<Resource> resources = index.list("com/hotels/styx/common/io", ".txt"); assertThat(resources, containsInAnyOrder( resourceWithPath("resource.txt"), resourceWithPath("subdirectory/subdir-resource.txt") )); } |
### Question:
FileResource implements Resource { @Override public InputStream inputStream() throws IOException { return new FileInputStream(file); } FileResource(File file); FileResource(File root, File file); FileResource(String path); @Override String path(); @Override URL url(); @Override String absolutePath(); @Override InputStream inputStream(); @Override ClassLoader classLoader(); File getFile(); @Override String toString(); static final String FILE_SCHEME; }### Answer:
@Test public void nonExistentResourceThrowsExceptionWhenTryingToGetInputStream() throws IOException { FileResource resource = new FileResource("foobar"); Exception e = assertThrows(FileNotFoundException.class, () -> resource.inputStream()); assertThat(e.getMessage(), matchesPattern("foobar.*")); } |
### Question:
ClasspathResource implements Resource { @Override public URL url() { URL url = this.classLoader.getResource(this.path); if (url == null) { throw new RuntimeException(new FileNotFoundException(this.path)); } return url; } ClasspathResource(String path, Class<?> clazz); ClasspathResource(String path, ClassLoader classLoader); @Override String path(); @Override URL url(); @Override String absolutePath(); @Override InputStream inputStream(); @Override ClassLoader classLoader(); @Override String toString(); static final String CLASSPATH_SCHEME; }### Answer:
@Test public void nonExistentResourceThrowsExceptionWhenTryingToGetURL() { ClasspathResource resource = new ClasspathResource("foobar", ClasspathResourceTest.class); Exception e = assertThrows(RuntimeException.class, () -> resource.url()); assertEquals("java.io.FileNotFoundException: foobar", e.getMessage()); } |
### Question:
ClasspathResource implements Resource { @Override public InputStream inputStream() throws FileNotFoundException { InputStream stream = classLoader.getResourceAsStream(this.path); if (stream == null) { throw new FileNotFoundException(CLASSPATH_SCHEME + path); } return stream; } ClasspathResource(String path, Class<?> clazz); ClasspathResource(String path, ClassLoader classLoader); @Override String path(); @Override URL url(); @Override String absolutePath(); @Override InputStream inputStream(); @Override ClassLoader classLoader(); @Override String toString(); static final String CLASSPATH_SCHEME; }### Answer:
@Test public void nonExistentResourceThrowsExceptionWhenTryingToGetInputStream() { ClasspathResource resource = new ClasspathResource("foobar", ClasspathResourceTest.class); Exception e = assertThrows(FileNotFoundException.class, () -> resource.inputStream()); assertEquals("classpath:foobar", e.getMessage()); } |
### Question:
ResourceFactory { public static Resource newResource(String path, ClassLoader classLoader) { if (path.startsWith(CLASSPATH_SCHEME)) { return new ClasspathResource(path, classLoader); } return new FileResource(path); } static Resource newResource(String path, ClassLoader classLoader); static Resource newResource(String path); }### Answer:
@Test public void canAcquireClasspathResources() { Resource resource = ResourceFactory.newResource("classpath:com/hotels/styx/common/io/resource.txt"); assertThat(resource, contains("This is an example resource.\nIt has content to use in automated tests.")); }
@Test public void canAcquireFileResources() { String filePath = ResourceFactoryTest.class.getResource("/com/hotels/styx/common/io/resource.txt").getPath(); Resource resource = ResourceFactory.newResource(filePath); assertThat(resource, contains("This is an example resource.\nIt has content to use in automated tests.")); } |
### Question:
ClassFactories { public static <T> T newInstance(String className, Class<T> type) { try { Object instance = classForName(className).newInstance(); return type.cast(instance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(format("No such class '%s'", className)); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } private ClassFactories(); static T newInstance(String className, Class<T> type); }### Answer:
@Test public void instantiatesClassWithZeroArgumentConstructor() { MyInterface instance = ClassFactories.newInstance(MyClass.class.getName(), MyInterface.class); assertThat(instance, is(instanceOf(MyClass.class))); }
@Test public void throwsExceptionIfThereIsNoZeroArgumentConstructor() { Exception e = assertThrows(RuntimeException.class, () -> ClassFactories.newInstance(MyInvalidClass.class.getName(), MyInterface.class)); assertEquals("java.lang.InstantiationException: com.hotels.styx.proxy.ClassFactoriesTest$MyInvalidClass", e.getMessage()); }
@Test public void throwsExceptionIfClassDoesNotExtendType() { Exception e = assertThrows(ClassCastException.class, () -> ClassFactories.newInstance(MyClass.class.getName(), Runnable.class)); assertEquals("Cannot cast com.hotels.styx.proxy.ClassFactoriesTest$MyClass to java.lang.Runnable", e.getMessage()); }
@Test public void throwsExceptionIfClassDoesNotExist() { Exception e = assertThrows(IllegalArgumentException.class, () -> ClassFactories.newInstance(MyClass.class.getName() + "NonExistent", Runnable.class)); assertEquals("No such class 'com.hotels.styx.proxy.ClassFactoriesTest$MyClassNonExistent'", e.getMessage()); } |
### Question:
Preconditions { public static String checkNotEmpty(String value) { if (value == null || value.length() == 0) { throw new IllegalArgumentException(); } return value; } private Preconditions(); static String checkNotEmpty(String value); static T checkArgument(T reference, boolean expression); static void checkArgument(boolean expression); static void checkArgument(boolean expression, Object errorMessage); static void checkArgument(boolean expression,
String errorMessageTemplate,
Object... errorMessageArgs); }### Answer:
@Test public void isNotEmptyString() { assertThat(checkNotEmpty(" "), is(" ") ); }
@Test public void isEmptyString() { assertThrows(IllegalArgumentException.class, () -> checkNotEmpty(null)); } |
### Question:
Preconditions { public static <T> T checkArgument(T reference, boolean expression) { if (!expression) { throw new IllegalArgumentException(); } return reference; } private Preconditions(); static String checkNotEmpty(String value); static T checkArgument(T reference, boolean expression); static void checkArgument(boolean expression); static void checkArgument(boolean expression, Object errorMessage); static void checkArgument(boolean expression,
String errorMessageTemplate,
Object... errorMessageArgs); }### Answer:
@Test public void checkArgumentFailure() { assertThrows(IllegalArgumentException.class, () -> checkArgument(0, false)); }
@Test public void checkArgumentSuccess() { assertThat(checkArgument(0, true), is(0)); } |
### Question:
QueueDrainingEventProcessor implements EventProcessor { @Override public void submit(Object event) { events.add(event); if (eventCount.getAndIncrement() == 0) { do { Object e = events.poll(); try { eventProcessor.submit(e); } catch (RuntimeException cause) { if (logErrors) { LOGGER.warn("Event {} threw an exception {}.", event, cause); } } } while (eventCount.decrementAndGet() > 0); } } QueueDrainingEventProcessor(EventProcessor eventProcessor); QueueDrainingEventProcessor(EventProcessor eventProcessor, boolean logErrors); @Override void submit(Object event); }### Answer:
@Test public void processesEvents() { QueueDrainingEventProcessor eventProcessor = new QueueDrainingEventProcessor((event) -> ((Consumer<Void>) event).accept(null)); Consumer<Void> event1 = mock(Consumer.class); eventProcessor.submit(event1); Consumer<Void> event2 = mock(Consumer.class); eventProcessor.submit(event2); InOrder inOrder = Mockito.inOrder(event1, event2); inOrder.verify(event1).accept(null); inOrder.verify(event2).accept(null); }
@Test public void processesQueuedEvents() { for (int i = 0; i < 1000; i++) { CyclicBarrier barrier1 = new CyclicBarrier(2); CyclicBarrier barrier2 = new CyclicBarrier(2); QueueDrainingEventProcessor eventProcessor = new QueueDrainingEventProcessor((event) -> ((Consumer<Void>) event).accept(null)); Consumer<Void> event1 = mock(Consumer.class); Consumer<Void> event2 = mock(Consumer.class); Consumer<Void> event3 = mock(Consumer.class); startThread(() -> { await(barrier1); eventProcessor.submit(event2); eventProcessor.submit(event3); await(barrier2); }); eventProcessor.submit(consumerEvent((x) -> { await(barrier1); event1.accept(null); await(barrier2); })); InOrder inOrder = Mockito.inOrder(event1, event2, event3); inOrder.verify(event1).accept(null); inOrder.verify(event2).accept(null); inOrder.verify(event3).accept(null); } }
@Test public void handlesEventProcessorExceptions() throws Exception { for (int i = 0; i < 1000; i++) { CyclicBarrier barrier1 = new CyclicBarrier(2); CyclicBarrier barrier2 = new CyclicBarrier(2); CyclicBarrier barrier3 = new CyclicBarrier(2); QueueDrainingEventProcessor eventProcessor = new QueueDrainingEventProcessor((event) -> ((Consumer<Void>) event).accept(null), false); startThread( () -> { Consumer<Void> lockEvent = consumerEvent((x) -> { await(barrier1); try { throw new JustATestException(); } finally { await(barrier2); } }); eventProcessor.submit(lockEvent); }); barrier1.await(); Consumer<Void> event2 = mock(Consumer.class); eventProcessor.submit(consumerEvent(x -> { event2.accept(null); await(barrier3); })); await(barrier2); await(barrier3); verify(event2).accept(eq(null)); } } |
### Question:
SanitisedHttpMessageFormatter implements HttpMessageFormatter { @Override public String formatRequest(HttpRequest request) { return request == null ? NULL : formatRequest( request.version(), request.method(), request.url(), request.id(), request.headers()); } SanitisedHttpMessageFormatter(SanitisedHttpHeaderFormatter sanitisedHttpHeaderFormatter); @Override String formatRequest(HttpRequest request); @Override String formatRequest(LiveHttpRequest request); @Override String formatResponse(HttpResponse response); @Override String formatResponse(LiveHttpResponse response); @Override String formatNettyMessage(HttpObject message); @Override Throwable wrap(Throwable t); }### Answer:
@Test public void shouldFormatHttpRequest() { String formattedRequest = sanitisedHttpMessageFormatter.formatRequest(httpRequest); assertThat(formattedRequest, matchesPattern(HTTP_REQUEST_PATTERN)); }
@Test public void shouldFormatLiveHttpRequest() { String formattedRequest = sanitisedHttpMessageFormatter.formatRequest(httpRequest.stream()); assertThat(formattedRequest, matchesPattern(HTTP_REQUEST_PATTERN)); } |
### Question:
SanitisedHttpMessageFormatter implements HttpMessageFormatter { @Override public String formatResponse(HttpResponse response) { return response == null ? NULL : formatResponse( response.version(), response.status(), response.headers()); } SanitisedHttpMessageFormatter(SanitisedHttpHeaderFormatter sanitisedHttpHeaderFormatter); @Override String formatRequest(HttpRequest request); @Override String formatRequest(LiveHttpRequest request); @Override String formatResponse(HttpResponse response); @Override String formatResponse(LiveHttpResponse response); @Override String formatNettyMessage(HttpObject message); @Override Throwable wrap(Throwable t); }### Answer:
@Test public void shouldFormatHttpResponse() { String formattedResponse = sanitisedHttpMessageFormatter.formatResponse(httpResponse); assertThat(formattedResponse, matchesPattern(HTTP_RESPONSE_PATTERN)); }
@Test public void shouldFormatLiveHttpResponse() { String formattedResponse = sanitisedHttpMessageFormatter.formatResponse(httpResponse.stream()); assertThat(formattedResponse, matchesPattern(HTTP_RESPONSE_PATTERN)); } |
### Question:
SanitisedHttpHeaderFormatter { public String format(HttpHeaders headers) { return StreamSupport.stream(headers.spliterator(), false) .map(this::hideOrFormatHeader) .collect(joining(", ")); } SanitisedHttpHeaderFormatter(List<String> headersToHide, List<String> cookiesToHide); List<String> cookiesToHide(); String format(HttpHeaders headers); }### Answer:
@Test public void formatShouldFormatRequest() { HttpHeaders headers = new HttpHeaders.Builder() .add("header1", "a") .add("header2", "b") .add("header3", "c") .add("header4", "d") .add("COOKIE", "cookie1=e;cookie2=f;") .add("SET-COOKIE", "cookie3=g;cookie4=h;") .build(); List<String> headersToHide = Arrays.asList("HEADER1", "HEADER3"); List<String> cookiesToHide = Arrays.asList("cookie2", "cookie4"); String formattedHeaders = new SanitisedHttpHeaderFormatter(headersToHide, cookiesToHide).format(headers); assertThat(formattedHeaders, is("header1=****, header2=b, header3=****, header4=d, COOKIE=cookie1=e;cookie2=****, SET-COOKIE=cookie3=g;cookie4=****")); } |
### Question:
StateMachine { public S currentState() { return currentState; } private StateMachine(S initialState, Map<Key<S>, Function<Object, S>> transitions,
BiFunction<S, Object, S> inappropriateEventHandler, StateChangeListener<S> stateChangeListener); S currentState(); void handle(Object event, String loggingPrefix); void handle(Object event); }### Answer:
@Test public void startsInInitialState() { StateMachine<State> stateMachine = stateMachineBuilder.build(); assertThat(stateMachine.currentState(), Matchers.is(STARTED)); } |
### Question:
FlowControllingHttpContentProducer { public void newChunk(ByteBuf content) { stateMachine.handle(new ContentChunkEvent(content)); } FlowControllingHttpContentProducer(
Runnable askForMore,
Runnable onCompleteAction,
Consumer<Throwable> onTerminateAction,
String loggingPrefix,
long inactivityTimeoutMs,
EventLoop eventLoop); void newChunk(ByteBuf content); void lastHttpContent(); void channelException(Throwable cause); void channelInactive(Throwable cause); void tearDownResources(Throwable cause); void request(long n); void onSubscribed(Subscriber<? super ByteBuf> subscriber); void unsubscribe(); long emittedBytes(); long emittedChunks(); long receivedBytes(); long receivedChunks(); }### Answer:
@Test public void contentEventInBufferingState() { setUpAndRequest(5); verify(askForMore).run(); producer.newChunk(contentChunk1); verify(askForMore, times(1)).run(); producer.newChunk(contentChunk2); verify(askForMore, times(1)).run(); } |
### Question:
Logging { public static String sanitise(String input) { return input.replaceAll("\\n", "\\\\n"); } private Logging(); static String sanitise(String input); }### Answer:
@Test public void sanitiseRemovesNewlines() throws Exception { assertThat(Logging.sanitise("first line\nsecond line"), is("first line\\nsecond line")); } |
### Question:
ConfigurableUnwiseCharsEncoder implements UnwiseCharsEncoder { @Override public String encode(String value) { String escaped = escaper.escape(value); if (!Objects.equals(escaped, value)) { logger.warn("Value contains unwise chars. you should fix this. raw={}, escaped={}: ", value, escaped); } return escaped; } ConfigurableUnwiseCharsEncoder(String unwiseChars); ConfigurableUnwiseCharsEncoder(StyxConfig config); ConfigurableUnwiseCharsEncoder(StyxConfig config, Logger logger); ConfigurableUnwiseCharsEncoder(String unwiseChars, Logger logger); @Override String encode(String value); static final String ENCODE_UNWISECHARS; }### Answer:
@Test public void loadsUnwiseCharsToEncodeFromConfigurations() { ConfigurableUnwiseCharsEncoder encoder = newUnwiseCharsEncoder("|,},{"); assertThat(encoder.encode("|}{"), is("%7C%7D%7B")); }
@Test public void shouldHandleEmptyUnwiseChars() { ConfigurableUnwiseCharsEncoder encoder = newUnwiseCharsEncoder(""); assertThat(encoder.encode("|}{"), is("|}{")); }
@Test public void shouldEncodeUnwiseCharsMixedWithOtherChars() { ConfigurableUnwiseCharsEncoder encoder = newUnwiseCharsEncoder("|,{,}"); String urlWithUnwiseChars = "/search.do?foo={&srsReport=Landing|AutoS|HOTEL|Hotel%20Il%20Duca%20D%27Este" + "|0|0|0|2|1|2|284128&srsr=Landing|AutoS|HOTEL|Hotel%20Il%20Duca%20D%27Este|0|0|0|2|1|2|284128"; assertThat(encoder.encode(urlWithUnwiseChars), is("/search.do?foo=%7B&srsReport=Landing%7CAutoS%7CHOTEL%7CHotel" + "%20Il%20Duca%20D%27Este%7C0%7C0%7C0%7C2%7C1%7C2%7C284128&srsr=Landing%7CAutoS%7CHOTEL%7CHotel%20Il%20" + "Duca%20D%27Este%7C0%7C0%7C0%7C2%7C1%7C2%7C284128")); }
@Test public void shouldLogErrorMessageInCaseOfEncodingUnwiseChars() throws Exception { Logger logger = mock(Logger.class); ConfigurableUnwiseCharsEncoder encoder = new ConfigurableUnwiseCharsEncoder(newStyxConfig("|"), logger); assertThat(encoder.encode("|}{"), is("%7C}{")); verify(logger).warn("Value contains unwise chars. you should fix this. raw={}, escaped={}: ", "|}{", "%7C}{"); }
@Test public void shouldNotLogIfNotEncoding() throws Exception { Logger logger = mock(Logger.class); ConfigurableUnwiseCharsEncoder encoder = new ConfigurableUnwiseCharsEncoder(newStyxConfig(""), logger); assertThat(encoder.encode("|}{"), is("|}{")); verifyZeroInteractions(logger); } |
### Question:
FunctionResolver { PartialFunction resolveFunction(String name, List<String> arguments) { int argumentSize = arguments.size(); String argumentsRepresentation = join(", ", arguments); switch (argumentSize) { case 0: Function0 function0 = ensureNotNull( zeroArgumentFunctions.get(name), "No such function=[%s], with n=[%d] arguments=[%s]", name, argumentSize, argumentsRepresentation); return function0::call; case 1: Function1 function1 = ensureNotNull( oneArgumentFunctions.get(name), "No such function=[%s], with n=[%d] arguments=[%s]", name, argumentSize, argumentsRepresentation); return (request, context) -> function1.call(request, context, arguments.get(0)); default: throw new IllegalArgumentException(format("No such function=[%s], with n=[%d] arguments=[%s]", name, argumentSize, argumentsRepresentation)); } } FunctionResolver(Map<String, Function0> zeroArgumentFunctions, Map<String, Function1> oneArgumentFunctions); }### Answer:
@Test public void resolvesZeroArgumentFunctions() { LiveHttpRequest request = get("/foo").build(); assertThat(functionResolver.resolveFunction("path", emptyList()).call(request, context), is("/foo")); assertThat(functionResolver.resolveFunction("method", emptyList()).call(request, context), is("GET")); }
@Test public void throwsExceptionIfZeroArgumentFunctionDoesNotExist() { LiveHttpRequest request = get("/foo").build(); Exception e = assertThrows(DslFunctionResolutionError.class, () -> functionResolver.resolveFunction("foobar", emptyList()).call(request, context)); assertThat(e.getMessage(), matchesPattern("No such function=\\[foobar\\], with n=\\[0\\] arguments=\\[\\]")); }
@Test public void resolvesOneArgumentFunctions() { LiveHttpRequest request = get("/foo") .header("Host", "www.hotels.com") .cookies(requestCookie("lang", "en_US|en-us_hotels_com")) .build(); assertThat(functionResolver.resolveFunction("header", singletonList("Host")).call(request, context), is("www.hotels.com")); assertThat(functionResolver.resolveFunction("cookie", singletonList("lang")).call(request, context), is("en_US|en-us_hotels_com")); }
@Test public void throwsExceptionIfOneArgumentFunctionDoesNotExist() { LiveHttpRequest request = get("/foo") .header("Host", "www.hotels.com") .cookies(requestCookie("lang", "en_US|en-us_hotels_com")) .build(); Exception e = assertThrows(DslFunctionResolutionError.class, () -> functionResolver.resolveFunction("foobar", singletonList("barfoo")).call(request, context)); assertThat(e.getMessage(), matchesPattern("No such function=\\[foobar\\], with n=\\[1\\] arguments=\\[barfoo\\]")); } |
### Question:
NettyToStyxRequestDecoder extends MessageToMessageDecoder<HttpObject> { @Override protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception { if (msg.getDecoderResult().isFailure()) { String formattedHttpObject = httpMessageFormatter.formatNettyMessage(msg); throw new BadRequestException("Error while decoding request: " + formattedHttpObject, httpMessageFormatter.wrap(msg.getDecoderResult().cause())); } try { if (msg instanceof HttpRequest) { ctx.channel().config().setAutoRead(false); ctx.channel().read(); HttpRequest nettyRequest = (HttpRequest) msg; this.producer = Optional.of(createProducer(ctx, nettyRequest.uri())); Publisher<Buffer> contentPublisher = new FlowControllingPublisher(queueDrainingExecutor, this.producer.get()); LiveHttpRequest styxRequest = toStyxRequest(nettyRequest, contentPublisher); out.add(styxRequest); } if (msg instanceof HttpContent) { assert this.producer.isPresent(); ByteBuf content = ((ByteBufHolder) msg).content(); if (content.isReadable()) { ByteBuf byteBuf = retain(content); queueDrainingExecutor.execute(() -> producer.get().newChunk(byteBuf)); } if (msg instanceof LastHttpContent) { queueDrainingExecutor.execute(() -> producer.get().lastHttpContent()); } } } catch (BadRequestException ex) { throw ex; } catch (Exception ex) { throw new BadRequestException(ex.getMessage() + " in " + msg, ex); } } private NettyToStyxRequestDecoder(Builder builder); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer:
@Test public void sanitisesHeadersInBadRequestException() throws Throwable { FullHttpRequest originalRequest = newHttpRequest("/uri"); HttpHeaders originalRequestHeaders = originalRequest.headers(); originalRequestHeaders.add("Foo", "foo"); originalRequestHeaders.add("secret-header", "secret"); originalRequestHeaders.add("Cookie", "Bar=bar;secret-cookie=secret"); originalRequest.setDecoderResult(DecoderResult.failure(new Exception("It just didn't work"))); Exception e = assertThrows(DecoderException.class, () -> decode(originalRequest)); assertEquals(BadRequestException.class, e.getCause().getClass()); String breMsg = e.getCause().getMessage(); assertThat(breMsg, containsString("Foo=foo")); assertThat(breMsg, containsString("secret-header=****")); assertThat(breMsg, containsString("Bar=bar")); assertThat(breMsg, containsString("secret-cookie=****")); assertThat(breMsg, not(containsString("secret-header=secret"))); assertThat(breMsg, not(containsString("secret-cookie=secret"))); }
@Test public void decodesNettyInternalRequestToStyxRequest() throws Exception { FullHttpRequest originalRequest = newHttpRequest("/uri"); HttpHeaders originalRequestHeaders = originalRequest.headers(); originalRequestHeaders.add("Foo", "Bar"); originalRequestHeaders.add("Bar", "Bar"); originalRequestHeaders.add("Host", "foo.com"); LiveHttpRequest styxRequest = decode(originalRequest); assertThat(styxRequest.id().toString(), is("1")); assertThat(styxRequest.url().encodedUri(), is(originalRequest.getUri())); assertThat(styxRequest.method(), is(HttpMethod.GET)); assertThatHttpHeadersAreSame(styxRequest.headers(), originalRequestHeaders); }
@Test public void removesExpectHeaderBeforePassingThroughTheRequest() throws Exception { FullHttpRequest originalRequest = newHttpRequest("/uri"); originalRequest.headers().set(EXPECT, CONTINUE); originalRequest.headers().set(HOST, "foo.com"); LiveHttpRequest styxRequest = decode(originalRequest); assertThat(styxRequest.header(EXPECT).isPresent(), is(false)); }
@Test public void overridesTheHostHeaderWithTheHostAndPortInTheAbsoluteURI() { HttpRequest request = newHttpRequest(URI.create("http: request.headers().set(HOST, "www.example.com:8000"); LiveHttpRequest styxRequest = decode(request); assertThat(styxRequest.headers().get(HOST).get(), is("example.net")); } |
### Question:
NettyToStyxRequestDecoder extends MessageToMessageDecoder<HttpObject> { @VisibleForTesting LiveHttpRequest.Builder makeAStyxRequestFrom(HttpRequest request, Publisher<Buffer> content) { Url url = UrlDecoder.decodeUrl(unwiseCharEncoder, request); LiveHttpRequest.Builder requestBuilder = new LiveHttpRequest.Builder() .method(toStyxMethod(request.method())) .url(url) .version(toStyxVersion(request.protocolVersion())) .id(uniqueIdSupplier.get()) .body(new ByteStream(content)); stream(request.headers().spliterator(), false) .forEach(entry -> requestBuilder.addHeader(entry.getKey(), entry.getValue())); return requestBuilder; } private NettyToStyxRequestDecoder(Builder builder); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer:
@Test public void canHandleNettyCookies() { HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http: request.headers().set(HOST, "http: request.headers().set("Cookie", "ABC01=\"1\"; ABC02=1; guid=xxxxx-xxx-xxx-xxx-xxxxxxx"); NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder() .uniqueIdSupplier(uniqueIdSupplier) .build(); LiveHttpRequest styxRequest = decoder.makeAStyxRequestFrom(request, Flux.empty()) .build(); LiveHttpRequest expected = new LiveHttpRequest.Builder( HttpMethod.GET, "http: .cookies( requestCookie("ABC01", "\"1\""), requestCookie("ABC02", "1"), requestCookie("guid", "xxxxx-xxx-xxx-xxx-xxxxxxx") ) .build(); assertThat(newHashSet(styxRequest.cookies()), is(newHashSet(expected.cookies()))); }
@Test public void acceptsMalformedCookiesWithRelaxedValidation() { HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http: request.headers().set(HOST, "http: request.headers().set("Cookie", "ABC01=\"1\"; ABC02=1; guid=a,b"); NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder() .uniqueIdSupplier(uniqueIdSupplier) .build(); LiveHttpRequest styxRequest = decoder.makeAStyxRequestFrom(request, Flux.empty()) .build(); LiveHttpRequest expected = new LiveHttpRequest.Builder( HttpMethod.GET, "http: .cookies( requestCookie("ABC01", "\"1\""), requestCookie("ABC02", "1"), requestCookie("guid", "a,b") ) .build(); assertThat(newHashSet(styxRequest.cookies()), is(newHashSet(expected.cookies()))); } |
### Question:
UrlDecoder { static Url decodeUrl(UnwiseCharsEncoder unwiseCharEncoder, HttpRequest request) { String host = request.headers().get(HOST); if (request.uri().startsWith("/") && host != null) { URI uri = URI.create("http: return new Url.Builder() .path(uri.getRawPath()) .rawQuery(uri.getRawQuery()) .fragment(uri.getFragment()) .build(); } else { return url(unwiseCharEncoder.encode(request.uri())).build(); } } private UrlDecoder(); }### Answer:
@Test public void decodesOriginForm() { DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/foo"); request.headers().add(HOST, "example.com"); Url url = UrlDecoder.decodeUrl(x -> x, request); assertThat(url.authority(), is(Optional.empty())); assertThat(url.path(), is("/foo")); assertThat(url.encodedUri(), is("/foo")); assertThat(url.isAbsolute(), is(false)); assertThat(url.isRelative(), is(true)); assertThat(url.host(), is(Optional.empty())); assertThat(url.queryParams(), is(emptyMap())); assertThat(url.scheme(), is("")); }
@Test public void exposesPathComponentsWithDoubleSlashSeparators() { DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, " request.headers().add(HOST, "example.com"); Url url = UrlDecoder.decodeUrl(x -> x, request); assertThat(url.authority(), is(Optional.empty())); assertThat(url.path(), is(" assertThat(url.encodedUri(), is(" assertThat(url.isAbsolute(), is(false)); assertThat(url.isRelative(), is(true)); assertThat(url.host(), is(Optional.empty())); assertThat(url.queryParams(), is(emptyMap())); assertThat(url.scheme(), is("")); }
@Test public void decodesOriginFormWithUppercaseHostHeader() { DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/foo"); request.headers().add("HOST", "example.com"); Url url = UrlDecoder.decodeUrl(x -> x, request); assertThat(url.authority(), is(Optional.empty())); assertThat(url.path(), is("/foo")); assertThat(url.encodedUri(), is("/foo")); assertThat(url.isAbsolute(), is(false)); assertThat(url.isRelative(), is(true)); assertThat(url.host(), is(Optional.empty())); assertThat(url.queryParams(), is(emptyMap())); assertThat(url.scheme(), is("")); }
@Test public void decodesAbsoluteForm() { DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http: Url url = UrlDecoder.decodeUrl(x -> x, request); assertThat(url.authority().isPresent(), is(true)); assertThat(url.path(), is("/foo")); assertThat(url.encodedUri(), is("http: assertThat(url.isAbsolute(), is(true)); assertThat(url.isRelative(), is(false)); assertThat(url.host(), is(Optional.of("example.com"))); assertThat(url.queryParams(), is(emptyMap())); assertThat(url.scheme(), is("http")); } |
### Question:
ChannelStatisticsHandler extends ChannelDuplexHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { receivedBytesCount.inc(((ByteBuf) msg).readableBytes()); } else if (msg instanceof ByteBufHolder) { receivedBytesCount.inc(((ByteBufHolder) msg).content().readableBytes()); } else { LOGGER.warn(format("channelRead(): Expected byte buffers, but got [%s]", msg)); } super.channelRead(ctx, msg); } ChannelStatisticsHandler(MetricRegistry metricRegistry); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void channelUnregistered(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise); }### Answer:
@Test public void countsReceivedBytes() throws Exception { ByteBuf buf = httpRequestAsBuf(POST, "/foo/bar", "Hello, world"); this.handler.channelRead(mock(ChannelHandlerContext.class), buf); assertThat(countOf("connections.bytes-received"), is((long) buf.readableBytes())); } |
### Question:
ChannelStatisticsHandler extends ChannelDuplexHandler { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof ByteBuf) { sentBytesCount.inc(((ByteBuf) msg).readableBytes()); } else if (msg instanceof ByteBufHolder) { sentBytesCount.inc(((ByteBufHolder) msg).content().readableBytes()); } super.write(ctx, msg, promise); } ChannelStatisticsHandler(MetricRegistry metricRegistry); @Override void channelRegistered(ChannelHandlerContext ctx); @Override void channelUnregistered(ChannelHandlerContext ctx); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void channelRead(ChannelHandlerContext ctx, Object msg); @Override void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise); }### Answer:
@Test public void countsSentBytes() throws Exception { ByteBuf buf = httpResponseAsBuf(OK, "Response from server"); this.handler.write(mock(ChannelHandlerContext.class), buf, mock(ChannelPromise.class)); assertThat(countOf("connections.bytes-sent"), is((long) buf.readableBytes())); } |
### Question:
HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { private static HttpResponseStatus status(Throwable exception) { return EXCEPTION_STATUSES.statusFor(exception) .orElseGet(() -> { if (exception instanceof DecoderException) { Throwable cause = exception.getCause(); if (cause instanceof BadRequestException) { if (cause.getCause() instanceof TooLongFrameException) { return REQUEST_ENTITY_TOO_LARGE; } return BAD_REQUEST; } } else if (exception instanceof TransportLostException) { return BAD_GATEWAY; } return INTERNAL_SERVER_ERROR; }); } private HttpPipelineHandler(Builder builder, RequestTracker tracker); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer:
@Test public void mapsUnrecoverableInternalErrorsToInternalServerError500ResponseCode() { HttpHandler handler = (request, context) -> { throw new RuntimeException("Forced exception for testing"); }; EmbeddedChannel channel = buildEmbeddedChannel(handlerWithMocks(handler)); channel.writeInbound(httpRequestAsBuf(GET, "http: DefaultHttpResponse response = (DefaultHttpResponse) channel.readOutbound(); assertThat(response.status(), is(io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR)); verify(responseEnhancer).enhance(any(LiveHttpResponse.Transformer.class), any(LiveHttpRequest.class)); verify(errorListener, only()).proxyErrorOccurred(any(LiveHttpRequest.class), any(InetSocketAddress.class), eq(INTERNAL_SERVER_ERROR), any(RuntimeException.class)); } |
### Question:
HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { eventProcessor.submit(new ChannelExceptionEvent(ctx, cause)); } private HttpPipelineHandler(Builder builder, RequestTracker tracker); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer:
@Test public void requestTimeoutExceptionOccursInAcceptingRequestsStateAndTcpConnectionRemainsActive() throws Exception { RuntimeException cause = new RequestTimeoutException("timeout occurred"); handler.exceptionCaught(ctx, cause); verify(errorListener).proxyErrorOccurred(REQUEST_TIMEOUT, cause); verify(responseEnhancer).enhance(any(LiveHttpResponse.Transformer.class), eq(null)); verify(responseWriter).write(response(REQUEST_TIMEOUT) .header(CONTENT_LENGTH, 15) .header(CONNECTION, "close") .build()); }
@Test public void tooLongFrameExceptionOccursInIdleStateAndTcpConnectionRemainsActive() throws Exception { setupHandlerTo(WAITING_FOR_RESPONSE); RuntimeException cause = new DecoderException("timeout occurred", new BadRequestException("bad request", new TooLongFrameException("too long frame"))); handler.exceptionCaught(ctx, cause); verify(errorListener).proxyErrorOccurred(REQUEST_ENTITY_TOO_LARGE, cause); verify(responseEnhancer).enhance(any(LiveHttpResponse.Transformer.class), eq(request)); verify(responseWriter).write(response(REQUEST_ENTITY_TOO_LARGE) .header(CONTENT_LENGTH, 24) .header(CONNECTION, "close") .build()); }
@Test public void badRequestExceptionExceptionOccursInIdleStateAndTcpConnectionRemainsActive() throws Exception { setupHandlerTo(WAITING_FOR_RESPONSE); RuntimeException cause = new DecoderException("timeout occurred", new BadRequestException("bad request", new RuntimeException("random bad request failure"))); handler.exceptionCaught(ctx, cause); verify(errorListener).proxyErrorOccurred(BAD_REQUEST, cause); verify(responseEnhancer).enhance(any(LiveHttpResponse.Transformer.class), eq(request)); verify(responseWriter).write(response(BAD_REQUEST) .header(CONTENT_LENGTH, 11) .header(CONNECTION, "close") .build()); }
@Test public void requestTimeoutExceptionOccursInWaitingForResponseStateAndTcpConnectionRemainsActive() throws Exception { setupHandlerTo(WAITING_FOR_RESPONSE); RuntimeException cause = new RequestTimeoutException("timeout occurred"); handler.exceptionCaught(ctx, cause); verify(errorListener).proxyErrorOccurred(REQUEST_TIMEOUT, cause); responseWriter.write(response(REQUEST_TIMEOUT).build()); }
@Test public void tooLongFrameExceptionOccursInWaitingForResponseStateAndTcpConnectionRemainsActive() throws Exception { setupHandlerTo(WAITING_FOR_RESPONSE); RuntimeException cause = new DecoderException("timeout occurred", new BadRequestException("bad request", new TooLongFrameException("too long frame"))); handler.exceptionCaught(ctx, cause); verify(errorListener).proxyErrorOccurred(REQUEST_ENTITY_TOO_LARGE, cause); responseWriter.write(response(REQUEST_ENTITY_TOO_LARGE).build()); }
@Test public void badRequestExceptionExceptionOccursInWaitingForResponseStateAndTcpConnectionRemainsActive() throws Exception { setupHandlerTo(WAITING_FOR_RESPONSE); RuntimeException cause = new DecoderException("timeout occurred", new BadRequestException("bad request", new RuntimeException("random bad request failure"))); handler.exceptionCaught(ctx, cause); verify(errorListener).proxyErrorOccurred(BAD_REQUEST, cause); responseWriter.write(response(BAD_REQUEST).build()); } |
### Question:
HttpPipelineHandler extends SimpleChannelInboundHandler<LiveHttpRequest> { @VisibleForTesting State state() { return this.stateMachine.currentState(); } private HttpPipelineHandler(Builder builder, RequestTracker tracker); @Override void channelActive(ChannelHandlerContext ctx); @Override void channelInactive(ChannelHandlerContext ctx); @Override void exceptionCaught(ChannelHandlerContext ctx, Throwable cause); }### Answer:
@Test public void responseObservableEmitsErrorInWaitingForResponseState() throws Exception { setupHandlerTo(WAITING_FOR_RESPONSE); responseObservable.onError(new RuntimeException("Request Send Error")); assertThat(responseUnsubscribed.get(), is(true)); writerFuture.complete(null); verify(statsCollector).onComplete(request.id(), 500); assertThat(handler.state(), is(TERMINATED)); }
@Test public void responseObservableEmitsErrorInSendingResponseState() throws Exception { setupHandlerTo(SENDING_RESPONSE); responseObservable.onError(new RuntimeException("Spurious error occurred")); assertThat(handler.state(), is(SENDING_RESPONSE)); verify(errorListener).proxyingFailure(any(LiveHttpRequest.class), any(LiveHttpResponse.class), any(Throwable.class)); }
@Test public void responseWriteFailsInSendingResponseState() throws Exception { RuntimeException cause = new RuntimeException("Response write failed"); setupHandlerTo(SENDING_RESPONSE); writerFuture.completeExceptionally(cause); assertThat(responseUnsubscribed.get(), is(true)); verify(statsCollector).onTerminate(request.id()); verify(errorListener).proxyWriteFailure(any(LiveHttpRequest.class), eq(response(OK).build()), any(RuntimeException.class)); assertThat(handler.state(), is(TERMINATED)); } |
### Question:
StyxToNettyResponseTranslator implements ResponseTranslator { public HttpResponse toNettyResponse(LiveHttpResponse httpResponse) { io.netty.handler.codec.http.HttpVersion version = toNettyVersion(httpResponse.version()); HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(httpResponse.status().code()); DefaultHttpResponse nettyResponse = new DefaultHttpResponse(version, httpResponseStatus, true); httpResponse.headers().forEach(httpHeader -> nettyResponse.headers().add(httpHeader.name(), httpHeader.value())); return nettyResponse; } HttpResponse toNettyResponse(LiveHttpResponse httpResponse); }### Answer:
@Test public void shouldCreateNettyResponseWithoutHeaders() throws Exception { LiveHttpResponse styxResponse = new LiveHttpResponse.Builder(OK) .version(HTTP_1_1) .build(); io.netty.handler.codec.http.HttpResponse nettyResponse = translator.toNettyResponse(styxResponse); assertThat(nettyResponse.status(), equalTo(io.netty.handler.codec.http.HttpResponseStatus.OK)); assertThat(nettyResponse.protocolVersion(), equalTo(io.netty.handler.codec.http.HttpVersion.HTTP_1_1)); }
@Test public void shouldCreateNettyResponseWithHostHeader() { LiveHttpResponse styxResponse = new LiveHttpResponse.Builder(OK) .header("Host", "localhost") .build(); io.netty.handler.codec.http.HttpResponse nettyResponse = translator.toNettyResponse(styxResponse); assertTrue(nettyResponse.headers().containsValue("Host", "localhost", false)); }
@Test public void shouldCreateNettyResponseWithCookieWithAttributes() { ResponseCookie cookie = responseCookie("cookie-test", "cookie-value") .domain("cookie-domain") .path("cookie-path") .maxAge(1234) .httpOnly(true) .secure(true) .build(); LiveHttpResponse styxResponse = new LiveHttpResponse.Builder(OK) .cookies(cookie) .build(); io.netty.handler.codec.http.HttpResponse nettyResponse = translator.toNettyResponse(styxResponse); String setCookie = nettyResponse.headers().get(SET_COOKIE); Cookie nettyCookie = ClientCookieDecoder.LAX.decode(setCookie); assertThat(nettyCookie.name(), is("cookie-test")); assertThat(nettyCookie.value(), is("cookie-value")); assertThat(nettyCookie.domain(), is("cookie-domain")); assertThat(nettyCookie.maxAge(), is(1234L)); assertThat(nettyCookie.isHttpOnly(), is(true)); assertThat(nettyCookie.isSecure(), is(true)); } |
### Question:
ExceptionStatusMapper { Optional<HttpResponseStatus> statusFor(Throwable throwable) { List<HttpResponseStatus> matchingStatuses = this.multimap.entries().stream() .filter(entry -> entry.getValue().isInstance(throwable)) .sorted(comparing(entry -> entry.getKey().code())) .map(Map.Entry::getKey) .collect(toList()); if (matchingStatuses.size() > 1) { LOG.error("Multiple matching statuses for throwable={} statuses={}", throwable, matchingStatuses); return Optional.empty(); } return matchingStatuses.stream().findFirst(); } private ExceptionStatusMapper(Builder builder); }### Answer:
@Test public void returnsEmptyIfNoStatusMatches() { assertThat(mapper.statusFor(new UnmappedException()), isAbsent()); }
@Test public void retrievesStatus() { assertThat(mapper.statusFor(new Exception1()), isValue(REQUEST_TIMEOUT)); }
@Test public void exceptionMayNotBeMappedToMultipleExceptions() { ExceptionStatusMapper mapper = new ExceptionStatusMapper.Builder() .add(BAD_GATEWAY, Exception1.class) .add(GATEWAY_TIMEOUT, DoubleMappedException.class) .build(); LoggingTestSupport support = new LoggingTestSupport(ExceptionStatusMapper.class); Optional<HttpResponseStatus> status; try { status = mapper.statusFor(new DoubleMappedException()); } finally { assertThat(support.lastMessage(), is(loggingEvent(ERROR, "Multiple matching statuses for throwable=" + quote(DoubleMappedException.class.getName()) + " statuses=\\[502 Bad Gateway, 504 Gateway Timeout\\]" ))); } assertThat(status, isAbsent()); } |
### Question:
StaticFileHandler implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { try { return resolveFile(request.path()) .map(ResolvedFile::new) .map(resolvedFile -> HttpResponse.response() .addHeader(CONTENT_TYPE, resolvedFile.mediaType) .body(resolvedFile.content, UTF_8) .build() .stream()) .map(Eventual::of) .orElseGet(() -> new HttpAggregator(NOT_FOUND_HANDLER).handle(request, context)); } catch (IOException e) { return Eventual.of(HttpResponse.response(INTERNAL_SERVER_ERROR).build().stream()); } } StaticFileHandler(File dir); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void should404ForMissingFiles() { assertThat(handle(get("/index.html").build()), hasStatus(NOT_FOUND)); assertThat(handle(get("/notfound.html").build()), hasStatus(NOT_FOUND)); assertThat(handle(get("/foo/bar").build()), hasStatus(NOT_FOUND)); }
@Test public void shouldServeExistingFiles() throws Exception { writeFile("index.html", "Hello world"); writeFile("foo.js", "Blah"); mkdir("/a/b"); writeFile("a/b/good", "hi"); assertThat("asking for /index.html", handle(get("/index.html").build()), hasStatus(OK)); assertThat(handle(get("/foo.js").build()), hasStatus(OK)); assertThat(handle(get("/notfound.html").build()), hasStatus(NOT_FOUND)); assertThat(handle(get("/a/b/good").build()), hasStatus(OK)); assertThat(handle(get("/a/b/bad").build()), hasStatus(NOT_FOUND)); }
@Test public void shouldIgnoreQueryParams() throws Exception { writeFile("index.html", "Hello world"); writeFile("foo.js", "Blah"); mkdir("/a/b"); writeFile("a/b/good", "hi"); assertThat(handle(get("/index.html?foo=x").build()), hasStatus(OK)); assertThat(handle(get("/foo.js?sdfsd").build()), hasStatus(OK)); assertThat(handle(get("/a/b/good?xx").build()), hasStatus(OK)); }
@Test public void shouldDisallowDirectoryTraversals() throws Exception { mkdir("/a/public"); writeFile("a/public/index.html", "hi"); mkdir("/a/private"); writeFile("a/private/index.html", "hi"); handler = new StaticFileHandler(new File(dir, "/a/public")); assertThat(handle(get("/index.html").build()), hasStatus(OK)); assertThat(handle(get("/../private/index.html").build()), hasStatus(NOT_FOUND)); }
@Test public void shouldDisallowDirectoryTraversalsWithEncodedRequests() throws Exception { mkdir("/a/public"); writeFile("a/public/index.html", "hi"); mkdir("/a/private"); writeFile("a/private/index.html", "hi"); handler = new StaticFileHandler(new File(dir, "/a/public")); assertThat(handle(get("/index.html").build()), hasStatus(OK)); assertThat(handle(get("/%2e%2e%2fprivate/index.html").build()), hasStatus(NOT_FOUND)); } |
### Question:
CurrentRequestTracker implements RequestTracker { public void trackRequest(LiveHttpRequest request, Supplier<String> state) { if (currentRequests.containsKey(request.id())) { currentRequests.get(request.id()).setCurrentThread(Thread.currentThread()); } else { currentRequests.put(request.id(), new CurrentRequest(request, state)); } } void trackRequest(LiveHttpRequest request, Supplier<String> state); void trackRequest(LiveHttpRequest request); void markRequestAsSent(LiveHttpRequest request); void endTrack(LiveHttpRequest request); Collection<CurrentRequest> currentRequests(); static final CurrentRequestTracker INSTANCE; }### Answer:
@Test public void testTrackRequest() { tracker.trackRequest(req1); assertThat(tracker.currentRequests().iterator().next().request(), is(req1.toString())); } |
### Question:
CurrentRequestTracker implements RequestTracker { public void endTrack(LiveHttpRequest request) { currentRequests.remove(request.id()); } void trackRequest(LiveHttpRequest request, Supplier<String> state); void trackRequest(LiveHttpRequest request); void markRequestAsSent(LiveHttpRequest request); void endTrack(LiveHttpRequest request); Collection<CurrentRequest> currentRequests(); static final CurrentRequestTracker INSTANCE; }### Answer:
@Test public void testEndTrack() { tracker.trackRequest(req1); assertThat(tracker.currentRequests().size(), is(1)); assertThat(tracker.currentRequests().iterator().next().request(), is(req1.toString())); tracker.endTrack(req1); assertThat(tracker.currentRequests().size(), is(0)); } |
### Question:
RequestStatsCollector implements RequestProgressListener { @Override public void onRequest(Object requestId) { Long previous = this.ongoingRequests.putIfAbsent(requestId, nanoClock.nanoTime()); if (previous == null) { this.outstandingRequests.inc(); this.requestsIncoming.mark(); } } RequestStatsCollector(MetricRegistry metrics); RequestStatsCollector(MetricRegistry metrics, NanoClock nanoClock); @Override void onRequest(Object requestId); @Override void onComplete(Object requestId, int responseStatus); @Override void onTerminate(Object requestId); }### Answer:
@Test public void ignoresAdditionalCallsToOnRequestWithSameRequestId() { sink.onRequest(requestId); assertThat(metrics.counter("outstanding").getCount(), is(1L)); sink.onRequest(requestId); assertThat(metrics.counter("outstanding").getCount(), is(1L)); } |
### Question:
PathTrie { public void put(String path, T value) { checkNotEmpty(path); requireNonNull(value); List<String> components = pathToComponents(Paths.get(removeAsterisk(path))); if (path.endsWith("/") || path.endsWith("/*")) { components.add("/"); } T existing = tree.getExactMatch(components); if (existing != null) { String message = format("Path '%s' has already been configured with a ID of [%s]", path, existing.toString()); throw new DuplicatePathException(message); } tree.addValueWithParents(components, value); } PathTrie(); void put(String path, T value); Optional<T> get(String path); T remove(String path); void printContent(); }### Answer:
@Test public void failWhenIdenticalPathsConfigured() { PathTrie<Integer> pathTrie = new PathTrie<>(); pathTrie.put("/a/b/c", 1); assertThrows(DuplicatePathException.class, () -> pathTrie.put("/a/b/c", 2)); }
@Test public void failWhenIdenticalPathsConfiguredWithStar() { PathTrie<Integer> pathTrie = new PathTrie<>(); pathTrie.put("/a/b/c/", 1); assertThrows(DuplicatePathException.class, () -> pathTrie.put("/a/b/c/*", 2)); }
@Test public void failWhenIdenticalPathsConfiguredInRoot() { PathTrie<Integer> pathTrie = new PathTrie<>(); pathTrie.put("/", 1); assertThrows(DuplicatePathException.class, () -> pathTrie.put("/", 2)); }
@Test public void failWhenIdenticalPathsConfiguredInRootWithStar() { PathTrie<Integer> pathTrie = new PathTrie<>(); pathTrie.put("/", 1); assertThrows(DuplicatePathException.class, () -> pathTrie.put("/*", 2)); }
@Test public void failWhenPathIsNull() { PathTrie<Integer> pathTrie = new PathTrie<>(); assertThrows(IllegalArgumentException.class, () -> pathTrie.put(null, 1)); }
@Test public void failWhenPathIsEmpty() { PathTrie<Integer> pathTrie = new PathTrie<>(); assertThrows(IllegalArgumentException.class, () -> pathTrie.put("", 1)); }
@Test public void failWhenValueIsNull() { PathTrie<Integer> pathTrie = new PathTrie<>(); assertThrows(NullPointerException.class, () -> pathTrie.put("/", null)); } |
### Question:
CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyErrorOccurred(Throwable cause) { listeners.forEach(listener -> listener.proxyErrorOccurred(cause)); } CompositeHttpErrorStatusListener(List<HttpErrorStatusListener> listeners); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); }### Answer:
@Test public void propagatesProxyErrorsWithCause() { IOException cause = new IOException(); listener.proxyErrorOccurred(cause); verify(delegate1).proxyErrorOccurred(cause); verify(delegate2).proxyErrorOccurred(cause); verify(delegate3).proxyErrorOccurred(cause); }
@Test public void propagatesProxyErrorsWithStatusAndCause() { IOException cause = new IOException(); listener.proxyErrorOccurred(INTERNAL_SERVER_ERROR, cause); verify(delegate1).proxyErrorOccurred(INTERNAL_SERVER_ERROR, cause); verify(delegate2).proxyErrorOccurred(INTERNAL_SERVER_ERROR, cause); verify(delegate3).proxyErrorOccurred(INTERNAL_SERVER_ERROR, cause); }
@Test public void propagatesProxyErrorsWithRequests() { LiveHttpRequest request = LiveHttpRequest.get("/foo").build(); IOException cause = new IOException(); InetSocketAddress clientAddress = InetSocketAddress.createUnresolved("127.0.0.1", 0); listener.proxyErrorOccurred(request, clientAddress, INTERNAL_SERVER_ERROR, cause); verify(delegate1).proxyErrorOccurred(request, clientAddress, INTERNAL_SERVER_ERROR, cause); verify(delegate2).proxyErrorOccurred(request, clientAddress, INTERNAL_SERVER_ERROR, cause); verify(delegate3).proxyErrorOccurred(request, clientAddress, INTERNAL_SERVER_ERROR, cause); } |
### Question:
CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause) { listeners.forEach(listener -> listener.proxyWriteFailure(request, response, cause)); } CompositeHttpErrorStatusListener(List<HttpErrorStatusListener> listeners); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); }### Answer:
@Test public void propagatesProxyWriteFailures() { IOException cause = new IOException(); listener.proxyWriteFailure(request, response, cause); verify(delegate1).proxyWriteFailure(request, response, cause); verify(delegate2).proxyWriteFailure(request, response, cause); verify(delegate3).proxyWriteFailure(request, response, cause); } |
### Question:
CompositeHttpErrorStatusListener implements HttpErrorStatusListener { @Override public void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause) { listeners.forEach(listener -> listener.proxyingFailure(request, response, cause)); } CompositeHttpErrorStatusListener(List<HttpErrorStatusListener> listeners); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); }### Answer:
@Test public void propagatesProxyingFailures() { IOException cause = new IOException(); listener.proxyingFailure(request, response, cause); verify(delegate1).proxyingFailure(request, response, cause); verify(delegate2).proxyingFailure(request, response, cause); verify(delegate3).proxyingFailure(request, response, cause); } |
### Question:
AggregateRequestBodyExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return request.aggregate(10000) .map(fullRequest -> { String body = fullRequest.bodyAs(UTF_8); return fullRequest.newBuilder() .body(body + config.extraText(), UTF_8) .build().stream(); }).flatMap(chain::proceed); } AggregateRequestBodyExamplePlugin(Config config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void contentIsModified() { Config config = new Config("MyExtraText"); String originalBody = "OriginalBody"; AggregateRequestBodyExamplePlugin plugin = new AggregateRequestBodyExamplePlugin(config); LiveHttpRequest request = LiveHttpRequest.post("/", ByteStream.from(originalBody, UTF_8)).build(); HttpInterceptor.Chain chain = intRequest -> { String requestBody = Mono.from(intRequest.aggregate(100)).block().bodyAs(UTF_8); assertThat(requestBody, is(originalBody + config.extraText())); return Eventual.of(LiveHttpResponse.response().build()); }; Mono.from(plugin.intercept(request, chain)).block(); } |
### Question:
ReplaceLiveContentExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(request) .map(response -> response.newBuilder() .body(body -> body.replaceWith(ByteStream.from(config.replacement(), UTF_8))) .build()); } ReplaceLiveContentExamplePlugin(ReplaceLiveContentExampleConfig config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void replacesLiveContent() { ReplaceLiveContentExampleConfig config = new ReplaceLiveContentExampleConfig("myNewContent"); ReplaceLiveContentExamplePlugin plugin = new ReplaceLiveContentExamplePlugin(config); LiveHttpRequest request = get("/").build(); HttpInterceptor.Chain chain = request1 -> Eventual.of(LiveHttpResponse.response().build()); HttpResponse response = Mono.from(plugin.intercept(request, chain) .flatMap(liveResponse -> liveResponse.aggregate(100))) .block(); assertThat(response.bodyAs(UTF_8), is("myNewContent")); } |
### Question:
ModifyHeadersExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { LiveHttpRequest newRequest = request.newBuilder() .header("myRequestHeader", config.requestHeaderValue()) .build(); return chain.proceed(newRequest).map(response -> response.newBuilder() .header("myResponseHeader", config.responseHeaderValue()) .build() ); } ModifyHeadersExamplePlugin(ModifyHeadersExamplePluginConfig config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); @Override Map<String, HttpHandler> adminInterfaceHandlers(); }### Answer:
@Test public void addsExtraHeaders() { HttpInterceptor.Chain chain = request -> { assertThat(request.header("myRequestHeader").orElse(null), is("foo")); return Eventual.of(response(OK).build()); }; LiveHttpRequest request = get("/foo") .build(); LiveHttpResponse response = Mono.from(plugin.intercept(request, chain)).block(); assertThat(response.header("myResponseHeader").orElse(null), is("bar")); } |
### Question:
ModifyContentByAggregationExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(request) .flatMap(response -> response.aggregate(10000)) .map(response -> { String body = response.bodyAs(UTF_8); return response.newBuilder() .body(body + config.extraText(), UTF_8) .build(); }) .map(HttpResponse::stream); } ModifyContentByAggregationExamplePlugin(Config config); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void modifiesContent() { Config config = new Config("MyExtraText"); ModifyContentByAggregationExamplePlugin plugin = new ModifyContentByAggregationExamplePlugin(config); LiveHttpRequest request = get("/").build(); HttpInterceptor.Chain chain = anyRequest -> Eventual.of(response() .body("OriginalBody", UTF_8) .build() .stream()); HttpResponse response = Mono.from(plugin.intercept(request, chain) .flatMap(liveResponse -> liveResponse.aggregate(100))) .block(); assertThat(response.bodyAs(UTF_8), is("OriginalBodyMyExtraText")); } |
### Question:
EarlyReturnExamplePlugin implements Plugin { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { if (request.header("X-Respond").isPresent()) { return Eventual.of(HttpResponse.response(OK) .header(CONTENT_TYPE, "text/plain; charset=utf-8") .body("Responding from plugin", UTF_8) .build() .stream()); } else { return chain.proceed(request); } } @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void returnsEarlyWhenHeaderIsPresent() { EarlyReturnExamplePlugin plugin = new EarlyReturnExamplePlugin(); LiveHttpRequest request = LiveHttpRequest.get("/") .header("X-Respond", "foo") .build(); HttpInterceptor.Chain chain = request1 -> Eventual.of(LiveHttpResponse.response().build()); Eventual<LiveHttpResponse> eventualLive = plugin.intercept(request, chain); Eventual<HttpResponse> eventual = eventualLive.flatMap(response -> response.aggregate(100)); HttpResponse response = Mono.from(eventual).block(); assertThat(response.bodyAs(UTF_8), is("Responding from plugin")); } |
### Question:
HttpErrorStatusCauseLogger implements HttpErrorStatusListener { @Override public void proxyErrorOccurred(HttpResponseStatus status, Throwable cause) { if (status.code() > 500) { LOG.error("Failure status=\"{}\", exception=\"{}\"", status, withoutStackTrace(cause)); } else { LOG.error("Failure status=\"{}\"", status, cause); } } HttpErrorStatusCauseLogger(HttpMessageFormatter formatter); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); }### Answer:
@Test public void logsThrowables() { Exception exception = new Exception("This is just a test"); httpErrorStatusCauseLogger.proxyErrorOccurred(INTERNAL_SERVER_ERROR, exception); assertThat(loggingTestSupport.log(), hasItem( loggingEvent( ERROR, "Failure status=\"500 Internal Server Error\"", "java.lang.Exception", "This is just a test"))); }
@Test public void logsThrowablesWithStatus5xxExcluding500WithoutStackTrace() { Exception exception = new Exception("This is just a test"); httpErrorStatusCauseLogger.proxyErrorOccurred(BAD_GATEWAY, exception); assertThat(loggingTestSupport.log(), hasItem( loggingEvent( ERROR, "Failure status=\"502 Bad Gateway\", exception=\"java.lang.Exception.*This is just a test.*\""))); }
@Test public void logsInternalServerErrorWithRequest() { LiveHttpRequest request = LiveHttpRequest.get("/foo").build(); Exception exception = new Exception("This is just a test"); httpErrorStatusCauseLogger.proxyErrorOccurred(request, InetSocketAddress.createUnresolved("localhost", 80), INTERNAL_SERVER_ERROR, exception); assertThat(loggingTestSupport.log(), hasItem( loggingEvent( ERROR, "Failure status=\"500 Internal Server Error\" during request=" + FORMATTED_REQUEST + ", clientAddress=localhost:80", "java.lang.Exception", "This is just a test"))); }
@Test public void logsOtherExceptionsWithoutRequest() { LiveHttpRequest request = LiveHttpRequest.get("/foo").build(); Exception exception = new Exception("This is just a test"); httpErrorStatusCauseLogger.proxyErrorOccurred(request, InetSocketAddress.createUnresolved("127.0.0.1", 0), BAD_GATEWAY, exception); assertThat(loggingTestSupport.log(), hasItem( loggingEvent( ERROR, "Failure status=\"502 Bad Gateway\", exception=\"java.lang.Exception.*This is just a test.*\""))); } |
### Question:
InterceptorPipelineBuilder { public RoutingObject build() { List<HttpInterceptor> interceptors = ImmutableList.copyOf(instrument(plugins, environment)); return new HttpInterceptorPipeline(interceptors, handler, trackRequests); } InterceptorPipelineBuilder(Environment environment, Iterable<NamedPlugin> plugins, RoutingObject handler, boolean trackRequests); RoutingObject build(); }### Answer:
@Test public void buildsPipelineWithInterceptors() throws Exception { HttpHandler pipeline = new InterceptorPipelineBuilder(environment, plugins, handler, false).build(); LiveHttpResponse response = Mono.from(pipeline.handle(get("/foo").build(), requestContext())).block(); assertThat(response.header("plug1"), isValue("1")); assertThat(response.header("plug2"), isValue("1")); assertThat(response.status(), is(OK)); } |
### Question:
HttpErrorStatusMetrics implements HttpErrorStatusListener { @Override public void proxyErrorOccurred(HttpResponseStatus status, Throwable cause) { record(status); if (isError(status)) { incrementExceptionCounter(cause, status); } } HttpErrorStatusMetrics(MetricRegistry metricRegistry); @Override void proxyErrorOccurred(HttpResponseStatus status, Throwable cause); @Override void proxyErrorOccurred(Throwable cause); @Override void proxyErrorOccurred(LiveHttpRequest request, InetSocketAddress clientAddress, HttpResponseStatus status, Throwable cause); @Override void proxyWriteFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); @Override void proxyingFailure(LiveHttpRequest request, LiveHttpResponse response, Throwable cause); }### Answer:
@Test public void pluginExceptionsAreNotRecordedAsStyxUnexpectedErrors() { errorListener.proxyErrorOccurred(INTERNAL_SERVER_ERROR, new PluginException("bad")); assertThat(count("styx.response.status.500"), is(1)); assertThat(statusCountsExcluding("styx.response.status.500"), everyItem(is(0))); assertThat(meterCount("styx.errors"), is(0)); }
@Test public void nonErrorStatusesIsNotRecordedForProxyEvenIfExceptionIsSupplied() { MetricRegistry registry = mock(MetricRegistry.class); HttpErrorStatusMetrics reporter = new HttpErrorStatusMetrics(registry); reset(registry); reporter.proxyErrorOccurred(OK, new RuntimeException("This shouldn't happen")); verifyZeroInteractions(registry); } |
### Question:
ViaHeaderAppendingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { LiveHttpRequest newRequest = request.newBuilder() .header(VIA, viaHeader(request)) .build(); return chain.proceed(newRequest) .map(response -> response.newBuilder() .header(VIA, viaHeader(response)) .build()); } ViaHeaderAppendingInterceptor(); ViaHeaderAppendingInterceptor(final String via); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void appendsHttp10RequestVersionInResponseViaHeader() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), ANY_RESPONSE_HANDLER)).block(); assertThat(response.headers().get(VIA), isValue("1.1 styx")); }
@Test public void appendsViaHeaderValueAtEndOfListInResponse() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), returnsResponse(response() .header(VIA, "1.0 ricky, 1.1 mertz, 1.0 lucy") .build()))).block(); assertThat(response.headers().get(VIA), isValue("1.0 ricky, 1.1 mertz, 1.0 lucy, 1.1 styx")); } |
### Question:
RequestEnrichingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(enrich(request, chain.context())); } RequestEnrichingInterceptor(StyxHeaderConfig styxHeaderConfig); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void addsRequestIdToTheHeaders() { requestEnrichingInterceptor.intercept(get("/some-uri").build(), recording); assertThat(recording.recordedRequest().header(REQUEST_ID_DEFAULT), is(notNullValue())); }
@Test public void setsTheRemoteAddressToTheForwardedForList() { requestEnrichingInterceptor.intercept(get("").build(), recording); assertThat(recording.recordedRequest().header(X_FORWARDED_FOR), isValue("127.0.0.1")); }
@Test public void appendsTheRemoteAddressToTheForwardedForList() { requestEnrichingInterceptor.intercept(get("/some") .header(X_FORWARDED_FOR, "172.21.175.59").build(), recording); assertThat(recording.recordedRequest().header(X_FORWARDED_FOR), isValue("172.21.175.59, 127.0.0.1")); }
@Test public void addsXForwardedProtoToHttpWhenAbsent() { requestEnrichingInterceptor.intercept(get("/some").build(), recording); assertThat(recording.recordedRequest().header(X_FORWARDED_PROTO), isValue("http")); }
@Test public void addsXForwardedProtoToHttpsWhenAbsent() { requestEnrichingInterceptor.intercept(get("/some").build(), recordingSecure); assertThat(recordingSecure.recordedRequest().header(X_FORWARDED_PROTO), isValue("https")); }
@Test public void retainsXForwardedProtoWhenPresentInHttpMessage() { requestEnrichingInterceptor.intercept(get("/some").addHeader(X_FORWARDED_PROTO, "https").build(), recording); assertThat(recording.recordedRequest().header(X_FORWARDED_PROTO), isValue("https")); requestEnrichingInterceptor.intercept(get("/some").addHeader(X_FORWARDED_PROTO, "http").build(), recording); assertThat(recording.recordedRequest().header(X_FORWARDED_PROTO), isValue("http")); }
@Test public void retainsXForwardedProtoWhenPresentInHttpsMessage() { requestEnrichingInterceptor.intercept(get("/some").addHeader(X_FORWARDED_PROTO, "http").build(), recording); assertThat(recording.recordedRequest().header(X_FORWARDED_PROTO), isValue("http")); requestEnrichingInterceptor.intercept(get("/some").addHeader(X_FORWARDED_PROTO, "https").build(), recording); assertThat(recording.recordedRequest().header(X_FORWARDED_PROTO), isValue("https")); } |
### Question:
HttpMessageLoggingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { boolean secure = chain.context().isSecure(); logger.logRequest(request, null, secure); return chain.proceed(request).map(response -> { logger.logResponse(request, response, secure); return response; }); } HttpMessageLoggingInterceptor(boolean longFormatEnabled, HttpMessageFormatter httpMessageFormatter); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void logsRequestsAndResponses() { LiveHttpRequest request = get("/") .version(HttpVersion.HTTP_1_1) .header("ReqHeader", "ReqHeaderValue") .cookies(requestCookie("ReqCookie", "ReqCookieValue")) .build(); consume(interceptor.intercept(request, chain( response(OK) .header("RespHeader", "RespHeaderValue") .cookies(responseCookie("RespCookie", "RespCookieValue").build()) ))); assertThat(responseLogSupport.log(), contains( loggingEvent(INFO, "requestId=" + request.id() + ", secure=true, origin=null, request=" + FORMATTED_REQUEST), loggingEvent(INFO, "requestId=" + request.id() + ", secure=true, response=" + FORMATTED_RESPONSE))); }
@Test public void logsRequestsAndResponsesShort() { interceptor = new HttpMessageLoggingInterceptor(false, httpMessageFormatter); LiveHttpRequest request = get("/") .header("ReqHeader", "ReqHeaderValue") .cookies(requestCookie("ReqCookie", "ReqCookieValue")) .build(); consume(interceptor.intercept(request, chain( response(OK) .header("RespHeader", "RespHeaderValue") .cookies(responseCookie("RespCookie", "RespCookieValue").build()) ))); String requestPattern = "request=\\{version=HTTP/1.1, method=GET, uri=/, id=" + request.id() + "\\}"; String responsePattern = "response=\\{version=HTTP/1.1, status=200 OK\\}"; assertThat(responseLogSupport.log(), contains( loggingEvent(INFO, "requestId=" + request.id() + ", secure=true, origin=null, " + requestPattern), loggingEvent(INFO, "requestId=" + request.id() + ", secure=true, " + responsePattern))); }
@Test public void logsSecureRequests() { LiveHttpRequest request = get("/") .header("ReqHeader", "ReqHeaderValue") .cookies(requestCookie("ReqCookie", "ReqCookieValue")) .build(); consume(interceptor.intercept(request, chain(response(OK)))); assertThat(responseLogSupport.log(), contains( loggingEvent(INFO, "requestId=" + request.id() + ", secure=true, origin=null, request=" + FORMATTED_REQUEST), loggingEvent(INFO, "requestId=" + request.id() + ", secure=true, response=" + FORMATTED_RESPONSE))); } |
### Question:
ConfigurationContextResolverInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { Configuration.Context context = configurationContextResolver.resolve(request); chain.context().add("config.context", context); return chain.proceed(request); } ConfigurationContextResolverInterceptor(ConfigurationContextResolver configurationContextResolver); @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void resolvesConfigurationContext() { LiveHttpRequest request = get("/").build(); Configuration.Context context = context(ImmutableMap.of("key1", "value1", "key2", "value2")); ConfigurationContextResolver configurationContextResolver = configurationContextResolver(request, context); ConfigurationContextResolverInterceptor interceptor = new ConfigurationContextResolverInterceptor(configurationContextResolver); TestChain chain = new TestChain(); Eventual<LiveHttpResponse> responseObservable = interceptor.intercept(request, chain); assertThat(Mono.from(responseObservable).block(), hasStatus(OK)); assertThat(chain.proceedWasCalled, is(true)); assertThat(chain.context().get("config.context", Configuration.Context.class), is(context)); } |
### Question:
HopByHopHeadersRemovingInterceptor implements HttpInterceptor { @Override public Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(removeHopByHopHeaders(request)) .map(HopByHopHeadersRemovingInterceptor::removeHopByHopHeaders); } @Override Eventual<LiveHttpResponse> intercept(LiveHttpRequest request, Chain chain); }### Answer:
@Test public void removesHopByHopHeadersFromResponse() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), returnsResponse(response() .header(TE, "foo") .header(PROXY_AUTHENTICATE, "foo") .header(PROXY_AUTHORIZATION, "bar") .build()))).block(); assertThat(response.header(TE), isAbsent()); assertThat(response.header(PROXY_AUTHENTICATE), isAbsent()); assertThat(response.header(PROXY_AUTHORIZATION), isAbsent()); }
@Test public void removesConnectionHeadersFromResponse() throws Exception { LiveHttpResponse response = Mono.from(interceptor.intercept(get("/foo").build(), returnsResponse(response() .header(CONNECTION, "Foo, Bar, Baz") .header("Foo", "abc") .header("Foo", "def") .header("Bar", "one, two, three") .build()))).block(); assertThat(response.header(CONNECTION), isAbsent()); assertThat(response.header("Foo"), isAbsent()); assertThat(response.header("Bar"), isAbsent()); assertThat(response.header("Baz"), isAbsent()); } |
### Question:
FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public CompletableFuture<ReloadResult> reload() { return this.fileBackedRegistry.reload() .thenApply(outcome -> logReloadAttempt("Admin Interface", outcome)); } @VisibleForTesting FileBackedBackendServicesRegistry(FileBackedRegistry<BackendService> fileBackedRegistry, FileMonitor fileChangeMonitor); @VisibleForTesting FileBackedBackendServicesRegistry(Resource originsFile, FileMonitor fileChangeMonitor); static FileBackedBackendServicesRegistry create(String originsFile); @Override Registry<BackendService> addListener(ChangeListener<BackendService> changeListener); @Override Registry<BackendService> removeListener(ChangeListener<BackendService> changeListener); @Override CompletableFuture<ReloadResult> reload(); @Override Iterable<BackendService> get(); @Override CompletableFuture<Void> stop(); @Override void fileChanged(); @Override String toString(); }### Answer:
@Test public void relaysReloadToRegistryDelegate() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); when(delegate.reload()).thenReturn(CompletableFuture.completedFuture(ReloadResult.reloaded("relaod ok"))); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); registry.reload(); verify(delegate).reload(); }
@Test public void reloadsDelegateRegistryOnStart() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); when(delegate.reload()).thenReturn(completedFuture(reloaded("Changes applied!"))); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); await(registry.start()); verify(delegate).reload(); } |
### Question:
FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public Registry<BackendService> addListener(ChangeListener<BackendService> changeListener) { return this.fileBackedRegistry.addListener(changeListener); } @VisibleForTesting FileBackedBackendServicesRegistry(FileBackedRegistry<BackendService> fileBackedRegistry, FileMonitor fileChangeMonitor); @VisibleForTesting FileBackedBackendServicesRegistry(Resource originsFile, FileMonitor fileChangeMonitor); static FileBackedBackendServicesRegistry create(String originsFile); @Override Registry<BackendService> addListener(ChangeListener<BackendService> changeListener); @Override Registry<BackendService> removeListener(ChangeListener<BackendService> changeListener); @Override CompletableFuture<ReloadResult> reload(); @Override Iterable<BackendService> get(); @Override CompletableFuture<Void> stop(); @Override void fileChanged(); @Override String toString(); }### Answer:
@Test public void relaysAddListenerToRegistryDelegate() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); Registry.ChangeListener<BackendService> listener = mock(Registry.ChangeListener.class); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); registry.addListener(listener); verify(delegate).addListener(eq(listener)); } |
### Question:
FileBackedBackendServicesRegistry extends AbstractStyxService implements Registry<BackendService>, FileChangeMonitor.Listener { @Override public Iterable<BackendService> get() { return this.fileBackedRegistry.get(); } @VisibleForTesting FileBackedBackendServicesRegistry(FileBackedRegistry<BackendService> fileBackedRegistry, FileMonitor fileChangeMonitor); @VisibleForTesting FileBackedBackendServicesRegistry(Resource originsFile, FileMonitor fileChangeMonitor); static FileBackedBackendServicesRegistry create(String originsFile); @Override Registry<BackendService> addListener(ChangeListener<BackendService> changeListener); @Override Registry<BackendService> removeListener(ChangeListener<BackendService> changeListener); @Override CompletableFuture<ReloadResult> reload(); @Override Iterable<BackendService> get(); @Override CompletableFuture<Void> stop(); @Override void fileChanged(); @Override String toString(); }### Answer:
@Test public void relaysGetToRegistryDelegate() { FileBackedRegistry<BackendService> delegate = mock(FileBackedRegistry.class); registry = new FileBackedBackendServicesRegistry(delegate, FileMonitor.DISABLED); registry.get(); verify(delegate).get(); } |
### Question:
FileChangeMonitor implements FileMonitor { @Override public void start(Listener listener) { LOGGER.debug("start, initialDelay={}, pollPeriod={}", new Object[] {initialDelay, pollPeriod}); synchronized (this) { if (monitoredTask != null) { String message = format("File monitor for '%s' is already started", monitoredFile); throw new IllegalStateException(message); } monitoredTask = executor.scheduleAtFixedRate( detectFileChangesTask(listener), initialDelay.toMillis(), pollPeriod.toMillis(), MILLISECONDS); } } FileChangeMonitor(String monitoredFile, Duration initialDelay, Duration pollPeriod); FileChangeMonitor(String monitoredFile); @Override void start(Listener listener); void stop(); }### Answer:
@Test public void canBeStartedOnlyOnce() { FileChangeMonitor.Listener listener = mock(FileChangeMonitor.Listener.class); FileChangeMonitor monitor = new FileChangeMonitor(monitoredFile.toString()); monitor.start(listener); Exception e = assertThrows(IllegalStateException.class, () -> monitor.start(listener)); assertThat(e.getMessage(), matchesPattern("File monitor for '.*' is already started")); }
@Test public void initialPollNotifiesListeners() { monitor.start(listener); verify(listener, timeout(3000).times(1)).fileChanged(); }
@Test public void notifiesListenersOnFileChange() throws Exception { monitor.start(listener); verify(listener, timeout(3000).times(1)).fileChanged(); Thread.sleep(250); for (int i = 2; i < 10; i++) { write(monitoredFile, format("content-v%d", i)); verify(listener, timeout(3000).times(i)).fileChanged(); LOGGER.info(format("verified v%d", i)); } }
@Test public void recoversFromFileDeletions() throws Exception { monitor.start(listener); verify(listener, timeout(3000).times(1)).fileChanged(); delete(monitoredFile); Thread.sleep(2000); write(monitoredFile, "some new content"); verify(listener, timeout(3000).times(2)).fileChanged(); }
@Test public void detectsFileSizeChanges() throws Exception { monitor.start(listener); verify(listener, timeout(3000).times(1)).fileChanged(); }
@Test public void recoversFromTruncatedFiles() throws Exception { monitor.start(listener); verify(listener, timeout(3000).times(1)).fileChanged(); write(monitoredFile, ""); verify(listener, timeout(3000).times(2)).fileChanged(); write(monitoredFile, "some new content"); verify(listener, timeout(3000).times(3)).fileChanged(); } |
### Question:
HealthCheckTimestamp extends HealthCheck { @Override protected Result check() { ZonedDateTime now = Instant.ofEpochMilli(clock.tickMillis()).atZone(UTC); return healthy(DATE_TIME_FORMATTER.format(now)); } HealthCheckTimestamp(); HealthCheckTimestamp(Clock clock); static final String NAME; }### Answer:
@Test public void printsTheCurrentTime() throws Exception { assertThat(healthCheckTimestamp.check().toString(), matchesRegex( "Result\\{isHealthy=true, message=1970-01-01T00:00:00.001\\+0000, timestamp=.*\\}")); } |
### Question:
PathPrefixRouter implements RoutingObject { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { String path = request.path(); for (PrefixRoute route : routes) { if (path.startsWith(route.prefix)) { return route.routingObject.handle(request, context); } } return Eventual.error(new NoServiceConfiguredException(path)); } PathPrefixRouter(PrefixRoute[] routes); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); @Override CompletableFuture<Void> stop(); static final Schema.FieldType SCHEMA; }### Answer:
@Test public void no_routes_always_throws_NoServiceConfiguredException() throws Exception { PathPrefixRouter router = buildRouter(emptyMap()); assertThrows(NoServiceConfiguredException.class, () -> Mono.from(router.handle(LiveHttpRequest.get("/").build(), null)).block() ); } |
### Question:
StandardHttpPipeline implements HttpHandler { @Override public Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context) { HttpInterceptorChain interceptorsChain = new HttpInterceptorChain(interceptors, 0, handler, context, requestTracker); return interceptorsChain.proceed(request); } StandardHttpPipeline(HttpHandler handler); StandardHttpPipeline(List<HttpInterceptor> interceptors, HttpHandler handler, RequestTracker requestTracker); @Override Eventual<LiveHttpResponse> handle(LiveHttpRequest request, HttpInterceptor.Context context); }### Answer:
@Test public void sendsExceptionUponMultipleSubscription() { HttpHandler handler = (request, context) -> Eventual.of(response(OK).build()); StandardHttpPipeline pipeline = new StandardHttpPipeline(handler); Eventual<LiveHttpResponse> responseObservable = pipeline.handle(get("/").build(), requestContext()); LiveHttpResponse response = Mono.from(responseObservable).block(); assertThat(response.status(), is(OK)); assertThrows(IllegalStateException.class, () -> Mono.from(responseObservable).block()); } |
### Question:
StyxServerComponents { public List<NamedPlugin> plugins() { return plugins; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjectStore<StyxObjectRecord<StyxService>> servicesDatabase(); StyxObjectStore<StyxObjectRecord<NettyExecutor>> executors(); StyxObjectStore<StyxObjectRecord<InetServer>> serversDatabase(); RoutingObjectFactory.Context routingObjectFactoryContext(); NettyExecutor clientExecutor(); StartupConfig startupConfig(); }### Answer:
@Test public void loadsPlugins() { ConfiguredPluginFactory f1 = new ConfiguredPluginFactory("plugin1", any -> stubPlugin("MyResponse1")); ConfiguredPluginFactory f2 = new ConfiguredPluginFactory("plugin2", any -> stubPlugin("MyResponse2")); StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig()) .pluginFactories(ImmutableList.of(f1, f2)) .build(); List<NamedPlugin> plugins = components.plugins(); List<String> names = plugins.stream().map(NamedPlugin::name).collect(toList()); assertThat(names, contains("plugin1", "plugin2")); } |
### Question:
StyxServerComponents { public Map<String, StyxService> services() { return services; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjectStore<StyxObjectRecord<StyxService>> servicesDatabase(); StyxObjectStore<StyxObjectRecord<NettyExecutor>> executors(); StyxObjectStore<StyxObjectRecord<InetServer>> serversDatabase(); RoutingObjectFactory.Context routingObjectFactoryContext(); NettyExecutor clientExecutor(); StartupConfig startupConfig(); }### Answer:
@Test public void loadsServices() { StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig()) .services((env, routeDb) -> ImmutableMap.of( "service1", mock(StyxService.class), "service2", mock(StyxService.class))) .build(); Map<String, StyxService> services = components.services(); assertThat(services.keySet(), containsInAnyOrder("service1", "service2")); }
@Test public void exposesAdditionalServices() { StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig()) .additionalServices(ImmutableMap.of( "service1", mock(StyxService.class), "service2", mock(StyxService.class))) .build(); Map<String, StyxService> services = components.services(); assertThat(services.keySet(), containsInAnyOrder("service1", "service2")); } |
### Question:
StyxServerComponents { public Environment environment() { return environment; } private StyxServerComponents(Builder builder); boolean showBanner(); Environment environment(); Map<String, StyxService> services(); List<NamedPlugin> plugins(); StyxObjectStore<RoutingObjectRecord> routeDatabase(); StyxObjectStore<StyxObjectRecord<StyxService>> servicesDatabase(); StyxObjectStore<StyxObjectRecord<NettyExecutor>> executors(); StyxObjectStore<StyxObjectRecord<InetServer>> serversDatabase(); RoutingObjectFactory.Context routingObjectFactoryContext(); NettyExecutor clientExecutor(); StartupConfig startupConfig(); }### Answer:
@Test public void createsEnvironment() { Configuration config = new Configuration.MapBackedConfiguration() .set("foo", "abc") .set("bar", "def"); StyxServerComponents components = new StyxServerComponents.Builder() .styxConfig(new StyxConfig(config)) .build(); Environment environment = components.environment(); assertThat(environment.configuration().get("foo", String.class), isValue("abc")); assertThat(environment.configuration().get("bar", String.class), isValue("def")); assertThat(environment.eventBus(), is(notNullValue())); assertThat(environment.metricRegistry(), is(notNullValue())); } |
### Question:
CoreMetrics { public static void registerCoreMetrics(Version buildInfo, MetricRegistry metrics) { registerVersionMetric(buildInfo, metrics); registerJvmMetrics(metrics); metrics.register("os", new OperatingSystemMetricSet()); } private CoreMetrics(); static void registerCoreMetrics(Version buildInfo, MetricRegistry metrics); }### Answer:
@Test public void registersVersionMetric() { MetricRegistry metrics = new CodaHaleMetricRegistry(); CoreMetrics.registerCoreMetrics(version, metrics); Gauge gauge = metrics.getGauges().get("styx.version.buildnumber"); assertThat(gauge.getValue(), is(3)); }
@Test public void registersJvmMetrics() { MetricRegistry metrics = new CodaHaleMetricRegistry(); CoreMetrics.registerCoreMetrics(version, metrics); Map<String, Gauge> gauges = metrics.getGauges(); assertThat(gauges.keySet(), hasItems( "jvm.thread.blocked.count", "jvm.thread.count", "jvm.thread.daemon.count", "jvm.thread.deadlock.count", "jvm.thread.deadlocks", "jvm.thread.new.count", "jvm.thread.runnable.count", "jvm.thread.terminated.count", "jvm.thread.timed_waiting.count", "jvm.thread.waiting.count", "jvm.uptime", "jvm.uptime.formatted" )); }
@Test public void registersOperatingSystemMetrics() { MetricRegistry metrics = new CodaHaleMetricRegistry(); CoreMetrics.registerCoreMetrics(version, metrics); Map<String, Gauge> gauges = metrics.getGauges(); assertThat(gauges.keySet(), hasItems( "os.process.cpu.load", "os.process.cpu.time", "os.system.cpu.load", "os.memory.physical.free", "os.memory.physical.total", "os.memory.virtual.committed", "os.swapSpace.free", "os.swapSpace.total" )); } |
### Question:
WebConfigurer implements ServletContextInitializer, EmbeddedServletContainerCustomizer { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); initMetrics(servletContext, disps); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(ConfigurableEmbeddedServletContainer container); @Bean CorsFilter corsFilter(); @Autowired(required = false) void setMetricRegistry(MetricRegistry metricRegistry); }### Answer:
@Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); }
@Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry); assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry); verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class)); verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class)); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); } |
### Question:
ProcessStartedEventConverter extends BaseEventToEntityConverter { @Override protected ProcessStartedAuditEventEntity createEventEntity(CloudRuntimeEvent cloudRuntimeEvent) { return new ProcessStartedAuditEventEntity((CloudProcessStartedEvent) cloudRuntimeEvent); } ProcessStartedEventConverter(EventContextInfoAppender eventContextInfoAppender); @Override String getSupportedEvent(); }### Answer:
@Test public void createEventEntityShouldSetAllNonProcessContextRelatedFields() { CloudProcessStartedEventImpl event = buildProcessStartedEvent(); ProcessStartedAuditEventEntity auditEventEntity = eventConverter.createEventEntity(event); assertThat(auditEventEntity).isNotNull(); assertThat(auditEventEntity.getEventId()).isEqualTo(event.getId()); assertThat(auditEventEntity.getTimestamp()).isEqualTo(event.getTimestamp()); assertThat(auditEventEntity.getAppName()).isEqualTo(event.getAppName()); assertThat(auditEventEntity.getAppVersion()).isEqualTo(event.getAppVersion()); assertThat(auditEventEntity.getServiceName()).isEqualTo(event.getServiceName()); assertThat(auditEventEntity.getServiceFullName()).isEqualTo(event.getServiceFullName()); assertThat(auditEventEntity.getServiceType()).isEqualTo(event.getServiceType()); assertThat(auditEventEntity.getServiceVersion()).isEqualTo(event.getServiceVersion()); assertThat(auditEventEntity.getMessageId()).isEqualTo(event.getMessageId()); assertThat(auditEventEntity.getSequenceNumber()).isEqualTo(event.getSequenceNumber()); assertThat(auditEventEntity.getProcessInstance()).isEqualTo(event.getEntity()); }
@Test public void convertToEntityShouldReturnCreatedEntity() { ProcessStartedAuditEventEntity auditEventEntity = new ProcessStartedAuditEventEntity(); CloudProcessStartedEventImpl cloudRuntimeEvent = new CloudProcessStartedEventImpl(); doReturn(auditEventEntity).when(eventConverter).createEventEntity(cloudRuntimeEvent); AuditEventEntity convertedEntity = eventConverter.convertToEntity(cloudRuntimeEvent); assertThat(convertedEntity).isEqualTo(auditEventEntity); } |
### Question:
ProcessStartedEventConverter extends BaseEventToEntityConverter { @Override protected CloudRuntimeEventImpl<?, ?> createAPIEvent(AuditEventEntity auditEventEntity) { ProcessStartedAuditEventEntity processStartedAuditEventEntity = (ProcessStartedAuditEventEntity) auditEventEntity; return new CloudProcessStartedEventImpl(processStartedAuditEventEntity.getEventId(), processStartedAuditEventEntity.getTimestamp(), processStartedAuditEventEntity.getProcessInstance()); } ProcessStartedEventConverter(EventContextInfoAppender eventContextInfoAppender); @Override String getSupportedEvent(); }### Answer:
@Test public void convertToAPIShouldCreateAPIEventAndCallEventContextInfoAppender() { ProcessStartedAuditEventEntity auditEventEntity = new ProcessStartedAuditEventEntity(); CloudProcessStartedEventImpl apiEvent = new CloudProcessStartedEventImpl(); doReturn(apiEvent).when(eventConverter).createAPIEvent(auditEventEntity); CloudProcessStartedEventImpl updatedApiEvent = new CloudProcessStartedEventImpl(); given(eventContextInfoAppender.addProcessContextInfoToApiEvent(apiEvent, auditEventEntity)).willReturn(updatedApiEvent); CloudRuntimeEvent convertedEvent = eventConverter.convertToAPI(auditEventEntity); assertThat(convertedEvent).isEqualTo(updatedApiEvent); verify(eventContextInfoAppender).addProcessContextInfoToApiEvent(apiEvent, auditEventEntity); } |
### Question:
AuditConsumerChannelHandlerImpl implements AuditConsumerChannelHandler { @SuppressWarnings("unchecked") @Override @StreamListener(AuditConsumerChannels.AUDIT_CONSUMER) public void receiveCloudRuntimeEvent(@Headers Map<String, Object> headers, CloudRuntimeEvent<?, ?>... events) { if (events != null) { AtomicInteger counter = new AtomicInteger(0); for (CloudRuntimeEvent event : events) { EventToEntityConverter converter = eventConverters.getConverterByEventTypeName(event.getEventType().name()); if (converter != null) { ((CloudRuntimeEventImpl)event).setMessageId((headers.get(MessageHeaders.ID).toString())); ((CloudRuntimeEventImpl)event).setSequenceNumber(counter.getAndIncrement()); eventsRepository.save((AuditEventEntity) converter.convertToEntity(event)); } else { LOGGER.warn(">>> Ignoring CloudRuntimeEvents type: " + event.getEventType().name()); } } } } AuditConsumerChannelHandlerImpl(EventsRepository eventsRepository,
APIEventToEntityConverters eventConverters); @SuppressWarnings("unchecked") @Override @StreamListener(AuditConsumerChannels.AUDIT_CONSUMER) void receiveCloudRuntimeEvent(@Headers Map<String, Object> headers, CloudRuntimeEvent<?, ?>... events); }### Answer:
@Test public void receiveEventShouldStoreEntity() { CloudRuntimeEvent cloudRuntimeEvent = mock(CloudRuntimeEventImpl.class); when(cloudRuntimeEvent.getEventType()).thenReturn(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED); EventToEntityConverter converter = mock(EventToEntityConverter.class); when(converters.getConverterByEventTypeName(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name())).thenReturn(converter); AuditEventEntity entity = mock(AuditEventEntity.class); when(converter.convertToEntity(cloudRuntimeEvent)).thenReturn(entity); CloudRuntimeEvent[] events = {cloudRuntimeEvent}; handler.receiveCloudRuntimeEvent(new HashMap<String,Object>(){{put("id", UUID.randomUUID());}}, events); verify(eventsRepository).save(entity); }
@Test public void messageIdShouldBeSet(){ CloudRuntimeEvent cloudRuntimeEvent = mock(CloudRuntimeEventImpl.class); when(cloudRuntimeEvent.getEventType()).thenReturn(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED); EventToEntityConverter converter = mock(EventToEntityConverter.class); when(converters.getConverterByEventTypeName(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name())).thenReturn(converter); AuditEventEntity entity = mock(AuditEventEntity.class); when(converter.convertToEntity(cloudRuntimeEvent)).thenReturn(entity); CloudRuntimeEvent[] events = {cloudRuntimeEvent}; HashMap <String,Object> headers = new HashMap<>(); headers.put("id", UUID.randomUUID()); handler.receiveCloudRuntimeEvent(headers, events); verify((CloudRuntimeEventImpl)cloudRuntimeEvent).setMessageId(headers.get("id").toString()); } |
### Question:
MemCacheTemplate implements CacheAble<T> { @Override public T get(String key) { T value = null; MemcacheClient oneL1 = null; if (masterL1List != null && masterL1List.size() > 0) { oneL1 = chooseOneL1Client(); if (oneL1 != null) { value = get(key, oneL1); } } if (value == null) { value = get(key, master); } if (value == null && slave != null) { value = get(key, slave); if (value != null && setbackMaster == true) { set(key, value, expireTime, master); } } if (value != null && oneL1 != null) { set(key, value, getExpireTimeL1(), oneL1); } return value; } @Override T get(String key); @Override Map<String, T> getMulti(String[] keys); @Override boolean set(String key, T value); @Override boolean set(String key, T value, Date expdate); @SuppressWarnings("unchecked") @Override CasValue<T> getCas(String key); @Override boolean cas(String key, CasValue<T> casValue); @Override boolean cas(String key, CasValue<T> casValue, Date expdate); @Override boolean delete(String key); void setExpire(long expire); void setExpireL1(long expireL1); Date getExpireTime(); Date getExpireTimeL1(); MemcacheClient getMaster(); List<MemcacheClient> getMasterL1List(); MemcacheClient getSlave(); List<MemcacheClient> getSlaveL1List(); boolean isSetbackMaster(); void setMaster(MemcacheClient master); void setMasterL1List(List<MemcacheClient> masterL1List); void setSlave(MemcacheClient slave); void setSlaveL1List(List<MemcacheClient> slaveL1List); void setSetbackMaster(boolean setbackMaster); boolean isMasterAsOneL1(); void setMasterAsOneL1(boolean masterAsOneL1); String getWirtePolicy(); void setWirtePolicy(String wirtePolicy); }### Answer:
@Test public void testGet() { String key = MemCacheUtil.toKey("123", "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(key, "dsadsadsadsadas")) { String value = memCacheTemplate.get(key); Assert.assertEquals("dsadsadsadsadas", value); memCacheTemplate.delete(key); value = memCacheTemplate.get(key); Assert.assertEquals(null, value); } } |
### Question:
ApacheHttpClient implements ApiHttpClient { public String getAsync(final String url){ return getAsync(url, soTimeOut); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minThread,int maxThread); @Deprecated String getURL(String url); @Deprecated void getURL(String url, ByteBuffer bb); @Deprecated int getURL(String url, OutputStream out); @Deprecated String requestURL(String url, Map<String, ?> nameValues); @Deprecated int requestURL(String url, Map<String, ?> nameValues, OutputStream out); @Deprecated String multURL_UTF8(String url, Map<String, Object> nameValues); void setProxyHostPort(String proxyHostPort); String getProxyHostPort(); HttpClient getClient(); @Deprecated String requestURL(String url, Map<String, String> nameValues, Map<String,String> headers); @Deprecated int requestURL(String url, Map<String, ?> nameValues, Map<String,?> headers, OutputStream out); void setAccessLog(AccessLog accessLog); @Override String get(String url); String get(String url,Map<String,String> headers); @Override String get(String url, String charset); String get(String url,Map<String,String> headers, String charset); String getAsync(final String url); String getAsync(final String url, final long timeout); Future<String> getAsyncFuture(final String url); String postAsync(final String url,final Map<String, ?> nameValues); Future<String> postAsyncFuture(final String url,final Map<String, ?> nameValues); byte[] getByte(String url); @Override String post(String url, Map<String, ?> nameValues); @Override String post(String url, Map<String, ?> nameValues, String charset); String post(String url, Map<String, ?> nameValues,Map<String,String> headers, String charset); String postMulti(String url, Map<String, Object> nameValues); String postMulti(String url, Map<String, Object> nameValues,String charset); String postMulti(String url, InputStream in); String postMulti(String url, byte[] buf); T get(String url, ResultConvert<T> c); T get(String url,String charset,ResultConvert<T> c); T post(String url,Map<String, ?> nameValues, ResultConvert<T> c); T post(String url, Map<String, ?> nameValues,String charset, ResultConvert<T> c); T postMulti(String url, Map<String, Object> nameValues,String charset, ResultConvert<T> c); RequestBuilder buildGet(String url); RequestBuilder buildPost(String url); }### Answer:
@Test public void testGetAsyncSlow(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String result = client.getAsync("http: ApiLogger.debug(result); Assert.assertTrue(StringUtils.isBlank(result)); } |
### Question:
ApacheHttpClient implements ApiHttpClient { public RequestBuilder buildGet(String url){ HttpMethod get=new GetMethod(url); HttpClientRequestBuilder ret=new HttpClientRequestBuilder(url,get,HttpManager.isBlockResource(url)); return ret; } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minThread,int maxThread); @Deprecated String getURL(String url); @Deprecated void getURL(String url, ByteBuffer bb); @Deprecated int getURL(String url, OutputStream out); @Deprecated String requestURL(String url, Map<String, ?> nameValues); @Deprecated int requestURL(String url, Map<String, ?> nameValues, OutputStream out); @Deprecated String multURL_UTF8(String url, Map<String, Object> nameValues); void setProxyHostPort(String proxyHostPort); String getProxyHostPort(); HttpClient getClient(); @Deprecated String requestURL(String url, Map<String, String> nameValues, Map<String,String> headers); @Deprecated int requestURL(String url, Map<String, ?> nameValues, Map<String,?> headers, OutputStream out); void setAccessLog(AccessLog accessLog); @Override String get(String url); String get(String url,Map<String,String> headers); @Override String get(String url, String charset); String get(String url,Map<String,String> headers, String charset); String getAsync(final String url); String getAsync(final String url, final long timeout); Future<String> getAsyncFuture(final String url); String postAsync(final String url,final Map<String, ?> nameValues); Future<String> postAsyncFuture(final String url,final Map<String, ?> nameValues); byte[] getByte(String url); @Override String post(String url, Map<String, ?> nameValues); @Override String post(String url, Map<String, ?> nameValues, String charset); String post(String url, Map<String, ?> nameValues,Map<String,String> headers, String charset); String postMulti(String url, Map<String, Object> nameValues); String postMulti(String url, Map<String, Object> nameValues,String charset); String postMulti(String url, InputStream in); String postMulti(String url, byte[] buf); T get(String url, ResultConvert<T> c); T get(String url,String charset,ResultConvert<T> c); T post(String url,Map<String, ?> nameValues, ResultConvert<T> c); T post(String url, Map<String, ?> nameValues,String charset, ResultConvert<T> c); T postMulti(String url, Map<String, Object> nameValues,String charset, ResultConvert<T> c); RequestBuilder buildGet(String url); RequestBuilder buildPost(String url); }### Answer:
@Test public void testBuildGet(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String headvalue="headvalue"; List<Integer> ids=new ArrayList<Integer>(); ids.add(11); ids.add(12); String result = client.buildGet("http: .withHeader(TEST_HEADER_PREFIX + "ahead", headvalue) .withParam("uid", "1").withParam("uid", "2") .withParam("uid2", new String[] { "3", "4" }) .withParam("uid3", 3l) .withParam("uid4", new int[] { 1, 2 }) .withParam("uid5", ids) .withParam("content", "中文").execute(); ApiLogger.debug(result); Assert.assertTrue(StringUtils.contains(result, headvalue)); } |
### Question:
ApacheHttpClient implements ApiHttpClient { public RequestBuilder buildPost(String url){ PostMethod post = new PostMethod(url); HttpClientRequestBuilder ret=new HttpClientRequestBuilder(url,post,HttpManager.isBlockResource(url)); return ret; } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minThread,int maxThread); @Deprecated String getURL(String url); @Deprecated void getURL(String url, ByteBuffer bb); @Deprecated int getURL(String url, OutputStream out); @Deprecated String requestURL(String url, Map<String, ?> nameValues); @Deprecated int requestURL(String url, Map<String, ?> nameValues, OutputStream out); @Deprecated String multURL_UTF8(String url, Map<String, Object> nameValues); void setProxyHostPort(String proxyHostPort); String getProxyHostPort(); HttpClient getClient(); @Deprecated String requestURL(String url, Map<String, String> nameValues, Map<String,String> headers); @Deprecated int requestURL(String url, Map<String, ?> nameValues, Map<String,?> headers, OutputStream out); void setAccessLog(AccessLog accessLog); @Override String get(String url); String get(String url,Map<String,String> headers); @Override String get(String url, String charset); String get(String url,Map<String,String> headers, String charset); String getAsync(final String url); String getAsync(final String url, final long timeout); Future<String> getAsyncFuture(final String url); String postAsync(final String url,final Map<String, ?> nameValues); Future<String> postAsyncFuture(final String url,final Map<String, ?> nameValues); byte[] getByte(String url); @Override String post(String url, Map<String, ?> nameValues); @Override String post(String url, Map<String, ?> nameValues, String charset); String post(String url, Map<String, ?> nameValues,Map<String,String> headers, String charset); String postMulti(String url, Map<String, Object> nameValues); String postMulti(String url, Map<String, Object> nameValues,String charset); String postMulti(String url, InputStream in); String postMulti(String url, byte[] buf); T get(String url, ResultConvert<T> c); T get(String url,String charset,ResultConvert<T> c); T post(String url,Map<String, ?> nameValues, ResultConvert<T> c); T post(String url, Map<String, ?> nameValues,String charset, ResultConvert<T> c); T postMulti(String url, Map<String, Object> nameValues,String charset, ResultConvert<T> c); RequestBuilder buildGet(String url); RequestBuilder buildPost(String url); }### Answer:
@Test public void testBuildPost(){ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); String headvalue="headvalue"; String result=client.buildPost("http: .withHeader(TEST_HEADER_PREFIX+"ahead", headvalue).withParam("uid", "1") .withParam("uid", "2").withParam("uid2", new String[]{"3","4"}) .withParam("content", "中文").execute(); ApiLogger.debug(result); Assert.assertTrue(StringUtils.contains(result, headvalue)); } |
### Question:
ApacheHttpClient implements ApiHttpClient { public String postMulti(String url, Map<String, Object> nameValues){ return postMulti(url,nameValues,DEFAULT_CHARSET); } ApacheHttpClient(); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize); ApacheHttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize,int minThread,int maxThread); @Deprecated String getURL(String url); @Deprecated void getURL(String url, ByteBuffer bb); @Deprecated int getURL(String url, OutputStream out); @Deprecated String requestURL(String url, Map<String, ?> nameValues); @Deprecated int requestURL(String url, Map<String, ?> nameValues, OutputStream out); @Deprecated String multURL_UTF8(String url, Map<String, Object> nameValues); void setProxyHostPort(String proxyHostPort); String getProxyHostPort(); HttpClient getClient(); @Deprecated String requestURL(String url, Map<String, String> nameValues, Map<String,String> headers); @Deprecated int requestURL(String url, Map<String, ?> nameValues, Map<String,?> headers, OutputStream out); void setAccessLog(AccessLog accessLog); @Override String get(String url); String get(String url,Map<String,String> headers); @Override String get(String url, String charset); String get(String url,Map<String,String> headers, String charset); String getAsync(final String url); String getAsync(final String url, final long timeout); Future<String> getAsyncFuture(final String url); String postAsync(final String url,final Map<String, ?> nameValues); Future<String> postAsyncFuture(final String url,final Map<String, ?> nameValues); byte[] getByte(String url); @Override String post(String url, Map<String, ?> nameValues); @Override String post(String url, Map<String, ?> nameValues, String charset); String post(String url, Map<String, ?> nameValues,Map<String,String> headers, String charset); String postMulti(String url, Map<String, Object> nameValues); String postMulti(String url, Map<String, Object> nameValues,String charset); String postMulti(String url, InputStream in); String postMulti(String url, byte[] buf); T get(String url, ResultConvert<T> c); T get(String url,String charset,ResultConvert<T> c); T post(String url,Map<String, ?> nameValues, ResultConvert<T> c); T post(String url, Map<String, ?> nameValues,String charset, ResultConvert<T> c); T postMulti(String url, Map<String, Object> nameValues,String charset, ResultConvert<T> c); RequestBuilder buildGet(String url); RequestBuilder buildPost(String url); }### Answer:
@Test public void testPostByteArray() throws UnsupportedEncodingException{ ApiHttpClient client = new ApacheHttpClient(100, 1000, 1000, 1024*100); byte[] bytes = "test".getBytes("UTF-8"); String result=client.postMulti("http: ApiLogger.debug(result); Assert.assertTrue(Arrays.equals(bytes, result.getBytes("UTF-8"))); } |
### Question:
McqBaseManager { public static String status() { StringBuilder sb = new StringBuilder(512); sb.append("\r\nreading_mcq(yangwm,true):\t"); sb.append(IS_ALL_READ.get()); return sb.toString(); } static void stopReadAll(); static void startReadAll(); static String status(); static AtomicBoolean IS_ALL_READ; }### Answer:
@Test public void testStatus() { String result = McqBaseManager.status(); Assert.assertEquals("\r\nreading_mcq(yangwm,true):\ttrue", result); ApiLogger.debug("testStatus result:" + result); } |
### Question:
ShardingUtil { public static<T> Map<Integer, T> parseClients(Map<String, T> clientsConfig){ Map<Integer, T> shardingClients = new HashMap<Integer, T>(); for(Map.Entry<String, T> entry : clientsConfig.entrySet()){ List<Integer> dbIdxs = parseDbIdx(entry.getKey()); T client = entry.getValue(); for(Integer dbIdx : dbIdxs){ shardingClients.put(dbIdx, client); } } return shardingClients; } static Map<Integer, T> parseClients(Map<String, T> clientsConfig); }### Answer:
@Test public void testParseClients() { Map<String, Integer> clientsConfig = new HashMap<String, Integer>(); clientsConfig.put("1", new Integer("11")); clientsConfig.put("2", new Integer("21")); clientsConfig.put("3", new Integer("31")); clientsConfig.put("4", new Integer("41")); Map<Integer, Integer> clients = ShardingUtil.parseClients(clientsConfig); ApiLogger.debug("testParseClients clients:" + clients); Assert.assertEquals(new Integer("11"), clients.get(new Integer("1"))); Assert.assertEquals(new Integer("21"), clients.get(new Integer("2"))); Assert.assertEquals(new Integer("31"), clients.get(new Integer("3"))); Assert.assertEquals(new Integer("41"), clients.get(new Integer("4"))); } |
### Question:
PageWrapperUtil { public static <T> String toJson(PageWrapper<T> pageWrapper, String name, long[] values) { JsonBuilder json = new JsonBuilder(); if (values == null) { json.append(name, "[]"); } else { json.appendStrArr(name, values); } appendJson(json, pageWrapper); json.flip(); return json.toString(); } static String toJson(PageWrapper<T> pageWrapper, String name, long[] values); static String toJson(PageWrapper<T> pageWrapper, String name, Jsonable[] values); static PageWrapper<long[]> wrap(long[] ids, int count); static int getPageOffset(int page, int count); static PageWrapper<long[]> paginationAndReverse(long[] ids, PaginationParam paginationParam); static PageWrapper<long[]> paginationAndReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static int[] calculatePaginationByReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static void calculateCursorByReverse(PageWrapper<T> wrapper, long[] ids, int offset, int limit, int count); }### Answer:
@Test public void testToJson() { long[] items = new long[10]; for (int i = 0; i < items.length; i++) { items[i] = (2300000000000000L + 101) + (items.length - 1 - i); } ArrayUtil.reverse(items); ApiLogger.debug(Arrays.toString(items)); int count = 20; int page = 1; long[] expecteds = Arrays.copyOf(items, items.length); ArrayUtil.reverse(expecteds); PaginationParam paginationParam = new PaginationParam.Builder().count(count).page(page).build(); PageWrapper<long[]> pageWrapper = PageWrapperUtil.paginationAndReverse(items, paginationParam); ApiLogger.debug(paginationParam + ", " + PageWrapperUtil.toJson(pageWrapper, "ids", pageWrapper.result)); } |
### Question:
PageWrapperUtil { public static PageWrapper<long[]> wrap(long[] ids, int count) { PageWrapper<long[]> wrapper = new PageWrapper<long[]>(0, 0, ids); wrapper.totalNumber = ids.length; if (ids.length > 1) { wrapper.nextCursor = ids[ids.length - 1] + MAX_ID_ADJECT; } wrapper.result = Arrays.copyOf(ids, Math.min(ids.length, count)); return wrapper; } static String toJson(PageWrapper<T> pageWrapper, String name, long[] values); static String toJson(PageWrapper<T> pageWrapper, String name, Jsonable[] values); static PageWrapper<long[]> wrap(long[] ids, int count); static int getPageOffset(int page, int count); static PageWrapper<long[]> paginationAndReverse(long[] ids, PaginationParam paginationParam); static PageWrapper<long[]> paginationAndReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static int[] calculatePaginationByReverse(long[] ids, int idsLen, long sinceId, long maxId, int count, int page); static void calculateCursorByReverse(PageWrapper<T> wrapper, long[] ids, int offset, int limit, int count); }### Answer:
@Test public void testWrap() { long[] items = new long[10]; for (int i = 0; i < items.length; i++) { items[i] = (2300000000000000L + 101) + (items.length - 1 - i); } ApiLogger.debug(Arrays.toString(items)); int count = 20; long[] expecteds = Arrays.copyOf(items, items.length); PageWrapper<long[]> pageWrapper = PageWrapperUtil.wrap(items, count); ApiLogger.debug(PageWrapperUtil.toJson(pageWrapper, "ids", pageWrapper.result)); Assert.assertArrayEquals(expecteds, pageWrapper.result); } |
### Question:
DaoUtil { public static String createMutiGetSql(String sql, int paramsSize){ StringBuilder sqlBuf = new StringBuilder().append(sql).append("( ?"); for(int i = 1; i < paramsSize; i++){ sqlBuf.append(", ?"); } return sqlBuf.append(")").toString(); } static String createMutiGetEncodedSql(String sql, int paramsSize); static String createMutiGetSql(String sql, int paramsSize); static String expendMultiGetSql(String sql, Object[] params); static Object[] expendMultiGetParams(Object[] params); static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize); static String buildSql(String rawSql, String db, String table); }### Answer:
@Test public void testCreateMutiGetSql() { String sql = "select a,b from table where a in "; int paramsSize = 10; String result = DaoUtil.createMutiGetSql(sql, paramsSize); ApiLogger.debug("testCreateMutiGetSql result:" + result); int count = 0; char[] chs = result.toCharArray(); for (char ch : chs) { if (ch == '?') { count++; } } if (paramsSize <= 0) { Assert.assertEquals(1, count); } else { Assert.assertEquals(paramsSize, count); } } |
### Question:
DaoUtil { public static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize) { StringBuilder sb = new StringBuilder(sqlPrefix).append(sqlSuffix); for (int i = 1; i < valuesSize; i++) { sb.append(", "); sb.append(sqlSuffix); } return sb.toString(); } static String createMutiGetEncodedSql(String sql, int paramsSize); static String createMutiGetSql(String sql, int paramsSize); static String expendMultiGetSql(String sql, Object[] params); static Object[] expendMultiGetParams(Object[] params); static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize); static String buildSql(String rawSql, String db, String table); }### Answer:
@Test public void testCreateMultiInsertSql() { int paramsSize = 1; String result = DaoUtil.createMultiInsertSql("insert into test values", "(?, ?, ?, now())", paramsSize); System.out.println("testCreateMultiInsertSql paramsSize:" + paramsSize + ", result:" + result); Assert.assertEquals("insert into test values(?, ?, ?, now())", result); paramsSize = 3; result = DaoUtil.createMultiInsertSql("insert ignore into test values", "(?, ?, ?, now())", paramsSize); System.out.println("testCreateMultiInsertSql paramsSize:" + paramsSize + ", result:" + result); Assert.assertEquals("insert ignore into test values(?, ?, ?, now()), (?, ?, ?, now()), (?, ?, ?, now())", result); } |
### Question:
MemCacheTemplate implements CacheAble<T> { @Override public Map<String, T> getMulti(String[] keys) { Map<String, T> values = new HashMap<String, T>(); MemcacheClient oneL1 = null; if (masterL1List != null && masterL1List.size() > 0) { oneL1 = chooseOneL1Client(); if (oneL1 != null) { values = getMulti(keys, oneL1); } } String[] leftkeys = null; if(keys.length > values.size()) { leftkeys = getMulti(values, keys, master); } if (keys.length > values.size() && slave != null) { String[] leftkeysSlave = getMulti(values, keys, slave); if (leftkeysSlave != null && setbackMaster == true) { set(values, leftkeysSlave, expireTime, master); } } if (oneL1 != null && leftkeys != null) { set(values, leftkeys, getExpireTimeL1(), oneL1); } return values; } @Override T get(String key); @Override Map<String, T> getMulti(String[] keys); @Override boolean set(String key, T value); @Override boolean set(String key, T value, Date expdate); @SuppressWarnings("unchecked") @Override CasValue<T> getCas(String key); @Override boolean cas(String key, CasValue<T> casValue); @Override boolean cas(String key, CasValue<T> casValue, Date expdate); @Override boolean delete(String key); void setExpire(long expire); void setExpireL1(long expireL1); Date getExpireTime(); Date getExpireTimeL1(); MemcacheClient getMaster(); List<MemcacheClient> getMasterL1List(); MemcacheClient getSlave(); List<MemcacheClient> getSlaveL1List(); boolean isSetbackMaster(); void setMaster(MemcacheClient master); void setMasterL1List(List<MemcacheClient> masterL1List); void setSlave(MemcacheClient slave); void setSlaveL1List(List<MemcacheClient> slaveL1List); void setSetbackMaster(boolean setbackMaster); boolean isMasterAsOneL1(); void setMasterAsOneL1(boolean masterAsOneL1); String getWirtePolicy(); void setWirtePolicy(String wirtePolicy); }### Answer:
@Test public void testGetMulti() { String[] keys = MemCacheUtil.toKeys(new String[] { "123", "456", "789" }, "module.c"); MemCacheTemplate<String> memCacheTemplate = getMemCacheTemplate(); if (memCacheTemplate.set(keys[0], "dsadsadsadsadas")) { Map<String, String> map = memCacheTemplate.getMulti(keys); Assert.assertEquals(true, map.containsKey(keys[0])); Assert.assertEquals(false, map.containsKey(keys[1])); Assert.assertEquals(false, map.containsKey(keys[2])); } } |
### Question:
DaoUtil { public static String expendMultiGetSql(String sql, Object[] params) { int lastQuoteIndex = -1; for (int i = 0; i < params.length; i++) { lastQuoteIndex = sql.indexOf('?', lastQuoteIndex + 1); Object param = params[i]; if (param instanceof Object[]) { Object[] nestArrayParam = (Object[]) param; String multipleGetStatement = multiGetPrepareStatement(nestArrayParam.length); sql = sql.substring(0, lastQuoteIndex) + multipleGetStatement + sql.substring(lastQuoteIndex + 1); lastQuoteIndex += multipleGetStatement.length(); } } return sql; } static String createMutiGetEncodedSql(String sql, int paramsSize); static String createMutiGetSql(String sql, int paramsSize); static String expendMultiGetSql(String sql, Object[] params); static Object[] expendMultiGetParams(Object[] params); static String createMultiInsertSql(String sqlPrefix, String sqlSuffix, int valuesSize); static String buildSql(String rawSql, String db, String table); }### Answer:
@Test public void testMultiGetSql() { String sql = "select * from table where uid=? and type in (?) order by date"; Object[] params = new Object[] { 12345, new Object[] { 1234, 1234 } }; String rs = DaoUtil.expendMultiGetSql(sql, params); Assert.assertEquals("select * from table where uid=? and type in (?,?) order by date", rs); sql = "select * from table where uid=? and type in (?) and vflag in (?) order by date"; params = new Object[] {123, new Object[] {12,12}, new Object[]{12,12}}; rs = DaoUtil.expendMultiGetSql(sql, params); Assert.assertEquals("select * from table where uid=? and type in (?,?) and vflag in (?,?) order by date", rs); params = new Object[] {123, new Object[] {12}, new Object[]{12}}; rs = DaoUtil.expendMultiGetSql(sql, params); Assert.assertEquals("select * from table where uid=? and type in (?) and vflag in (?) order by date", rs); params = new Object[] {123, 12, 12}; rs = DaoUtil.expendMultiGetSql(sql, params); Assert.assertEquals("select * from table where uid=? and type in (?) and vflag in (?) order by date", rs); sql = "select * from table where uid=?"; rs = DaoUtil.expendMultiGetSql(sql, params); Assert.assertEquals("select * from table where uid=?", rs); } |
### Question:
IdCreator implements IdCreate { public long generateId(int bizFlagValue){ return getNextId(bizFlagValue); } long generateId(int bizFlagValue); NaiveMemcacheClient getIdGenerateClient(); void setIdGenerateClient(NaiveMemcacheClient idGenerateClient); }### Answer:
@Test public void testGenerateIdForUuid() { IdCreator idCreator = createIdCreator("testuuid:5001,testuuid:5001"); long t1 = System.currentTimeMillis(); int count = 10; for(int i = 0; i < count; i++){ long id = idCreator.generateId(2); ApiLogger.debug("IdCreatorTest testGenerateIdForUuid id:" + id); } long t2 = System.currentTimeMillis(); ApiLogger.debug(String.format("count=%s,time=%sms", count, (t2 - t1))); }
@Test public void testGenerateIdForUid() { IdCreator idCreator = createIdCreator("testuid:5101,testuid:5101"); long t1 = System.currentTimeMillis(); int count = 10; for(int i = 0; i < count; i++){ long id = idCreator.generateId(2); ApiLogger.debug("IdCreatorTest testGenerateIdForUid id:" + id); } long t2 = System.currentTimeMillis(); ApiLogger.debug(String.format("count=%s,time=%sms", count, (t2 - t1))); } |
### Question:
WebExceptionFormat { public static String formatException(WebApiException e, String path, String type) { if (path == null) { throw new IllegalArgumentException(" path argument is null"); } ExcepFactor factor = e.getFactor(); if (type == null) { } String result; if ("xml".equals(type)) { result = String.format(xmlMsg, path, factor.getErrorCode(), e.getMessage()); } else if ("str".equals(type)) { result = String.format(strMsg, path, factor.getErrorCode(), e.getMessage(), factor.getErrorMsgCn()); } else { result = String.format(jsonMsg, path, factor.getErrorCode(), e.getMessage()); } return result; } static String formatException(WebApiException e, String path, String type); }### Answer:
@Test public void testFormatException(){ WebApiException e = new WebApiException(ExcepFactor.E_PARAM_INVALID_ERROR, "param error"); String result = WebExceptionFormat.formatException(e, "/user/test", "json"); ApiLogger.debug("testFormatException result:" + result); } |
### Question:
TopN { public static long[] top(Collection<? extends VectorInterface> vectorItems, int n) { VectorInterface[] vectors = getVectors(vectorItems); return top(vectors, n); } static long[] top(Collection<? extends VectorInterface> vectorItems, int n); }### Answer:
@Test public void testTopN() { Map<String, ? extends VectorInterface> vectorMap = getAllVectorMap(); for (int column = -1; column >= 0; column--) { ApiLogger.debug(column); } long[] result = TopN.top(vectorMap.values(), 20); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopN.top(vectorMap.values(), 30); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopN.top(vectorMap.values(), CommonConst.TIMELINE_SIZE); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); } |
### Question:
TopNObject { public static Object[] top(Collection<? extends VectorInterface> vectorItems, int n) { return top(vectorItems, n, CommonConst.EMPTY_OBJECT_ARRAY); } static Object[] top(Collection<? extends VectorInterface> vectorItems, int n); static Object[] top(Collection<? extends VectorInterface> vectorItems, int n, Object[] newObject); }### Answer:
@Test public void testTopN() { Map<String, ? extends VectorInterface> vectorMap = getAllVectorMap(); for (int column = -1; column >= 0; column--) { ApiLogger.debug(column); } Object[] result = (Object[]) TopNObject.top(vectorMap.values(), 20); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopNObject.top(vectorMap.values(), 30, CommonConst.EMPTY_LONG_OBJECT_ARRAY); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); result = TopNObject.top(vectorMap.values(), CommonConst.TIMELINE_SIZE, CommonConst.EMPTY_LONG_OBJECT_ARRAY); ApiLogger.debug("result length:" + result.length + ", result" + Arrays.toString(result)); } |
### Question:
JsonUtil { public static String toJsonStr(String value) { if (value == null) return null; StringBuilder buf = new StringBuilder(value.length()); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); switch(c) { case '"': buf.append("\\\""); break; case '\\': buf.append("\\\\"); break; case '\n': buf.append("\\n"); break; case '\r': buf.append("\\r"); break; case '\t': buf.append("\\t"); break; case '\f': buf.append("\\f"); break; case '\b': buf.append("\\b"); break; default: if (c < 32 || c == 127) { buf.append(" "); } else { buf.append(c); } } } return buf.toString(); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer:
@Test public void testToJsonStr() { Assert.assertEquals("dal\\\"?[]}das\\\\aa\\n33\\r24\\tkkh\\r86gg\\f11\\b", JsonUtil.toJsonStr("dal\"?[]}das\\aa\n33\r24\tkkh\r86gg\f11\b")); } |
### Question:
JsonUtil { public static boolean isValidJsonObject(String json){ return isValidJsonObject(json, false); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer:
@Test public void testIsValidJsonObject() { Assert.assertEquals(true, JsonUtil.isValidJsonObject("{}")); Assert.assertEquals(false, JsonUtil.isValidJsonObject("")); Assert.assertEquals(false, JsonUtil.isValidJsonObject(null)); Assert.assertEquals(true, JsonUtil.isValidJsonObject("{\"uid\":1750715731}")); Assert.assertEquals(true, JsonUtil.isValidJsonObject("{\"id\":10001}")); Assert.assertEquals(true, JsonUtil.isValidJsonObject("{}", true)); Assert.assertEquals(true, JsonUtil.isValidJsonObject("", true)); Assert.assertEquals(true, JsonUtil.isValidJsonObject(null, true)); } |
### Question:
JsonUtil { public static boolean isValidJsonArray(String json){ return isValidJsonArray(json, false); } static String toJsonStr(String value); static boolean isValidJsonObject(String json); static boolean isValidJsonObject(String json, boolean allowBlank); static boolean isValidJsonArray(String json); static boolean isValidJsonArray(String json, boolean allowBlank); static String toJson(long[] ids); static String toJson(Jsonable[] values); }### Answer:
@Test public void testIsValidJsonArray() { Assert.assertEquals(true, JsonUtil.isValidJsonArray("[]")); Assert.assertEquals(false, JsonUtil.isValidJsonArray("")); Assert.assertEquals(false, JsonUtil.isValidJsonArray(null)); Assert.assertEquals(true, JsonUtil.isValidJsonArray("[{\"uid\":1750715731},{\"uid\":1821155363}]")); Assert.assertEquals(true, JsonUtil.isValidJsonArray("[1750715731, 1821155363]")); Assert.assertEquals(true, JsonUtil.isValidJsonArray("[]", true)); Assert.assertEquals(true, JsonUtil.isValidJsonArray("", true)); Assert.assertEquals(true, JsonUtil.isValidJsonArray(null, true)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.