target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void logWarning() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.WARN); logger.log(LogLevel.WARN, "logger name", "warn message"); assertThat(capture.toString(), containsString("WARN logger name - warn message")); } | private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } |
@Test public void logWarningError() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.WARN); logger.log(LogLevel.WARN, "logger name", "warn message", new Exception("error message")); Pattern pattern = Pattern.compile("WARN logger name - warn message.*java.lang.Exception: error message", Pattern.DOTALL | Pattern.MULTILINE); assertTrue(pattern.matcher(capture.toString()).find()); } | private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } |
@Test public void logError() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.ERROR); logger.log(LogLevel.ERROR, "logger name", "error message"); assertThat(capture.toString(), containsString("ERROR logger name - error message")); } | private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } |
@Test public void logErrorError() { LoggingSystem.get(ClassLoader.getSystemClassLoader()) .setLogLevel(org.slf4j.Logger.ROOT_LOGGER_NAME, LogLevel.ERROR); logger.log(LogLevel.ERROR, "logger name", "error message", new Exception("error message")); Pattern pattern = Pattern.compile("ERROR logger name - error message.*java.lang.Exception: error message", Pattern.DOTALL | Pattern.MULTILINE); assertTrue(pattern.matcher(capture.toString()).find()); } | private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } | Logger { private void log(org.slf4j.Logger logger, LogLevel level, String message) { Objects.requireNonNull(level, "LogLevel must not be null."); switch (level) { case TRACE: logger.trace(message); break; case DEBUG: logger.debug(message); break; case INFO: logger.info(message); break; case WARN: logger.warn(message); break; case ERROR: case FATAL: logger.error(message); break; default: break; } } void log(LogLevel level, Class<?> clazz, String message); void log(LogLevel level, String name, String message); void log(Class<?> clazz, String message, Throwable err); void log(LogLevel level, String name, String message, Throwable err); boolean isEnabled(LogLevel level, Class<?> clazz); boolean isEnabled(LogLevel level, String name); } |
@Test public void testRelativeRedirects() throws Throwable { try (DeferredAssertions as = new DeferredAssertions()) { client.get().setURL("http: @Override public void receive(final State<?> object) { if (object.stateType() == StateType.Redirect) { as.add(new Assertion() { @Override public void exec() throws Throwable { assertEquals("http: } }); } } }).execute().await(2, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } } | public HttpRequestBuilder get() { return new RB(Method.GET); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } |
@Test public void testRedirectLimit() throws Throwable { final List<URL> redirects = new CopyOnWriteArrayList<>(); final Set<StateType> states = Sets.newConcurrentHashSet(); final AtomicBoolean errorResponse = new AtomicBoolean(); final AtomicReference<Throwable> error = new AtomicReference<>(); final AtomicBoolean received = new AtomicBoolean(); client.get().setURL("http: @Override public void receive(URL object) { redirects.add(object); } }).onEvent(new Receiver<State<?>>() { @Override public void receive(State<?> object) { states.add(object.stateType()); } }).execute(new ResponseHandler<String>(String.class) { @Override protected void onError(Throwable err) { error.set(err); } @Override protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) { errorResponse.set(true); } @Override protected void receive(HttpResponseStatus status, HttpHeaders headers, String obj) { received.set(true); } }).await(5, TimeUnit.SECONDS); Thread.sleep(200); assertEquals(5, redirects.size()); assertTrue(states.contains(StateType.Connecting)); assertTrue(states.contains(StateType.Connected)); assertTrue(states.contains(StateType.SendRequest)); assertTrue(states.contains(StateType.AwaitingResponse)); assertTrue(states.contains(StateType.HeadersReceived)); assertTrue(states.contains(StateType.Error)); assertTrue(states.contains(StateType.Redirect)); assertFalse(states.contains(StateType.Timeout)); assertFalse(states.contains(StateType.Finished)); assertFalse(states.contains(StateType.FullContentReceived)); assertFalse(errorResponse.get()); assertFalse(received.get()); assertNotNull(error.get()); assertTrue(error.get() instanceof RedirectException); assertTrue(((RedirectException) error.get()).kind() == RedirectException.Kind.REDIRECT_LOOP); } | public HttpRequestBuilder get() { return new RB(Method.GET); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } |
@Test(expected = InvalidInputException.class) public void testInvalidUrl() throws Throwable { client.get().setURL(URL.parse("!garbage!!")).execute(); } | public HttpRequestBuilder get() { return new RB(Method.GET); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } |
@Test public void testCancellation() throws Throwable { final CountDownLatch latch = new CountDownLatch(2); final AtomicReference<ResponseFuture> future = new AtomicReference<>(); final AtomicReference<Throwable> exception = new AtomicReference<>(); final AtomicBoolean cancelled = new AtomicBoolean(); final AtomicBoolean receiveCalled = new AtomicBoolean(); final AtomicBoolean errorResponseCalled = new AtomicBoolean(); future.set(client.get().setURL("http: @Override public void receive(State<?> object) { if (object.stateType() == StateType.Cancelled) { cancelled.set(true); latch.countDown(); } } }).execute(new ResponseHandler<String>(String.class) { @Override protected void onError(Throwable err) { exception.set(err); latch.countDown(); } @Override protected void onErrorResponse(HttpResponseStatus status, HttpHeaders headers, String content) { errorResponseCalled.set(true); } @Override protected void receive(HttpResponseStatus status, HttpHeaders headers, String obj) { receiveCalled.set(true); } })); future.get().cancel(); latch.await(10, TimeUnit.SECONDS); assertFalse(errorResponseCalled.get()); assertFalse(receiveCalled.get()); Thread.sleep(200); assertNotNull(exception.get()); assertTrue(exception.get() instanceof CancellationException); } | public HttpRequestBuilder get() { return new RB(Method.GET); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } |
@Test public void testPost() throws Throwable { final AM am = new AM(); final String ur = "http: client.addActivityMonitor(am); final DeferredAssertions assertions = new DeferredAssertions(); final Set<StateType> stateTypes = new HashSet<>(); final String[] xheader = new String[1]; ResponseFuture f = client.post() .setURL(ur) .addHeader(Headers.CONNECTION, Connection.close) .setBody("This is a test", MediaType.PLAIN_TEXT_UTF_8) .onEvent(new Receiver<State<?>>() { public void receive(State<?> state) { stateTypes.add(state.stateType()); if (null != state.stateType()) switch (state.stateType()) { case Finished: DefaultFullHttpResponse d = (DefaultFullHttpResponse) state.get(); assertions.add(() -> { assertTrue(am.started.contains(ur)); }); break; case Closed: assertions.add(() -> { assertTrue(am.ended.contains(ur)); }); break; case FullContentReceived: ByteBuf buf = (ByteBuf) state.get(); byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(0, bytes); final String content = new String(bytes, CharsetUtil.UTF_8); assertions.add(() -> { assertEquals("Hey you, This is a test", content); }); break; case HeadersReceived: xheader[0] = ((HttpResponse) state.get()).headers().get("X-foo"); break; default: break; } } }).execute(); f.await(5, TimeUnit.SECONDS).throwIfError(); server.throwLast(); assertions.exec(); assertTrue(stateTypes.contains(StateType.Connected)); assertTrue(stateTypes.contains(StateType.SendRequest)); assertTrue(stateTypes.contains(StateType.Connecting)); assertTrue(stateTypes.contains(StateType.ContentReceived)); assertTrue(stateTypes.contains(StateType.FullContentReceived)); assertTrue(stateTypes.contains(StateType.HeadersReceived)); assertFalse(stateTypes.contains(StateType.Cancelled)); assertFalse(stateTypes.contains(StateType.Error)); assertEquals("bar", xheader[0]); } | public HttpRequestBuilder post() { return new RB(Method.POST); } | HttpClient { public HttpRequestBuilder post() { return new RB(Method.POST); } } | HttpClient { public HttpRequestBuilder post() { return new RB(Method.POST); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); } | HttpClient { public HttpRequestBuilder post() { return new RB(Method.POST); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } | HttpClient { public HttpRequestBuilder post() { return new RB(Method.POST); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } |
@Test public void test() throws Throwable { final CookieStore store = new CookieStore(); final String[] contents = new String[1]; ResponseFuture h = client.get().setCookieStore(store).setURL(URL.parse("https: .execute(new ResponseHandler<String>(String.class) { @Override protected void receive(HttpResponseStatus status, HttpHeaders headers, String obj) { contents[0] = obj; } }); final AtomicInteger chunkCount = new AtomicInteger(); final List<String> chunks = new ArrayList<>(); h.onAnyEvent(new Receiver<State<?>>() { Set<StateType> seen = new HashSet<>(); @Override public void receive(State<?> state) { seen.add(state.stateType()); if (state.get() instanceof HttpContent) { HttpContent content = (HttpContent) state.get(); ByteBuf bb = content.content(); byte[] bytes = new byte[bb.readableBytes()]; bb.getBytes(0, bytes); String s = new String(bytes, CharsetUtil.UTF_8); chunks.add(s); chunkCount.incrementAndGet(); } } }); h.await(5, TimeUnit.SECONDS).throwIfError(); assertEquals(7, chunkCount.get()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 5; i++) { assertEquals("CHUNK-" + (i + 1) + "\n", chunks.get(i)); sb.append(chunks.get(i)); } assertEquals("skiddoo", store.get("twentythree")); assertEquals(sb.toString(), contents[0]); } | public HttpRequestBuilder get() { return new RB(Method.GET); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } | HttpClient { public HttpRequestBuilder get() { return new RB(Method.GET); } HttpClient(); HttpClient(boolean compress, int maxChunkSize, int threads,
int maxInitialLineLength, int maxHeadersSize, boolean followRedirects,
CharSequence userAgent, List<RequestInterceptor> interceptors,
Iterable<ChannelOptionSetting<?>> settings, boolean send100continue,
CookieStore cookies, Duration timeout, SslContext sslContext, AddressResolverGroup<?> resolver,
NioEventLoopGroup threadPool, int maxRedirects, NettyContentMarshallers marshallers,
ObjectMapper mapper); static HttpClientBuilder builder(); HttpRequestBuilder request(Method method); HttpRequestBuilder get(); HttpRequestBuilder head(); HttpRequestBuilder put(); HttpRequestBuilder post(); HttpRequestBuilder delete(); HttpRequestBuilder options(); @SuppressWarnings("deprecation") void shutdown(); void addActivityMonitor(ActivityMonitor monitor); void removeActivityMonitor(ActivityMonitor monitor); } |
@Test public void shouldSetDataSourceOnInit() { plugin.init(application); verify(flyway).setDataSource("jdbc:mysql: verify(flyway).setSchemas("test"); } | public void init(Application<? extends ApplicationConfiguration> application) { DatabaseConfiguration dbConfig = application.getConfiguration().getDatabaseConfiguration(); URI uri = getUri(dbConfig.getUrl()); if (Strings.isNullOrEmpty(uri.getPath())) { flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword()); } else { flyway.setDataSource(getUrl(uri, false), dbConfig.getUsername(), dbConfig.getPassword()); flyway.setSchemas(uri.getPath().substring(1)); } flyway.migrate(); } | MigrationsPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { DatabaseConfiguration dbConfig = application.getConfiguration().getDatabaseConfiguration(); URI uri = getUri(dbConfig.getUrl()); if (Strings.isNullOrEmpty(uri.getPath())) { flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword()); } else { flyway.setDataSource(getUrl(uri, false), dbConfig.getUsername(), dbConfig.getPassword()); flyway.setSchemas(uri.getPath().substring(1)); } flyway.migrate(); } } | MigrationsPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { DatabaseConfiguration dbConfig = application.getConfiguration().getDatabaseConfiguration(); URI uri = getUri(dbConfig.getUrl()); if (Strings.isNullOrEmpty(uri.getPath())) { flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword()); } else { flyway.setDataSource(getUrl(uri, false), dbConfig.getUsername(), dbConfig.getPassword()); flyway.setSchemas(uri.getPath().substring(1)); } flyway.migrate(); } MigrationsPlugin(); MigrationsPlugin(Flyway flyway); } | MigrationsPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { DatabaseConfiguration dbConfig = application.getConfiguration().getDatabaseConfiguration(); URI uri = getUri(dbConfig.getUrl()); if (Strings.isNullOrEmpty(uri.getPath())) { flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword()); } else { flyway.setDataSource(getUrl(uri, false), dbConfig.getUsername(), dbConfig.getPassword()); flyway.setSchemas(uri.getPath().substring(1)); } flyway.migrate(); } MigrationsPlugin(); MigrationsPlugin(Flyway flyway); void init(Application<? extends ApplicationConfiguration> application); void destroy(); } | MigrationsPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { DatabaseConfiguration dbConfig = application.getConfiguration().getDatabaseConfiguration(); URI uri = getUri(dbConfig.getUrl()); if (Strings.isNullOrEmpty(uri.getPath())) { flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword()); } else { flyway.setDataSource(getUrl(uri, false), dbConfig.getUsername(), dbConfig.getPassword()); flyway.setSchemas(uri.getPath().substring(1)); } flyway.migrate(); } MigrationsPlugin(); MigrationsPlugin(Flyway flyway); void init(Application<? extends ApplicationConfiguration> application); void destroy(); } |
@Test public void shouldSetEntityKeyOnMetaDataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, key, method); verify(metaData).setEntityKey("code"); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldSetEntityKeyOnMetaDataWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("code"); handler.handle(metaData, key, field); verify(metaData).setEntityKey("code"); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test(expectedExceptions=IllegalArgumentException.class, expectedExceptionsMessageRegExp="Method - readCode is not a getter") public void shouldThrowExceptionWhenMethodIsNotGetter() throws Exception { Method method = DummyModel.class.getDeclaredMethod("readCode"); handler.handle(metaData, key, method); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { metaData.setEntityKey(getGetterName(method, true)); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldHandleSecureAnnotation() { SecurableMetaData metaData = mock(SecurableMetaData.class); SecureMultipleAnnotationHandler handler = new SecureMultipleAnnotationHandler(); SecureMultiple multiple = mock(SecureMultiple.class); Secure secure1 = mock(Secure.class); when(secure1.permissions()).thenReturn(new String[] {"permission1", "permission2"}); when(secure1.method()).thenReturn(Method.GET); Secure secure2 = mock(Secure.class); when(secure2.permissions()).thenReturn(new String[] {"permission3"}); when(secure2.method()).thenReturn(Method.POST); when(multiple.value()).thenReturn(new Secure[]{secure1, secure2}); handler.handle(metaData, multiple); verify(metaData).addPermissionMetaData(new PermissionMetaData(Method.GET.getMethod(), Sets.newHashSet("permission1", "permission2"))); verify(metaData).addPermissionMetaData(new PermissionMetaData(Method.POST.getMethod(), Sets.newHashSet("permission3"))); } | public void handle(SecurableMetaData metaData, Annotation annotation) { for (Secure secure : ((SecureMultiple) annotation).value()) { super.handle(metaData, secure); } } | SecureMultipleAnnotationHandler extends SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { for (Secure secure : ((SecureMultiple) annotation).value()) { super.handle(metaData, secure); } } } | SecureMultipleAnnotationHandler extends SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { for (Secure secure : ((SecureMultiple) annotation).value()) { super.handle(metaData, secure); } } } | SecureMultipleAnnotationHandler extends SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { for (Secure secure : ((SecureMultiple) annotation).value()) { super.handle(metaData, secure); } } void handle(SecurableMetaData metaData, Annotation annotation); } | SecureMultipleAnnotationHandler extends SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { for (Secure secure : ((SecureMultiple) annotation).value()) { super.handle(metaData, secure); } } void handle(SecurableMetaData metaData, Annotation annotation); } |
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), ManyToMany.class); } | @Override public Class<?> getAnnotationType() { return ManyToMany.class; } | ManyToManyAnnotationHandler extends OneToManyAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToMany.class; } } | ManyToManyAnnotationHandler extends OneToManyAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToMany.class; } } | ManyToManyAnnotationHandler extends OneToManyAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToMany.class; } @Override Class<?> getAnnotationType(); } | ManyToManyAnnotationHandler extends OneToManyAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToMany.class; } @Override Class<?> getAnnotationType(); } |
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Action.class); } | @Override public Class<?> getAnnotationType() { return Action.class; } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Action.class; } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Action.class; } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Action.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Action.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddActionMethodToMetadataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("dummyAction"); handler.handle(metaData, annotation, method); ActionMetaData data = new ActionMetaData("dummyAction", "/dummy", method); verify(metaData).addActionMethod(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddActionMethodWithCustomValueToMetadataWhenOnMethod() throws Exception { when(annotation.value()).thenReturn("customAction"); Method method = DummyModel.class.getDeclaredMethod("dummyAction"); handler.handle(metaData, annotation, method); ActionMetaData data = new ActionMetaData("customAction", "/custom", method); verify(metaData).addActionMethod(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddActionMethodToMetadataWithParamsWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("dummyAction", String.class, Long.class); handler.handle(metaData, annotation, method); ActionMetaData data = new ActionMetaData("dummyAction", "/dummy", method); data.addParameter(new ParameterMetaData("param1", "param1", String.class)); data.addParameter(new ParameterMetaData("param2", "param2", Long.class)); verify(metaData).addActionMethod(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test(expectedExceptions=IllegalArgumentException.class) public void shouldNotAddActionToMetadataWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("children"); handler.handle(metaData, annotation, field); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldGetClientFromSessionIfClientNameAttributeIsSet() { Session session = mock(Session.class); when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("client1"); assertEquals(filter.getClient(session), basicClient); } | protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); static final String PRINCIPAL; } |
@Test(expectedExceptions=MinnalInstrumentationException.class) public void shouldThrowExceptionWhenActionSpecifiedOnNonAggregateRoot() throws Exception { when(metaData.getEntityClass()).thenReturn((Class) NonAggregateRootModel.class); Method method = NonAggregateRootModel.class.getDeclaredMethod("dummyAction"); handler.handle(metaData, annotation, method); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | ActionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (! ClassUtils.hasAnnotation(metaData.getEntityClass(), AggregateRoot.class)) { logger.error("@Action can be specified only on classes marked with @AggregateRoot. {} class is not an aggregate root", metaData.getEntityClass()); throw new MinnalInstrumentationException("@Action can be specified only on classes marked with @AggregateRoot. " + metaData.getEntityClass() + " class is not an aggregate root"); } String value = ((Action)annotation).value(); String path = ((Action)annotation).path(); if (Strings.isNullOrEmpty(value)) { value = method.getName(); } if (Strings.isNullOrEmpty(path)) { path = null; } ActionMetaData actionMetaData = new ActionMetaData(value, path, method); String[] parameterNames = ParameterNameDiscoverer.getParameterNames(method); Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { ParameterMetaData parameterMetaData = new ParameterMetaData(parameterNames[i], parameterNames[i], parameterTypes[i]); actionMetaData.addParameter(parameterMetaData); } metaData.addActionMethod(actionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Searchable.class); } | @Override public Class<?> getAnnotationType() { return Searchable.class; } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Searchable.class; } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Searchable.class; } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Searchable.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return Searchable.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddSearchFieldToMetadataWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, annotation, method); ParameterMetaData data = new ParameterMetaData("code", "code", String.class); metaData.addSearchField(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddSearchFieldWithValueToMetadataWhenOnMethod() throws Exception { when(annotation.value()).thenReturn("customCode"); Method method = DummyModel.class.getDeclaredMethod("getCode"); handler.handle(metaData, annotation, method); ParameterMetaData data = new ParameterMetaData("customCode", "code", String.class); metaData.addSearchField(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddSearchFieldToMetadataWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("code"); handler.handle(metaData, annotation, field); ParameterMetaData data = new ParameterMetaData("code", "code", String.class); metaData.addSearchField(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddSearchFieldWithValueToMetadataWhenOnField() throws Exception { when(annotation.value()).thenReturn("customCode"); Field field = DummyModel.class.getDeclaredField("code"); handler.handle(metaData, annotation, field); ParameterMetaData data = new ParameterMetaData("customCode", "code", String.class); metaData.addSearchField(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | SearchableAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { String value = ((Searchable)annotation).value(); value = Strings.isNullOrEmpty(value) ? getGetterName(method, true) : value; ParameterMetaData parameterMetaData = new ParameterMetaData(value, value, method.getReturnType()); metaData.addSearchField(parameterMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), OneToOne.class); } | @Override public Class<?> getAnnotationType() { return OneToOne.class; } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return OneToOne.class; } } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return OneToOne.class; } } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return OneToOne.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return OneToOne.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddToMetadataAssociationWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getSpouse"); handler.handle(metaData, annotation, method); AssociationMetaData data = new AssociationMetaData("spouse", DummyModel.class, true); verify(metaData).addAssociation(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldAddToMetadataAssociationWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("spouse"); handler.handle(metaData, annotation, field); AssociationMetaData data = new AssociationMetaData("spouse", DummyModel.class, true); verify(metaData).addAssociation(data); } | @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } | OneToOneAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), method.getReturnType(), isEntity(method.getReturnType())); metaData.addAssociation(associationMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); } |
@Test public void shouldHandleSecureAnnotation() { SecurableMetaData metaData = mock(SecurableMetaData.class); SecureAnnotationHandler handler = new SecureAnnotationHandler(); Secure secure = mock(Secure.class); when(secure.permissions()).thenReturn(new String[] {"permission1", "permission2"}); when(secure.method()).thenReturn(Method.GET); handler.handle(metaData, secure); verify(metaData).addPermissionMetaData(new PermissionMetaData(Method.GET.getMethod(), Sets.newHashSet("permission1", "permission2"))); } | public void handle(SecurableMetaData metaData, Annotation annotation) { metaData.addPermissionMetaData(constructPermissionMetaData(annotation)); } | SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { metaData.addPermissionMetaData(constructPermissionMetaData(annotation)); } } | SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { metaData.addPermissionMetaData(constructPermissionMetaData(annotation)); } } | SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { metaData.addPermissionMetaData(constructPermissionMetaData(annotation)); } void handle(SecurableMetaData metaData, Annotation annotation); } | SecureAnnotationHandler { public void handle(SecurableMetaData metaData, Annotation annotation) { metaData.addPermissionMetaData(constructPermissionMetaData(annotation)); } void handle(SecurableMetaData metaData, Annotation annotation); } |
@Test public void shouldReturnNullClientFromSessionIfClientNameAttributeIsNotSet() { Session session = mock(Session.class); when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn(null); assertNull(filter.getClient(session)); } | protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); static final String PRINCIPAL; } |
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), ManyToOne.class); } | @Override public Class<?> getAnnotationType() { return ManyToOne.class; } | ManyToOneAnnotationHandler extends OneToOneAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToOne.class; } } | ManyToOneAnnotationHandler extends OneToOneAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToOne.class; } } | ManyToOneAnnotationHandler extends OneToOneAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToOne.class; } @Override Class<?> getAnnotationType(); } | ManyToOneAnnotationHandler extends OneToOneAnnotationHandler { @Override public Class<?> getAnnotationType() { return ManyToOne.class; } @Override Class<?> getAnnotationType(); } |
@Test public void shouldConstructEntityTree() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); entityNode.construct(); assertEquals(entityNode.getChildren().size(), 2); } | public void construct() { LinkedList<EntityNode> queue = new LinkedList<EntityNode>(); queue.offer(this); while (! queue.isEmpty()) { EntityNode node = queue.poll(); for (CollectionMetaData collection : node.getValue().getCollections()) { if (! collection.isEntity()) { continue; } EntityNode child = new EntityNode(collection, namingStrategy); if (node.addChild(child) != null) { queue.offer(child); } } } } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public void construct() { LinkedList<EntityNode> queue = new LinkedList<EntityNode>(); queue.offer(this); while (! queue.isEmpty()) { EntityNode node = queue.poll(); for (CollectionMetaData collection : node.getValue().getCollections()) { if (! collection.isEntity()) { continue; } EntityNode child = new EntityNode(collection, namingStrategy); if (node.addChild(child) != null) { queue.offer(child); } } } } } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public void construct() { LinkedList<EntityNode> queue = new LinkedList<EntityNode>(); queue.offer(this); while (! queue.isEmpty()) { EntityNode node = queue.poll(); for (CollectionMetaData collection : node.getValue().getCollections()) { if (! collection.isEntity()) { continue; } EntityNode child = new EntityNode(collection, namingStrategy); if (node.addChild(child) != null) { queue.offer(child); } } } } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public void construct() { LinkedList<EntityNode> queue = new LinkedList<EntityNode>(); queue.offer(this); while (! queue.isEmpty()) { EntityNode node = queue.poll(); for (CollectionMetaData collection : node.getValue().getCollections()) { if (! collection.isEntity()) { continue; } EntityNode child = new EntityNode(collection, namingStrategy); if (node.addChild(child) != null) { queue.offer(child); } } } } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public void construct() { LinkedList<EntityNode> queue = new LinkedList<EntityNode>(); queue.offer(this); while (! queue.isEmpty()) { EntityNode node = queue.poll(); for (CollectionMetaData collection : node.getValue().getCollections()) { if (! collection.isEntity()) { continue; } EntityNode child = new EntityNode(collection, namingStrategy); if (node.addChild(child) != null) { queue.offer(child); } } } } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } |
@Test public void shouldPopulateEntityNodeName() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); assertEquals(entityNode.getName(), "compositeModel"); } | public String getName() { return name; } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getName() { return name; } } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getName() { return name; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getName() { return name; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getName() { return name; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } |
@Test public void shouldPopulateEntityResourceName() { entityNode = new EntityNode(CompositeModel.class, namingStrategy); assertEquals(entityNode.getResourceName(), "composite_models"); } | public String getResourceName() { return resourceName; } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getResourceName() { return resourceName; } } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getResourceName() { return resourceName; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getResourceName() { return resourceName; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public String getResourceName() { return resourceName; } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } |
@Test public void shouldPopulateEntityMetaData() { entityNode = new EntityNode(Parent.class, namingStrategy); assertEquals(entityNode.getEntityMetaData(), EntityMetaDataProvider.instance().getEntityMetaData(Parent.class)); } | public EntityMetaData getEntityMetaData() { return getValue(); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public EntityMetaData getEntityMetaData() { return getValue(); } } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public EntityMetaData getEntityMetaData() { return getValue(); } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public EntityMetaData getEntityMetaData() { return getValue(); } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } | EntityNode extends Node<EntityNode, EntityNodePath, EntityMetaData> { public EntityMetaData getEntityMetaData() { return getValue(); } EntityNode(Class<?> entityClass, NamingStrategy namingStrategy); EntityNode(Class<?> entityClass, String name, NamingStrategy namingStrategy); EntityNode(CollectionMetaData collection, NamingStrategy namingStrategy); void construct(); String getResourceName(); String getName(); EntityMetaData getEntityMetaData(); CollectionMetaData getSource(); EntityNodePath getEntityNodePath(String path); @Override String toString(); } |
@Test public void shouldCreateGeneratedClass() { wrapper = new ResourceWrapper(resource, entityClass); assertNotNull(wrapper.getGeneratedClass()); } | public CtClass getGeneratedClass() { return generatedClass; } | ResourceWrapper { public CtClass getGeneratedClass() { return generatedClass; } } | ResourceWrapper { public CtClass getGeneratedClass() { return generatedClass; } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { public CtClass getGeneratedClass() { return generatedClass; } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { public CtClass getGeneratedClass() { return generatedClass; } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test public void shouldCreateResourceClassCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourceClassCreator creator = wrapper.getResourceClassCreator(); assertEquals(creator.getEntityClass(), entityClass); assertEquals(creator.getPath(), resource.getPath()); assertEquals(creator.getResource(), resource); } | protected ResourceClassCreator getResourceClassCreator() { return new ResourceClassCreator(resource, namingStrategy, entityClass, path); } | ResourceWrapper { protected ResourceClassCreator getResourceClassCreator() { return new ResourceClassCreator(resource, namingStrategy, entityClass, path); } } | ResourceWrapper { protected ResourceClassCreator getResourceClassCreator() { return new ResourceClassCreator(resource, namingStrategy, entityClass, path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { protected ResourceClassCreator getResourceClassCreator() { return new ResourceClassCreator(resource, namingStrategy, entityClass, path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { protected ResourceClassCreator getResourceClassCreator() { return new ResourceClassCreator(resource, namingStrategy, entityClass, path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test public void shouldGetCreateMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, true, namingStrategy); CreateMethodCreator creator = wrapper.getCreateMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } | protected CreateMethodCreator getCreateMethodCreator(ResourcePath path) { return new CreateMethodCreator(generatedClass, resource, path, this.path); } | ResourceWrapper { protected CreateMethodCreator getCreateMethodCreator(ResourcePath path) { return new CreateMethodCreator(generatedClass, resource, path, this.path); } } | ResourceWrapper { protected CreateMethodCreator getCreateMethodCreator(ResourcePath path) { return new CreateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { protected CreateMethodCreator getCreateMethodCreator(ResourcePath path) { return new CreateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { protected CreateMethodCreator getCreateMethodCreator(ResourcePath path) { return new CreateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test public void shouldGetReadMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ReadMethodCreator creator = wrapper.getReadMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } | protected ReadMethodCreator getReadMethodCreator(ResourcePath path) { return new ReadMethodCreator(generatedClass, resource, path, this.path); } | ResourceWrapper { protected ReadMethodCreator getReadMethodCreator(ResourcePath path) { return new ReadMethodCreator(generatedClass, resource, path, this.path); } } | ResourceWrapper { protected ReadMethodCreator getReadMethodCreator(ResourcePath path) { return new ReadMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { protected ReadMethodCreator getReadMethodCreator(ResourcePath path) { return new ReadMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { protected ReadMethodCreator getReadMethodCreator(ResourcePath path) { return new ReadMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test public void shouldGetActionMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ActionMetaData action = mock(ActionMetaData.class); ActionMethodCreator creator = wrapper.getActionMethodCreator(resourcePath, action); assertMethodCreator(creator, resourcePath); assertEquals(creator.getAction(), action); } | protected ActionMethodCreator getActionMethodCreator(ResourcePath path, ActionMetaData action) { return new ActionMethodCreator(generatedClass, resource, path, this.path, action); } | ResourceWrapper { protected ActionMethodCreator getActionMethodCreator(ResourcePath path, ActionMetaData action) { return new ActionMethodCreator(generatedClass, resource, path, this.path, action); } } | ResourceWrapper { protected ActionMethodCreator getActionMethodCreator(ResourcePath path, ActionMetaData action) { return new ActionMethodCreator(generatedClass, resource, path, this.path, action); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { protected ActionMethodCreator getActionMethodCreator(ResourcePath path, ActionMetaData action) { return new ActionMethodCreator(generatedClass, resource, path, this.path, action); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { protected ActionMethodCreator getActionMethodCreator(ResourcePath path, ActionMetaData action) { return new ActionMethodCreator(generatedClass, resource, path, this.path, action); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test(expectedExceptions=TechnicalException.class) public void shouldThrowExceptionIfClientNameIsNotFoundInSession() { Session session = mock(Session.class); when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("unknownClient"); filter.getClient(session); } | protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected Client getClient(Session session) { String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER); if (Strings.isNullOrEmpty(clientName)) { return null; } return clients.findClient(clientName); } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); static final String PRINCIPAL; } |
@Test public void shouldGetDeleteMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); DeleteMethodCreator creator = wrapper.getDeleteMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } | protected DeleteMethodCreator getDeleteMethodCreator(ResourcePath path) { return new DeleteMethodCreator(generatedClass, resource, path, this.path); } | ResourceWrapper { protected DeleteMethodCreator getDeleteMethodCreator(ResourcePath path) { return new DeleteMethodCreator(generatedClass, resource, path, this.path); } } | ResourceWrapper { protected DeleteMethodCreator getDeleteMethodCreator(ResourcePath path) { return new DeleteMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { protected DeleteMethodCreator getDeleteMethodCreator(ResourcePath path) { return new DeleteMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { protected DeleteMethodCreator getDeleteMethodCreator(ResourcePath path) { return new DeleteMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test public void shouldGetListMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); ListMethodCreator creator = wrapper.getListMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } | protected ListMethodCreator getListMethodCreator(ResourcePath path) { return new ListMethodCreator(generatedClass, resource, path, this.path); } | ResourceWrapper { protected ListMethodCreator getListMethodCreator(ResourcePath path) { return new ListMethodCreator(generatedClass, resource, path, this.path); } } | ResourceWrapper { protected ListMethodCreator getListMethodCreator(ResourcePath path) { return new ListMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { protected ListMethodCreator getListMethodCreator(ResourcePath path) { return new ListMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { protected ListMethodCreator getListMethodCreator(ResourcePath path) { return new ListMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test public void shouldGetUpdateMethodCreator() { wrapper = spy(new ResourceWrapper(resource, entityClass)); ResourcePath resourcePath = new ResourcePath(path, false, namingStrategy); UpdateMethodCreator creator = wrapper.getUpdateMethodCreator(resourcePath); assertMethodCreator(creator, resourcePath); } | protected UpdateMethodCreator getUpdateMethodCreator(ResourcePath path) { return new UpdateMethodCreator(generatedClass, resource, path, this.path); } | ResourceWrapper { protected UpdateMethodCreator getUpdateMethodCreator(ResourcePath path) { return new UpdateMethodCreator(generatedClass, resource, path, this.path); } } | ResourceWrapper { protected UpdateMethodCreator getUpdateMethodCreator(ResourcePath path) { return new UpdateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); } | ResourceWrapper { protected UpdateMethodCreator getUpdateMethodCreator(ResourcePath path) { return new UpdateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } | ResourceWrapper { protected UpdateMethodCreator getUpdateMethodCreator(ResourcePath path) { return new UpdateMethodCreator(generatedClass, resource, path, this.path); } ResourceWrapper(ResourceMetaData resource, Class<?> entityClass); void addPath(EntityNodePath path); Class<?> wrap(); CtClass getGeneratedClass(); } |
@Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Path.class); } | public Class<?> getAnnotationType() { return Path.class; } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public Class<?> getAnnotationType() { return Path.class; } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public Class<?> getAnnotationType() { return Path.class; } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public Class<?> getAnnotationType() { return Path.class; } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public Class<?> getAnnotationType() { return Path.class; } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); static final Set<Class<? extends Annotation>> httpMethods; } |
@Test public void shouldAddSubResourceLocatorToResource() throws Exception { Path path = mock(Path.class); when(path.value()).thenReturn("/sub"); handler.handle(metaData, path, DummyResource.class.getMethod("subResource")); assertTrue(! metaData.getSubResources().isEmpty()); assertEquals(metaData.getSubResources().iterator().next(), new ResourceMetaData(DummySubResource.class, "/dummy/sub")); } | public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); static final Set<Class<? extends Annotation>> httpMethods; } |
@Test public void shouldNotAddSubResourceMethodToResource() throws Exception { Path path = mock(Path.class); when(path.value()).thenReturn("/sub1"); handler.handle(metaData, path, DummyResource.class.getMethod("methodWithHttpMethodAnnotation")); assertTrue(metaData.getSubResources().isEmpty()); } | public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); static final Set<Class<? extends Annotation>> httpMethods; } |
@Test public void shouldHandleGETAnnotation() throws Exception { GETAnnotationHandler handler = new GETAnnotationHandler(); handler.handle(metaData, mock(GET.class), DummyResource.class.getMethod("get")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy", HttpMethod.GET, DummyResource.class.getMethod("get"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandleGETAnnotationWithPath() throws Exception { GETAnnotationHandler handler = new GETAnnotationHandler(); handler.handle(metaData, mock(GET.class), DummyResource.class.getMethod("getWithPath")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/get", HttpMethod.GET, DummyResource.class.getMethod("getWithPath"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandlePOSTAnnotation() throws Exception { POSTAnnotationHandler handler = new POSTAnnotationHandler(); handler.handle(metaData, mock(POST.class), DummyResource.class.getMethod("post")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy", HttpMethod.POST, DummyResource.class.getMethod("post"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandlePOSTAnnotationWithPath() throws Exception { POSTAnnotationHandler handler = new POSTAnnotationHandler(); handler.handle(metaData, mock(POST.class), DummyResource.class.getMethod("postWithPath")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/post", HttpMethod.POST, DummyResource.class.getMethod("postWithPath"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldReturnNullProfileIfNotFoundInSession() { Session session = mock(Session.class); when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(null); assertNull(filter.retrieveProfile(session)); } | @SuppressWarnings("rawtypes") protected User retrieveProfile(Session session) { Object profile = session.getAttribute(PRINCIPAL); if (profile == null) { return null; } Client client = getClient(session); Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class); if (type.isAssignableFrom(profile.getClass())) { return new User((UserProfile) profile); } if (profile instanceof Map) { String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile); profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type); User user = new User((UserProfile) profile); session.addAttribute(PRINCIPAL, profile); return user; } return null; } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { @SuppressWarnings("rawtypes") protected User retrieveProfile(Session session) { Object profile = session.getAttribute(PRINCIPAL); if (profile == null) { return null; } Client client = getClient(session); Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class); if (type.isAssignableFrom(profile.getClass())) { return new User((UserProfile) profile); } if (profile instanceof Map) { String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile); profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type); User user = new User((UserProfile) profile); session.addAttribute(PRINCIPAL, profile); return user; } return null; } } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { @SuppressWarnings("rawtypes") protected User retrieveProfile(Session session) { Object profile = session.getAttribute(PRINCIPAL); if (profile == null) { return null; } Client client = getClient(session); Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class); if (type.isAssignableFrom(profile.getClass())) { return new User((UserProfile) profile); } if (profile instanceof Map) { String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile); profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type); User user = new User((UserProfile) profile); session.addAttribute(PRINCIPAL, profile); return user; } return null; } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { @SuppressWarnings("rawtypes") protected User retrieveProfile(Session session) { Object profile = session.getAttribute(PRINCIPAL); if (profile == null) { return null; } Client client = getClient(session); Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class); if (type.isAssignableFrom(profile.getClass())) { return new User((UserProfile) profile); } if (profile instanceof Map) { String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile); profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type); User user = new User((UserProfile) profile); session.addAttribute(PRINCIPAL, profile); return user; } return null; } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); } | AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { @SuppressWarnings("rawtypes") protected User retrieveProfile(Session session) { Object profile = session.getAttribute(PRINCIPAL); if (profile == null) { return null; } Client client = getClient(session); Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class); if (type.isAssignableFrom(profile.getClass())) { return new User((UserProfile) profile); } if (profile instanceof Map) { String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile); profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type); User user = new User((UserProfile) profile); session.addAttribute(PRINCIPAL, profile); return user; } return null; } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); static final String PRINCIPAL; } |
@Test public void shouldHandlePUTAnnotation() throws Exception { PUTAnnotationHandler handler = new PUTAnnotationHandler(); handler.handle(metaData, mock(PUT.class), DummyResource.class.getMethod("put")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy", HttpMethod.PUT, DummyResource.class.getMethod("put"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandlePUTAnnotationWithPath() throws Exception { PUTAnnotationHandler handler = new PUTAnnotationHandler(); handler.handle(metaData, mock(PUT.class), DummyResource.class.getMethod("putWithPath")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/put", HttpMethod.PUT, DummyResource.class.getMethod("putWithPath"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandleDELETEAnnotation() throws Exception { DELETEAnnotationHandler handler = new DELETEAnnotationHandler(); handler.handle(metaData, mock(DELETE.class), DummyResource.class.getMethod("delete")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy", HttpMethod.DELETE, DummyResource.class.getMethod("delete"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandleDELETEAnnotationWithPath() throws Exception { DELETEAnnotationHandler handler = new DELETEAnnotationHandler(); handler.handle(metaData, mock(DELETE.class), DummyResource.class.getMethod("deleteWithPath")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/delete", HttpMethod.DELETE, DummyResource.class.getMethod("deleteWithPath"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandleHEADAnnotation() throws Exception { HEADAnnotationHandler handler = new HEADAnnotationHandler(); handler.handle(metaData, mock(HEAD.class), DummyResource.class.getMethod("head")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy", HttpMethod.HEAD, DummyResource.class.getMethod("head"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandleHEADAnnotationWithPath() throws Exception { HEADAnnotationHandler handler = new HEADAnnotationHandler(); handler.handle(metaData, mock(HEAD.class), DummyResource.class.getMethod("headWithPath")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/head", HttpMethod.HEAD, DummyResource.class.getMethod("headWithPath"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandleOPTIONSAnnotation() throws Exception { OPTIONSAnnotationHandler handler = new OPTIONSAnnotationHandler(); handler.handle(metaData, mock(OPTIONS.class), DummyResource.class.getMethod("options")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy", HttpMethod.OPTIONS, DummyResource.class.getMethod("options"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldHandleOPTIONSAnnotationWithPath() throws Exception { OPTIONSAnnotationHandler handler = new OPTIONSAnnotationHandler(); handler.handle(metaData, mock(OPTIONS.class), DummyResource.class.getMethod("optionsWithPath")); assertTrue(! metaData.getResourceMethods().isEmpty()); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/options", HttpMethod.OPTIONS, DummyResource.class.getMethod("optionsWithPath"))); } | @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } | HttpMethodAnnotationHandler extends AbstractResourceAnnotationHandler { @Override public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { Path path = ClassUtils.getAnnotation(method, Path.class); String methodPath = HttpUtil.concatPaths(metaData.getPath(), path != null ? path.value() : null); ResourceMethodMetaData resourceMethod = new ResourceMethodMetaData(methodPath, getHttpMethod(), method); metaData.addResourceMethod(resourceMethod); } @Override void handle(ResourceMetaData metaData, Annotation annotation, Method method); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); } |
@Test public void shouldBuildResourceMetaData() throws Exception { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(DummyResource.class); ResourceMetaData metaData = builder.build(); assertEquals(metaData.getResourceMethods().size(), 1); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/sub1", HttpMethod.GET, DummyResource.class.getMethod("getMethod"))); } | @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } ResourceMetaDataBuilder(Class<?> resourceClass); ResourceMetaDataBuilder(ResourceMetaData metaData); } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } ResourceMetaDataBuilder(Class<?> resourceClass); ResourceMetaDataBuilder(ResourceMetaData metaData); @Override ResourceMetaData build(); } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } ResourceMetaDataBuilder(Class<?> resourceClass); ResourceMetaDataBuilder(ResourceMetaData metaData); @Override ResourceMetaData build(); } |
@Test public void shouldBuildSubResourceMetaData() throws Exception { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(DummyResource.class); ResourceMetaData metaData = builder.build(); assertEquals(metaData.getSubResources().size(), 1); ResourceMetaData subResource = metaData.getSubResources().iterator().next(); assertEquals(subResource.getResourceMethods().size(), 1); assertEquals(subResource.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/sub/get", HttpMethod.GET, DummySubResource.class.getMethod("subGetMethod"))); } | @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } ResourceMetaDataBuilder(Class<?> resourceClass); ResourceMetaDataBuilder(ResourceMetaData metaData); } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } ResourceMetaDataBuilder(Class<?> resourceClass); ResourceMetaDataBuilder(ResourceMetaData metaData); @Override ResourceMetaData build(); } | ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } ResourceMetaDataBuilder(Class<?> resourceClass); ResourceMetaDataBuilder(ResourceMetaData metaData); @Override ResourceMetaData build(); } |
@Test public void shouldNotFilterIfRequestIsNotACallback() { when(uriInfo.getPath()).thenReturn("/dummy"); filter.filter(context); verify(filter, never()).getSession(context, true); } | @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); } |
@Test public void shouldCreateFilter() { MultivaluedMap<String, String> map = mock(MultivaluedMap.class); when(map.getFirst(ResourceUtil.PAGE_NO)).thenReturn("1"); when(map.getFirst(ResourceUtil.PER_PAGE)).thenReturn("10"); assertEquals(ResourceUtil.getFilter(map), new Filter(10, 1)); } | public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldCreateFilterWithSearchParams() { MultivaluedMap<String, String> map = mock(MultivaluedMap.class); when(map.getFirst(ResourceUtil.PAGE_NO)).thenReturn("1"); when(map.getFirst(ResourceUtil.PER_PAGE)).thenReturn("10"); when(map.getFirst("param1")).thenReturn("value1"); when(map.getFirst("param2")).thenReturn("value2"); List<String> params = Arrays.asList("param1", "param2"); assertEquals(ResourceUtil.getFilter(map, params), new Filter(10, 1, new Condition("param1", "value1"), new Condition("param2", "value2"))); } | public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldCreateFilterWithUnderscoreSeparatedSearchParams() { MultivaluedMap<String, String> map = mock(MultivaluedMap.class); when(map.getFirst(ResourceUtil.PAGE_NO)).thenReturn("1"); when(map.getFirst(ResourceUtil.PER_PAGE)).thenReturn("10"); when(map.getFirst("param_name1")).thenReturn("value1"); when(map.getFirst("param_name2")).thenReturn("value2"); List<String> params = Arrays.asList("param_name1", "param_name2"); assertEquals(ResourceUtil.getFilter(map, params), new Filter(10, 1, new Condition("paramName1", "value1"), new Condition("paramName2", "value2"))); } | public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldGetContentAsMap() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "value1"); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(map); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, new Annotation[]{}, mediaType)).thenReturn(reader); Object content = ResourceUtil.getContent(bytes, providers, httpHeaders, Map.class); assertTrue(content instanceof Map); assertEquals(content, map); } | public static <T> T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations) { MessageBodyReader<T> reader = providers.getMessageBodyReader(type, genericType, annotations, httpHeaders.getMediaType()); try { return reader.readFrom(type, genericType, annotations, httpHeaders.getMediaType(), httpHeaders.getRequestHeaders(), inputStream); } catch (Exception e) {e.printStackTrace(); throw new MinnalInstrumentationException("Failed while getting the content from the request stream", e); } } | ResourceUtil { public static <T> T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations) { MessageBodyReader<T> reader = providers.getMessageBodyReader(type, genericType, annotations, httpHeaders.getMediaType()); try { return reader.readFrom(type, genericType, annotations, httpHeaders.getMediaType(), httpHeaders.getRequestHeaders(), inputStream); } catch (Exception e) {e.printStackTrace(); throw new MinnalInstrumentationException("Failed while getting the content from the request stream", e); } } } | ResourceUtil { public static <T> T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations) { MessageBodyReader<T> reader = providers.getMessageBodyReader(type, genericType, annotations, httpHeaders.getMediaType()); try { return reader.readFrom(type, genericType, annotations, httpHeaders.getMediaType(), httpHeaders.getRequestHeaders(), inputStream); } catch (Exception e) {e.printStackTrace(); throw new MinnalInstrumentationException("Failed while getting the content from the request stream", e); } } } | ResourceUtil { public static <T> T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations) { MessageBodyReader<T> reader = providers.getMessageBodyReader(type, genericType, annotations, httpHeaders.getMediaType()); try { return reader.readFrom(type, genericType, annotations, httpHeaders.getMediaType(), httpHeaders.getRequestHeaders(), inputStream); } catch (Exception e) {e.printStackTrace(); throw new MinnalInstrumentationException("Failed while getting the content from the request stream", e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static <T> T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations) { MessageBodyReader<T> reader = providers.getMessageBodyReader(type, genericType, annotations, httpHeaders.getMediaType()); try { return reader.readFrom(type, genericType, annotations, httpHeaders.getMediaType(), httpHeaders.getRequestHeaders(), inputStream); } catch (Exception e) {e.printStackTrace(); throw new MinnalInstrumentationException("Failed while getting the content from the request stream", e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldCheckIfStringIsCommaSeparated() { assertTrue(ResourceUtil.isCommaSeparated("test,test1")); assertFalse(ResourceUtil.isCommaSeparated("testtest1")); } | public static boolean isCommaSeparated(String value) { return value.contains(","); } | ResourceUtil { public static boolean isCommaSeparated(String value) { return value.contains(","); } } | ResourceUtil { public static boolean isCommaSeparated(String value) { return value.contains(","); } } | ResourceUtil { public static boolean isCommaSeparated(String value) { return value.contains(","); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static boolean isCommaSeparated(String value) { return value.contains(","); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldGetCommaSeparatedValues() { assertEquals(ResourceUtil.getCommaSeparatedValues("test,test1"), new String[]{"test", "test1"}); assertEquals(ResourceUtil.getCommaSeparatedValues("testtest1"), new String[]{"testtest1"}); } | public static String[] getCommaSeparatedValues(String value) { return value.split(","); } | ResourceUtil { public static String[] getCommaSeparatedValues(String value) { return value.split(","); } } | ResourceUtil { public static String[] getCommaSeparatedValues(String value) { return value.split(","); } } | ResourceUtil { public static String[] getCommaSeparatedValues(String value) { return value.split(","); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static String[] getCommaSeparatedValues(String value) { return value.split(","); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldInvokeMethodWithNoArguments() throws Throwable { Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(values); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); assertEquals(ResourceUtil.invokeAction(model, "dummyAction", new ArrayList<ParameterMetaData>(), bytes, providers, httpHeaders, values), "dummy"); } | public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldInvokeMethodWithArguments() throws Throwable { Map<String, Object> content = new HashMap<String, Object>(); content.put("value", "test123"); content.put("someNumber", 1L); Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(content); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); assertEquals(ResourceUtil.invokeAction(model, "dummyActionWithArguments", Lists.newArrayList(new ParameterMetaData("value", "value", String.class), new ParameterMetaData("someNumber", "someNumber", Long.class)), bytes, providers, httpHeaders, values), "dummyActionWithArguments"); } | public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldInvokeMethodWithArgumentsAndModel() throws Throwable { Map<String, Object> content = new HashMap<String, Object>(); content.put("value", "test123"); content.put("someNumber", 1L); Map<String, Object> values = new HashMap<String, Object>(); values.put("anotherModel", new DummyModel()); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(content); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); assertEquals(ResourceUtil.invokeAction(model, "dummyActionWithArgumentsAndModel", Lists.newArrayList(new ParameterMetaData("anotherModel", "anotherModel", DummyModel.class), new ParameterMetaData("value", "value", String.class), new ParameterMetaData("someNumber", "someNumber", Long.class)), bytes, providers, httpHeaders, values), "dummyActionWithArgumentsAndModel"); } | public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test(expectedExceptions=MinnalInstrumentationException.class) public void shouldThrowExceptionIfMethodNotFound() throws Throwable { Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(values); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); ResourceUtil.invokeAction(model, "nonExistingMethod", Lists.newArrayList(new ParameterMetaData("anotherModel", "anotherModel", DummyModel.class)), bytes, providers, httpHeaders, values); } | public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldReturnUnAcceptableIfClientNameNotSet() { Session session = mock(Session.class); Response response = mock(Response.class); JaxrsWebContext webContext = mock(JaxrsWebContext.class); when(webContext.getResponse()).thenReturn(response); doReturn(session).when(filter).getSession(context, true); doReturn(webContext).when(filter).getContext(context, session); doReturn(null).when(filter).getClient(session); filter.filter(context); verify(webContext).setResponseStatus(422); verify(context).abortWith(response); verify(listener).authFailed(session); } | @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); } |
@Test(expectedExceptions=IllegalStateException.class) public void shouldThrowExceptionIfMethodThrowsAnyException() throws Throwable { Map<String, Object> values = new HashMap<String, Object>(); DummyModel model = new DummyModel(); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), isNull(Annotation[].class), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(values); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, null, mediaType)).thenReturn(reader); ResourceUtil.invokeAction(model, "throwsException", new ArrayList<ParameterMetaData>(), bytes, providers, httpHeaders, values); } | public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); } | ResourceUtil { public static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values) throws Throwable { List<Class<?>> types = Lists.transform(parameters, new Function<ParameterMetaData, Class<?>>() { @Override public Class<?> apply(ParameterMetaData input) { return input == null ? null : input.getType(); } }); Method method = MethodUtils.getAccessibleMethod(model.getClass(), actionName, types.toArray(new Class[0])); if (method == null) { logger.error("Unable to get the action - {} for the model - {}", actionName, model.getClass()); throw new MinnalInstrumentationException("Unable to get the action - " + actionName + " for the model - " + model.getClass()); } Map<String, Object> payload = getContent(new ByteArrayInputStream(rawContent), providers, httpHeaders, Map.class, Map.class, null); Object[] arguments = getActionParameterValues(parameters, payload, values); try { return method.invoke(model, arguments); } catch (InvocationTargetException e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw e.getCause(); } catch (Exception e) { logger.error("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); throw new MinnalInstrumentationException("Failed while invoking the action - " + actionName + " for the model - " + model.getClass(), e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders,
Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; } |
@Test public void shouldScanClasses() { Scanner<Class<?>> scanner = mock(Scanner.class); enhancer.scanClasses(scanner); verify(scanner).scan(any(Listener.class)); } | protected List<Class<?>> scanClasses(Scanner<Class<?>> scanner) { final List<Class<?>> classes = new ArrayList<Class<?>>(); scanner.scan(new Listener<Class<?>>() { public void handle(Class<?> t) { classes.add(t); } }); return classes; } | ApplicationEnhancer { protected List<Class<?>> scanClasses(Scanner<Class<?>> scanner) { final List<Class<?>> classes = new ArrayList<Class<?>>(); scanner.scan(new Listener<Class<?>>() { public void handle(Class<?> t) { classes.add(t); } }); return classes; } } | ApplicationEnhancer { protected List<Class<?>> scanClasses(Scanner<Class<?>> scanner) { final List<Class<?>> classes = new ArrayList<Class<?>>(); scanner.scan(new Listener<Class<?>>() { public void handle(Class<?> t) { classes.add(t); } }); return classes; } ApplicationEnhancer(Application application, NamingStrategy namingStrategy, String[] entityPackages, String[] resourcePackages); } | ApplicationEnhancer { protected List<Class<?>> scanClasses(Scanner<Class<?>> scanner) { final List<Class<?>> classes = new ArrayList<Class<?>>(); scanner.scan(new Listener<Class<?>>() { public void handle(Class<?> t) { classes.add(t); } }); return classes; } ApplicationEnhancer(Application application, NamingStrategy namingStrategy, String[] entityPackages, String[] resourcePackages); void enhance(); } | ApplicationEnhancer { protected List<Class<?>> scanClasses(Scanner<Class<?>> scanner) { final List<Class<?>> classes = new ArrayList<Class<?>>(); scanner.scan(new Listener<Class<?>>() { public void handle(Class<?> t) { classes.add(t); } }); return classes; } ApplicationEnhancer(Application application, NamingStrategy namingStrategy, String[] entityPackages, String[] resourcePackages); void enhance(); } |
@Test void shouldFormatMetricName(){ FullHttpResponse response = mock(FullHttpResponse.class); when(response.getStatus()).thenReturn(HttpResponseStatus.OK); when(context.getResponse()).thenReturn(response); when(context.getMatchedRoute()).thenReturn("/facilities/{id}/stations/{station_id}"); when(request.getMethod()).thenReturn(HttpMethod.GET); assertEquals("facilities.id.stations.station_id.GET.responseTime",collector.getMetricName(context, collector.RESPONSE_TIME)); } | protected String getMetricName(MessageContext context, String metricName) { String name = null; if (! Strings.isNullOrEmpty(context.getMatchedRoute())) { name = context.getMatchedRoute(); } else { name = context.getApplication().getConfiguration().getName(); } name = formatName(name); return MetricRegistry.name(name, context.getRequest().getMethod().toString(), metricName); } | ResponseMetricCollector extends MessageListenerAdapter { protected String getMetricName(MessageContext context, String metricName) { String name = null; if (! Strings.isNullOrEmpty(context.getMatchedRoute())) { name = context.getMatchedRoute(); } else { name = context.getApplication().getConfiguration().getName(); } name = formatName(name); return MetricRegistry.name(name, context.getRequest().getMethod().toString(), metricName); } } | ResponseMetricCollector extends MessageListenerAdapter { protected String getMetricName(MessageContext context, String metricName) { String name = null; if (! Strings.isNullOrEmpty(context.getMatchedRoute())) { name = context.getMatchedRoute(); } else { name = context.getApplication().getConfiguration().getName(); } name = formatName(name); return MetricRegistry.name(name, context.getRequest().getMethod().toString(), metricName); } } | ResponseMetricCollector extends MessageListenerAdapter { protected String getMetricName(MessageContext context, String metricName) { String name = null; if (! Strings.isNullOrEmpty(context.getMatchedRoute())) { name = context.getMatchedRoute(); } else { name = context.getApplication().getConfiguration().getName(); } name = formatName(name); return MetricRegistry.name(name, context.getRequest().getMethod().toString(), metricName); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); } | ResponseMetricCollector extends MessageListenerAdapter { protected String getMetricName(MessageContext context, String metricName) { String name = null; if (! Strings.isNullOrEmpty(context.getMatchedRoute())) { name = context.getMatchedRoute(); } else { name = context.getApplication().getConfiguration().getName(); } name = formatName(name); return MetricRegistry.name(name, context.getRequest().getMethod().toString(), metricName); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; } |
@Test public void shouldSetStartTimeOnMessageReceive() { collector.onReceived(context); verify(context).addAttribute(eq(ResponseMetricCollector.START_TIME), any(Long.class)); } | @Override public void onReceived(MessageContext context) { context.addAttribute(START_TIME, clock.getTick()); } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onReceived(MessageContext context) { context.addAttribute(START_TIME, clock.getTick()); } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onReceived(MessageContext context) { context.addAttribute(START_TIME, clock.getTick()); } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onReceived(MessageContext context) { context.addAttribute(START_TIME, clock.getTick()); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onReceived(MessageContext context) { context.addAttribute(START_TIME, clock.getTick()); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; } |
@Test public void shouldSetSuccessfulOnSuccess() { FullHttpResponse response = mock(FullHttpResponse.class); when(response.getStatus()).thenReturn(HttpResponseStatus.OK); when(context.getResponse()).thenReturn(response); collector.onSuccess(context); verify(context).addAttribute(eq(ResponseMetricCollector.SUCCESSFUL), eq(Boolean.TRUE)); } | @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; } |
@Test public void shouldSetNotSuccessfulOn4xx() { FullHttpResponse response = mock(FullHttpResponse.class); when(response.getStatus()).thenReturn(HttpResponseStatus.NOT_FOUND); when(context.getResponse()).thenReturn(response); collector.onSuccess(context); verify(context).addAttribute(eq(ResponseMetricCollector.SUCCESSFUL), eq(Boolean.FALSE)); } | @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; } |
@Test public void shouldLogExceptionOnCompletion() { when(context.getAttribute(ResponseMetricCollector.SUCCESSFUL)).thenReturn(null); when(context.getApplication()).thenReturn(application); Meter meter = mock(Meter.class); when(metricRegistry.meter("test." + ResponseMetricCollector.EXCEPTIONS)).thenReturn(meter); collector.onComplete(context); verify(meter).mark(); } | @Override public void onComplete(MessageContext context) { String name = null; Boolean successful = (Boolean) context.getAttribute(SUCCESSFUL); if (successful == null) { name = MetricRegistry.name(context.getApplication().getConfiguration().getName(), EXCEPTIONS); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } else { if (! successful) { name = getMetricName(context, Integer.toString(context.getResponse().getStatus().code())); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } name = getMetricName(context, RESPONSE_TIME); Timer timer = MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).timer(name); timer.update(clock.getTick() - (Long) context.getAttribute(START_TIME), TimeUnit.NANOSECONDS); } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onComplete(MessageContext context) { String name = null; Boolean successful = (Boolean) context.getAttribute(SUCCESSFUL); if (successful == null) { name = MetricRegistry.name(context.getApplication().getConfiguration().getName(), EXCEPTIONS); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } else { if (! successful) { name = getMetricName(context, Integer.toString(context.getResponse().getStatus().code())); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } name = getMetricName(context, RESPONSE_TIME); Timer timer = MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).timer(name); timer.update(clock.getTick() - (Long) context.getAttribute(START_TIME), TimeUnit.NANOSECONDS); } } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onComplete(MessageContext context) { String name = null; Boolean successful = (Boolean) context.getAttribute(SUCCESSFUL); if (successful == null) { name = MetricRegistry.name(context.getApplication().getConfiguration().getName(), EXCEPTIONS); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } else { if (! successful) { name = getMetricName(context, Integer.toString(context.getResponse().getStatus().code())); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } name = getMetricName(context, RESPONSE_TIME); Timer timer = MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).timer(name); timer.update(clock.getTick() - (Long) context.getAttribute(START_TIME), TimeUnit.NANOSECONDS); } } } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onComplete(MessageContext context) { String name = null; Boolean successful = (Boolean) context.getAttribute(SUCCESSFUL); if (successful == null) { name = MetricRegistry.name(context.getApplication().getConfiguration().getName(), EXCEPTIONS); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } else { if (! successful) { name = getMetricName(context, Integer.toString(context.getResponse().getStatus().code())); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } name = getMetricName(context, RESPONSE_TIME); Timer timer = MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).timer(name); timer.update(clock.getTick() - (Long) context.getAttribute(START_TIME), TimeUnit.NANOSECONDS); } } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); } | ResponseMetricCollector extends MessageListenerAdapter { @Override public void onComplete(MessageContext context) { String name = null; Boolean successful = (Boolean) context.getAttribute(SUCCESSFUL); if (successful == null) { name = MetricRegistry.name(context.getApplication().getConfiguration().getName(), EXCEPTIONS); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } else { if (! successful) { name = getMetricName(context, Integer.toString(context.getResponse().getStatus().code())); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } name = getMetricName(context, RESPONSE_TIME); Timer timer = MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).timer(name); timer.update(clock.getTick() - (Long) context.getAttribute(START_TIME), TimeUnit.NANOSECONDS); } } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; } |
@Test public void shouldInitializeMetrics() { bundle.init(container, configuration); verify(container).registerListener(bundle); verify(container).registerListener(any(ResponseMetricCollector.class)); } | @Override public void init(Container container, MetricsBundleConfiguration configuration) { this.configuration = configuration; container.registerListener(this); container.registerListener(responseMetricCollector); } | MetricsBundle extends ContainerAdapter implements Bundle<MetricsBundleConfiguration> { @Override public void init(Container container, MetricsBundleConfiguration configuration) { this.configuration = configuration; container.registerListener(this); container.registerListener(responseMetricCollector); } } | MetricsBundle extends ContainerAdapter implements Bundle<MetricsBundleConfiguration> { @Override public void init(Container container, MetricsBundleConfiguration configuration) { this.configuration = configuration; container.registerListener(this); container.registerListener(responseMetricCollector); } } | MetricsBundle extends ContainerAdapter implements Bundle<MetricsBundleConfiguration> { @Override public void init(Container container, MetricsBundleConfiguration configuration) { this.configuration = configuration; container.registerListener(this); container.registerListener(responseMetricCollector); } @Override void init(Container container, MetricsBundleConfiguration configuration); @Override void start(); @Override void stop(); @Override int getOrder(); @Override void postMount(Application<ApplicationConfiguration> application); @Override void postUnMount(Application<ApplicationConfiguration> application); } | MetricsBundle extends ContainerAdapter implements Bundle<MetricsBundleConfiguration> { @Override public void init(Container container, MetricsBundleConfiguration configuration) { this.configuration = configuration; container.registerListener(this); container.registerListener(responseMetricCollector); } @Override void init(Container container, MetricsBundleConfiguration configuration); @Override void start(); @Override void stop(); @Override int getOrder(); @Override void postMount(Application<ApplicationConfiguration> application); @Override void postUnMount(Application<ApplicationConfiguration> application); } |
@Test public void shouldStructureUrlIfEmptyOrNull() { assertEquals(HttpUtil.structureUrl(null), HttpUtil.SEPARATOR); assertEquals(HttpUtil.structureUrl(""), HttpUtil.SEPARATOR); } | public static String structureUrl(String url) { if (url == null || url.equals("")) { return SEPARATOR; } if (! url.startsWith(SEPARATOR)) { url = SEPARATOR + url; } if (url.endsWith(SEPARATOR)) { url = url.substring(0, url.length() - 1); } return url; } | HttpUtil { public static String structureUrl(String url) { if (url == null || url.equals("")) { return SEPARATOR; } if (! url.startsWith(SEPARATOR)) { url = SEPARATOR + url; } if (url.endsWith(SEPARATOR)) { url = url.substring(0, url.length() - 1); } return url; } } | HttpUtil { public static String structureUrl(String url) { if (url == null || url.equals("")) { return SEPARATOR; } if (! url.startsWith(SEPARATOR)) { url = SEPARATOR + url; } if (url.endsWith(SEPARATOR)) { url = url.substring(0, url.length() - 1); } return url; } } | HttpUtil { public static String structureUrl(String url) { if (url == null || url.equals("")) { return SEPARATOR; } if (! url.startsWith(SEPARATOR)) { url = SEPARATOR + url; } if (url.endsWith(SEPARATOR)) { url = url.substring(0, url.length() - 1); } return url; } static Map<String, String> getQueryParameters(URI uri); static String decode(String value); static String encode(String value); static URI createURI(String scheme, String host, String path); static URI createURI(String uri); static Map<String, String> getCookies(String cookieHeader); static String createCookie(Map<String, String> cookies); static String structureUrl(String url); static String getRootSegment(String path); static String concatPaths(String... paths); static String deriveRelativePath(String basePath, String absolutePath); static void main(String[] args); } | HttpUtil { public static String structureUrl(String url) { if (url == null || url.equals("")) { return SEPARATOR; } if (! url.startsWith(SEPARATOR)) { url = SEPARATOR + url; } if (url.endsWith(SEPARATOR)) { url = url.substring(0, url.length() - 1); } return url; } static Map<String, String> getQueryParameters(URI uri); static String decode(String value); static String encode(String value); static URI createURI(String scheme, String host, String path); static URI createURI(String uri); static Map<String, String> getCookies(String cookieHeader); static String createCookie(Map<String, String> cookies); static String structureUrl(String url); static String getRootSegment(String path); static String concatPaths(String... paths); static String deriveRelativePath(String basePath, String absolutePath); static void main(String[] args); static final String SEPARATOR; } |
@Test public void shouldGetRouteElements() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items"); assertEquals(pattern.getElements().size(), 3); assertEquals(pattern.getElements().get(0).getName(), "orders"); assertFalse(pattern.getElements().get(0).isParameter()); assertTrue(pattern.getElements().get(1).isParameter()); } | public List<RouteElement> getElements() { List<RouteElement> elements = new ArrayList<RoutePattern.RouteElement>(); for (String element : Splitter.on("/").split(pathPattern)) { elements.add(new RouteElement(element, PLACEHOLDER_PATTERN.matcher(element).matches())); } if (elements.isEmpty()) { System.out.println(""); } elements.remove(0); return elements; } | RoutePattern { public List<RouteElement> getElements() { List<RouteElement> elements = new ArrayList<RoutePattern.RouteElement>(); for (String element : Splitter.on("/").split(pathPattern)) { elements.add(new RouteElement(element, PLACEHOLDER_PATTERN.matcher(element).matches())); } if (elements.isEmpty()) { System.out.println(""); } elements.remove(0); return elements; } } | RoutePattern { public List<RouteElement> getElements() { List<RouteElement> elements = new ArrayList<RoutePattern.RouteElement>(); for (String element : Splitter.on("/").split(pathPattern)) { elements.add(new RouteElement(element, PLACEHOLDER_PATTERN.matcher(element).matches())); } if (elements.isEmpty()) { System.out.println(""); } elements.remove(0); return elements; } RoutePattern(String pathPattern); } | RoutePattern { public List<RouteElement> getElements() { List<RouteElement> elements = new ArrayList<RoutePattern.RouteElement>(); for (String element : Splitter.on("/").split(pathPattern)) { elements.add(new RouteElement(element, PLACEHOLDER_PATTERN.matcher(element).matches())); } if (elements.isEmpty()) { System.out.println(""); } elements.remove(0); return elements; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public List<RouteElement> getElements() { List<RouteElement> elements = new ArrayList<RoutePattern.RouteElement>(); for (String element : Splitter.on("/").split(pathPattern)) { elements.add(new RouteElement(element, PLACEHOLDER_PATTERN.matcher(element).matches())); } if (elements.isEmpty()) { System.out.println(""); } elements.remove(0); return elements; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldReturnOkIfClientNameIsSet() throws RequiresHttpAction { Session session = mock(Session.class); Response response = mock(Response.class); JaxrsWebContext webContext = mock(JaxrsWebContext.class); when(webContext.getResponse()).thenReturn(response); doReturn(session).when(filter).getSession(context, true); doReturn(webContext).when(filter).getContext(context, session); doReturn(client).when(filter).getClient(session); Credentials credentials = mock(Credentials.class); HttpProfile profile = mock(HttpProfile.class); when(client.getCredentials(webContext)).thenReturn(credentials); when(client.getUserProfile(credentials, webContext)).thenReturn(profile); filter.filter(context); verify(session).addAttribute(AuthenticationFilter.PRINCIPAL, profile); verify(session).addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "client1"); verify(sessionStore).save(session); verify(webContext).setResponseStatus(Response.Status.OK.getStatusCode()); verify(listener).authSuccess(session, profile); verify(context).abortWith(response); } | @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); } | CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); } |
@Test public void shouldFetchParameterNames() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); assertNotNull(pattern.getParameterNames()); assertEquals(pattern.getParameterNames(), Arrays.asList("order_id", "id")); } | public List<String> getParameterNames() { return parameterNames; } | RoutePattern { public List<String> getParameterNames() { return parameterNames; } } | RoutePattern { public List<String> getParameterNames() { return parameterNames; } RoutePattern(String pathPattern); } | RoutePattern { public List<String> getParameterNames() { return parameterNames; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public List<String> getParameterNames() { return parameterNames; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldMatchAPathWithAlphaNumericParamsToPattern() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); assertTrue(pattern.matches("/orders/code1/order_items/1code")); } | public boolean matches(String path) { return regex.matcher(path).matches(); } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } RoutePattern(String pathPattern); } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldMatchAPathWithSpecialCharacterParamsToPattern() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); assertTrue(pattern.matches("/orders/order_1/order_items/order-item-1")); } | public boolean matches(String path) { return regex.matcher(path).matches(); } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } RoutePattern(String pathPattern); } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldGetParameterMapForAValidPath() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); Map<String, String> params = pattern.match("/orders/1/order_items/124"); assertNotNull(params); assertEquals(params.get("order_id"), "1"); assertEquals(params.get("id"), "124"); } | public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldNotGetParameterMapForAnInvalidPath() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); Map<String, String> params = pattern.match("/orders/order_items/124"); assertNull(params); } | public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldGetEmptyParameterMapForAPathWithoutParameters() { RoutePattern pattern = new RoutePattern("/orders/1/order_items/124"); Map<String, String> params = pattern.match("/orders/1/order_items/124"); assertNotNull(params); assertTrue(params.isEmpty()); } | public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldMatchUrlEncodedString() { RoutePattern pattern = new RoutePattern("/orders/{order_id}"); Map<String, String> params = pattern.match("/orders/1234%2F1"); assertEquals(params.get("order_id"), "1234/1"); } | public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } | RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); } |
@Test public void shouldReturnOpenSessionInViewFilterOnRequestEvent() { DatabaseConfiguration configuration = mock(DatabaseConfiguration.class); JerseyApplicationEventListener listener = new JerseyApplicationEventListener(configuration); RequestEvent requestEvent = mock(RequestEvent.class); RequestEventListener eventListener = listener.onRequest(requestEvent); assertTrue(eventListener instanceof OpenSessionInViewFilter); assertEquals(((OpenSessionInViewFilter)eventListener).getConfiguration(), configuration); } | @Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new OpenSessionInViewFilter(configuration); } | JerseyApplicationEventListener implements ApplicationEventListener { @Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new OpenSessionInViewFilter(configuration); } } | JerseyApplicationEventListener implements ApplicationEventListener { @Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new OpenSessionInViewFilter(configuration); } JerseyApplicationEventListener(DatabaseConfiguration configuration); } | JerseyApplicationEventListener implements ApplicationEventListener { @Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new OpenSessionInViewFilter(configuration); } JerseyApplicationEventListener(DatabaseConfiguration configuration); @Override void onEvent(ApplicationEvent event); @Override RequestEventListener onRequest(RequestEvent requestEvent); } | JerseyApplicationEventListener implements ApplicationEventListener { @Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new OpenSessionInViewFilter(configuration); } JerseyApplicationEventListener(DatabaseConfiguration configuration); @Override void onEvent(ApplicationEvent event); @Override RequestEventListener onRequest(RequestEvent requestEvent); } |
@Test public void shouldInitializeEntityManagerWhenRequestReceived() throws IOException { filter.requestReceived(request); verify(context).getEntityManager(); } | protected void requestReceived(ContainerRequest request) { JPAContext context = getContext(); context.getEntityManager(); contextCreated.set(true); } | OpenSessionInViewFilter implements RequestEventListener { protected void requestReceived(ContainerRequest request) { JPAContext context = getContext(); context.getEntityManager(); contextCreated.set(true); } } | OpenSessionInViewFilter implements RequestEventListener { protected void requestReceived(ContainerRequest request) { JPAContext context = getContext(); context.getEntityManager(); contextCreated.set(true); } OpenSessionInViewFilter(DatabaseConfiguration configuration); } | OpenSessionInViewFilter implements RequestEventListener { protected void requestReceived(ContainerRequest request) { JPAContext context = getContext(); context.getEntityManager(); contextCreated.set(true); } OpenSessionInViewFilter(DatabaseConfiguration configuration); @Override void onEvent(RequestEvent event); DatabaseConfiguration getConfiguration(); } | OpenSessionInViewFilter implements RequestEventListener { protected void requestReceived(ContainerRequest request) { JPAContext context = getContext(); context.getEntityManager(); contextCreated.set(true); } OpenSessionInViewFilter(DatabaseConfiguration configuration); @Override void onEvent(RequestEvent event); DatabaseConfiguration getConfiguration(); } |
@Test public void shouldInitPlugin() { EntityManagerFactory factory = mock(EntityManagerFactory.class); when(provider.createContainerEntityManagerFactory(persistenceUnitInfo, null)).thenReturn(factory); plugin.init(application); assertEquals(JPA.instance.getDefaultConfig().getEntityManagerFactory(), factory); } | public void init(Application<? extends ApplicationConfiguration> application) { List<PersistenceProvider> providers = getProviders(); if (providers == null || providers.isEmpty()) { throw new MinnalException("No JPA persistence provider found"); } PersistenceProvider provider = providers.get(0); PersistenceUnitInfo info = createPersistenceUnitInfo(application.getConfiguration(), provider); factory = provider.createContainerEntityManagerFactory(info, null); JPA.instance.addPersistenceUnit(info.getPersistenceUnitName(), factory); application.addListener(new JerseyApplicationEventListener(application.getConfiguration().getDatabaseConfiguration())); } | JPAPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { List<PersistenceProvider> providers = getProviders(); if (providers == null || providers.isEmpty()) { throw new MinnalException("No JPA persistence provider found"); } PersistenceProvider provider = providers.get(0); PersistenceUnitInfo info = createPersistenceUnitInfo(application.getConfiguration(), provider); factory = provider.createContainerEntityManagerFactory(info, null); JPA.instance.addPersistenceUnit(info.getPersistenceUnitName(), factory); application.addListener(new JerseyApplicationEventListener(application.getConfiguration().getDatabaseConfiguration())); } } | JPAPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { List<PersistenceProvider> providers = getProviders(); if (providers == null || providers.isEmpty()) { throw new MinnalException("No JPA persistence provider found"); } PersistenceProvider provider = providers.get(0); PersistenceUnitInfo info = createPersistenceUnitInfo(application.getConfiguration(), provider); factory = provider.createContainerEntityManagerFactory(info, null); JPA.instance.addPersistenceUnit(info.getPersistenceUnitName(), factory); application.addListener(new JerseyApplicationEventListener(application.getConfiguration().getDatabaseConfiguration())); } } | JPAPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { List<PersistenceProvider> providers = getProviders(); if (providers == null || providers.isEmpty()) { throw new MinnalException("No JPA persistence provider found"); } PersistenceProvider provider = providers.get(0); PersistenceUnitInfo info = createPersistenceUnitInfo(application.getConfiguration(), provider); factory = provider.createContainerEntityManagerFactory(info, null); JPA.instance.addPersistenceUnit(info.getPersistenceUnitName(), factory); application.addListener(new JerseyApplicationEventListener(application.getConfiguration().getDatabaseConfiguration())); } void init(Application<? extends ApplicationConfiguration> application); void destroy(); } | JPAPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { List<PersistenceProvider> providers = getProviders(); if (providers == null || providers.isEmpty()) { throw new MinnalException("No JPA persistence provider found"); } PersistenceProvider provider = providers.get(0); PersistenceUnitInfo info = createPersistenceUnitInfo(application.getConfiguration(), provider); factory = provider.createContainerEntityManagerFactory(info, null); JPA.instance.addPersistenceUnit(info.getPersistenceUnitName(), factory); application.addListener(new JerseyApplicationEventListener(application.getConfiguration().getDatabaseConfiguration())); } void init(Application<? extends ApplicationConfiguration> application); void destroy(); } |
@Test public void shouldCreateSession() { Session session = sessionStore.createSession("test123"); assertNotNull(session); assertEquals(JpaSession.one("id", "test123"), session); } | public Session createSession(String id) { JpaSession session = new JpaSession(id); session.persist(); return session; } | JpaSessionStore implements SessionStore { public Session createSession(String id) { JpaSession session = new JpaSession(id); session.persist(); return session; } } | JpaSessionStore implements SessionStore { public Session createSession(String id) { JpaSession session = new JpaSession(id); session.persist(); return session; } } | JpaSessionStore implements SessionStore { public Session createSession(String id) { JpaSession session = new JpaSession(id); session.persist(); return session; } Session createSession(String id); JpaSession getSession(String id); void deleteSession(String id); void save(Session session); JpaSession findSessionBy(String key, String value); } | JpaSessionStore implements SessionStore { public Session createSession(String id) { JpaSession session = new JpaSession(id); session.persist(); return session; } Session createSession(String id); JpaSession getSession(String id); void deleteSession(String id); void save(Session session); JpaSession findSessionBy(String key, String value); } |
@Test public void shouldHandleException() { ConstraintViolation<?> violation = mock(ConstraintViolation.class); Path path = mock(Path.class); when(path.toString()).thenReturn("dummyField"); when(violation.getPropertyPath()).thenReturn(path); when(violation.getMessage()).thenReturn("dummy message"); when(violation.getInvalidValue()).thenReturn("dummy"); ConstraintViolationException exception = new ConstraintViolationException(Sets.newHashSet(violation)); ConstraintViolationExceptionHandler handler = new ConstraintViolationExceptionHandler(); Response response = handler.toResponse(exception); Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", Arrays.asList(new FieldError("dummy_field", "dummy message", "dummy"))); assertEquals(response.getEntity(), message); assertEquals(response.getStatus(), 422); } | @Override public Response toResponse(ConstraintViolationException exception) { ConstraintViolationException ex = (ConstraintViolationException) exception; List<FieldError> errors = new ArrayList<FieldError>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue())); } Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", errors); return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build(); } | ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(ConstraintViolationException exception) { ConstraintViolationException ex = (ConstraintViolationException) exception; List<FieldError> errors = new ArrayList<FieldError>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue())); } Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", errors); return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build(); } } | ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(ConstraintViolationException exception) { ConstraintViolationException ex = (ConstraintViolationException) exception; List<FieldError> errors = new ArrayList<FieldError>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue())); } Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", errors); return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build(); } } | ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(ConstraintViolationException exception) { ConstraintViolationException ex = (ConstraintViolationException) exception; List<FieldError> errors = new ArrayList<FieldError>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue())); } Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", errors); return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build(); } @Override Response toResponse(ConstraintViolationException exception); } | ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(ConstraintViolationException exception) { ConstraintViolationException ex = (ConstraintViolationException) exception; List<FieldError> errors = new ArrayList<FieldError>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue())); } Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", errors); return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build(); } @Override Response toResponse(ConstraintViolationException exception); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.