@Override public boolean configure(FeatureContext context) { // limit to SERVER runtime if (RuntimeType.SERVER == context.getConfiguration().getRuntimeType()) { // check disabled if (context.getConfiguration().getProperties().containsKey(DISABLE_AUTHENTICATION)) { LOGGER.debug(() -> "Skip AuthenticationFeature registration, [" + DISABLE_AUTHENTICATION + "] property detected"); return false; } if (!context.getConfiguration().isRegistered(AuthenticationDynamicFeature.class)) { context.register(AuthenticationDynamicFeature.class); } return true; } return false; }
/** * An extending class must implement the {@link #configure()} method to * provide an application descriptor. * * @throws TestContainerException if the default test container factory * cannot be obtained, or the application descriptor is not * supported by the test container factory. */ public SpringContextJerseyTest() throws TestContainerException { ResourceConfig config = getResourceConfig(configure()); config.register(new ServiceFinderBinder<TestContainerFactory>(TestContainerFactory.class, null, RuntimeType.SERVER)); if (isLogRecordingEnabled()) { registerLogHandler(); } this.application = new ApplicationHandler(config); this.tc = getContainer(application, getTestContainerFactory()); if (isLogRecordingEnabled()) { loggedStartupRecords.addAll(loggedRuntimeRecords); loggedRuntimeRecords.clear(); unregisterLogHandler(); } }
/** * Construct a new instance with a test container factory. * <p/> * An extending class must implement the {@link #configure()} method to * provide an application descriptor. * * @param testContainerFactory the test container factory to use for testing. * @throws TestContainerException if the application descriptor is not * supported by the test container factory. */ public SpringContextJerseyTest(TestContainerFactory testContainerFactory) { setTestContainerFactory(testContainerFactory); ResourceConfig config = getResourceConfig(configure()); config.register(new ServiceFinderBinder<TestContainerFactory>(TestContainerFactory.class, null, RuntimeType.SERVER)); if (isLogRecordingEnabled()) { registerLogHandler(); } this.application = new ApplicationHandler(config); this.tc = getContainer(application, testContainerFactory); if (isLogRecordingEnabled()) { loggedStartupRecords.addAll(loggedRuntimeRecords); loggedRuntimeRecords.clear(); unregisterLogHandler(); } }
@Test public void testJerseyFilterClientNoParams() throws Exception{ //environment ArgumentCaptor<Response> argument = ArgumentCaptor.forClass(Response.class); when(context.getConfiguration()).thenReturn(config); when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT); when(context.getProperty(JWSJerseyFilter.JWS_FILTER_KEY)).thenReturn(null); when(context.getUri()).thenReturn(new URI("http://localhost:8080")); //test jwsJerseyFilter.filter(context); //validation verify(context,atLeastOnce()).abortWith(argument.capture()); Assert.assertEquals("Response should be bad request",Response.Status.BAD_REQUEST.getStatusCode(),argument.getValue().getStatus()); validateMockitoUsage(); }
static String getPropertyNameForRuntime(String key, RuntimeType runtimeType) { if (runtimeType != null && key.startsWith("jersey.config")) { RuntimeType[] types = RuntimeType.values(); for (int i = 0; i < types.length; ++i) { RuntimeType type = types[i]; if (key.startsWith("jersey.config." + type.name().toLowerCase())) { return key; } } return key.replace("jersey.config", "jersey.config." + runtimeType.name().toLowerCase()); } else { return key; } }
/** * Construct a new instance with an application descriptor that defines * how the test container is configured. * * @param jaxrsApplication an application describing how to configure the * test container. * @throws TestContainerException if the default test container factory * cannot be obtained, or the application descriptor is not * supported by the test container factory. */ public SpringContextJerseyTest(Application jaxrsApplication) throws TestContainerException { ResourceConfig config = getResourceConfig(jaxrsApplication); config.register(new ServiceFinderBinder<TestContainerFactory>(TestContainerFactory.class, null, RuntimeType.SERVER)); if (isLogRecordingEnabled()) { registerLogHandler(); } this.application = new ApplicationHandler(config); this.tc = getContainer(application, getTestContainerFactory()); if (isLogRecordingEnabled()) { loggedStartupRecords.addAll(loggedRuntimeRecords); loggedRuntimeRecords.clear(); unregisterLogHandler(); } }
/** * Construct a new instance with an {@link Application} class. * * @param jaxrsApplicationClass an application describing how to configure the * test container. * @throws TestContainerException if the default test container factory * cannot be obtained, or the application descriptor is not * supported by the test container factory. */ public SpringContextJerseyTest(Class<? extends Application> jaxrsApplicationClass) throws TestContainerException { ResourceConfig config = ResourceConfig.forApplicationClass(jaxrsApplicationClass); config.register(new ServiceFinderBinder<TestContainerFactory>(TestContainerFactory.class, null, RuntimeType.SERVER)); if (isLogRecordingEnabled()) { registerLogHandler(); } this.application = new ApplicationHandler(config); this.tc = getContainer(application, getTestContainerFactory()); if (isLogRecordingEnabled()) { loggedStartupRecords.addAll(loggedRuntimeRecords); loggedRuntimeRecords.clear(); unregisterLogHandler(); } }
@Inject public PropertiesValueFactoryProvider(MultivaluedParameterExtractorProvider mpep, ServiceLocator locator, Configuration configuration) { super(mpep, locator, Parameter.Source.UNKNOWN); this.serviceLocator = locator; this.i18nEnabled = PropertiesHelper.getValue(configuration.getProperties(), RuntimeType.SERVER, JerseyPropertiesFeature.ENABLE_I18N, false, null); }
@Override public boolean configure(final FeatureContext context) { final Configuration config = context.getConfiguration(); //client side only configuration if (RuntimeType.CLIENT == config.getRuntimeType()) { if (!config.isRegistered(JWSJerseyFilter.class)){ context.property(JWSJerseyFilter.JWS_FILTER_KEY, key); context.register(JWSJerseyFilter.class); return true; } } return false; }
@Test public void testJerseyFilterServer() throws IOException{ //environment when(context.getConfiguration()).thenReturn(config); when(config.getRuntimeType()).thenReturn(RuntimeType.SERVER); //test jwsJerseyFilter.filter(context); //validation verify(config,times(1)).getRuntimeType(); validateMockitoUsage(); }
@Test public void testJerseyFilterClientWithParams() throws Exception{ //load certificate KeyStore keyStore = getKeyStoreClient(); Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray()); //environment ArgumentCaptor<String> argumentHeader = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> argumentHeaderValue = ArgumentCaptor.forClass(String.class); when(context.getConfiguration()).thenReturn(config); when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT); when(context.getProperty(JWSJerseyFilter.JWS_FILTER_KEY)).thenReturn(key); when(context.getUri()).thenReturn(new URI("http://localhost:8080")); when(context.getHeaders()).thenReturn(headers); //test jwsJerseyFilter.filter(context); //validation verify(headers,times(1)).add(argumentHeader.capture(), argumentHeaderValue.capture()); Assert.assertEquals("Response should contain header",JWSJerseyFilter.JWS_AUTHORIZATION_HEADER,argumentHeader.getValue()); String headerValue = argumentHeaderValue.getValue(); Assert.assertTrue("Response should contain token",headerValue.contains(JWSJerseyFilter.JWS_AUTHORIZATION_START_TOKEN)); //validate split by space String[] token = headerValue.split(" "); Assert.assertEquals("Header should contain signed hash", 2,token.length); Assert.assertFalse("Header should contain signed hash", token[1].isEmpty()); validateMockitoUsage(); }
@Test public void testJerseyFeatureClientWithParamsConstructor1() throws Exception{ //load certificate KeyStore keyStore = getKeyStoreClient(); Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray()); //test constructor1 JWSJerseyFeature jwsJerseyFeature = new JWSJerseyFeature(keyStore,clientCertAlias,clientCertPassword); //environment ArgumentCaptor<String> argumentName = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Object> argumentKey = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<Class> argumentClazz = ArgumentCaptor.forClass(Class.class); when(featureContext.getConfiguration()).thenReturn(config); when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT); when(config.isRegistered(JWSJerseyFilter.class)).thenReturn(false); //test boolean response = jwsJerseyFeature.configure(featureContext); //validation Assert.assertTrue("response should be true", response); verify(featureContext,times(1)).property(argumentName.capture(),argumentKey.capture()); Assert.assertEquals("Response should have the same name as param", JWSJerseyFilter.JWS_FILTER_KEY, argumentName.getValue()); Assert.assertEquals("Response should have the same key as param", key, argumentKey.getValue()); verify(featureContext,times(1)).register(argumentClazz.capture()); Assert.assertEquals("Response should have the same key as param",JWSJerseyFilter.class,argumentClazz.getValue()); validateMockitoUsage(); }
@Test public void testJerseyFeatureClientWithParamsConstructor2() throws Exception{ //load certificate KeyStore keyStore = getKeyStoreClient(); Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray()); //test constructor1 JWSJerseyFeature jwsJerseyFeature = new JWSJerseyFeature(key); //environment ArgumentCaptor<String> argumentName = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Object> argumentKey = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<Class> argumentClazz = ArgumentCaptor.forClass(Class.class); when(featureContext.getConfiguration()).thenReturn(config); when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT); when(config.isRegistered(JWSJerseyFilter.class)).thenReturn(false); //test boolean response = jwsJerseyFeature.configure(featureContext); //validation Assert.assertTrue("response should be true", response); verify(featureContext,times(1)).property(argumentName.capture(),argumentKey.capture()); Assert.assertEquals("Response should have the same name as param", JWSJerseyFilter.JWS_FILTER_KEY, argumentName.getValue()); Assert.assertEquals("Response should have the same key as param", key, argumentKey.getValue()); verify(featureContext,times(1)).register(argumentClazz.capture()); Assert.assertEquals("Response should have the same key as param",JWSJerseyFilter.class,argumentClazz.getValue()); validateMockitoUsage(); }
private boolean isNotServerProvider(Class<?> clazz) { final ConstrainedTo ct = clazz.getAnnotation(ConstrainedTo.class); if (ct != null && ct.value() != RuntimeType.SERVER) { if (!FAIL_ON_CONSTRAINED_TO) { LOGGER.warning(clazz + " is not a SERVER provider, ignoring"); return true; } throw new IllegalArgumentException(clazz + " is not a SERVER provider"); } return false; }
@Override public RuntimeType getRuntimeType() { return RuntimeType.SERVER; }
@Test public void testJWSAuthenticationFilterHeaderWithNoContent() throws Exception{ //empty content and specific url String content = ""; String requestURL="http://localhost:8080"; ServletInputStream emptyContent = new DelegatingServletInputStream(new ByteArrayInputStream( content.getBytes())); //prepare client KeyStore keyStore = getKeyStoreClient(); Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray()); JWSJerseyFilter jwsJerseyFilter = new JWSJerseyFilter(); //environment ArgumentCaptor<String> argumentHeader = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> argumentHeaderValue = ArgumentCaptor.forClass(String.class); when(context.getConfiguration()).thenReturn(config); when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT); when(context.getProperty(JWSJerseyFilter.JWS_FILTER_KEY)).thenReturn(key); when(context.getUri()).thenReturn(new URI(requestURL)); when(context.getHeaders()).thenReturn(headers); when(context.getEntity()).thenReturn(null); //test client jwsJerseyFilter.filter(context); //validation client verify(headers,times(1)).add(argumentHeader.capture(), argumentHeaderValue.capture()); String headerKey = argumentHeader.getValue(); String headerValue = argumentHeaderValue.getValue(); Assert.assertTrue("Response from client should contain token", headerValue.contains(JWSJerseyFilter.JWS_AUTHORIZATION_START_TOKEN)); logger.info("Client Header Content: {}={}", headerKey,headerValue); //prepare server when(request.getHeader(headerKey)).thenReturn(headerValue); when(request.getInputStream()).thenReturn(emptyContent); when(request.getRequestURL()).thenReturn(new StringBuffer(requestURL)); //test server myJWSFilter.doFilter(request, response, chain); //validation verify(chain,times(1)).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verify(response, times(0)).sendError(anyInt());//check sendError is not set }
@Test public void testJWSAuthenticationFilterHeaderWithContent() throws Exception{ //some content and specific url final String content = "{\n" + "\t\"id\": \"0001\",\n" + "\t\"type\": \"donut\",\n" + "\t\"name\": \"Cake\",\n" + "\t\"image\":\n" + "\t\t{\n" + "\t\t\t\"url\": \"images/0001.jpg\",\n" + "\t\t\t\"width\": 200,\n" + "\t\t\t\"height\": 200\n" + "\t\t},\n" + "\t\"thumbnail\":\n" + "\t\t{\n" + "\t\t\t\"url\": \"images/thumbnails/0001.jpg\",\n" + "\t\t\t\"width\": 32,\n" + "\t\t\t\"height\": 32\n" + "\t\t}\n" + "}"; String requestURL="http://localhost:8080"; //prepare client ServletInputStream someContent = new DelegatingServletInputStream(new ByteArrayInputStream( content.getBytes())); KeyStore keyStore = getKeyStoreClient(); Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray()); JWSJerseyFilter jwsJerseyFilter = new JWSJerseyFilter(); //environment ArgumentCaptor<String> argumentHeader = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> argumentHeaderValue = ArgumentCaptor.forClass(String.class); when(context.getConfiguration()).thenReturn(config); when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT); when(context.getProperty(JWSJerseyFilter.JWS_FILTER_KEY)).thenReturn(key); when(context.getUri()).thenReturn(new URI(requestURL)); when(context.getHeaders()).thenReturn(headers); when(context.getEntity()).thenReturn(content); doAnswer(new Answer<Void>(){ @Override public Void answer(InvocationOnMock invocation) throws Throwable{ Object[] arguments = invocation.getArguments(); ((OutputStream)arguments[6]).write(content.getBytes()); ((OutputStream)arguments[6]).flush(); return null; } }).when(messageBodyWriter).writeTo(any(Object.class), any(Class.class), any(Type.class), any(Annotation[].class), any(MediaType.class), any(MultivaluedMap.class), any(OutputStream.class)); /* TODO: Next sentence is not working because of jax.ws.rs version change, it needs to be reviewed when(messageBodyWorkers.getMessageBodyWriter(any(Class.class), any(Type.class), any(Annotation[].class), any(MediaType.class))).thenReturn(messageBodyWriter); */ jwsJerseyFilter.setWorkers(messageBodyWorkers); Type entity = content.getClass(); when(context.getEntityClass()).thenReturn((Class)entity); //test client jwsJerseyFilter.filter(context); //validation client verify(headers,times(1)).add(argumentHeader.capture(), argumentHeaderValue.capture()); String headerKey = argumentHeader.getValue(); String headerValue = argumentHeaderValue.getValue(); Assert.assertTrue("Response from client should contain token", headerValue.contains(JWSJerseyFilter.JWS_AUTHORIZATION_START_TOKEN)); logger.info("Client Header Content: {}={}", headerKey,headerValue); //prepare server when(request.getHeader(headerKey)).thenReturn(headerValue); when(request.getInputStream()).thenReturn(someContent); when(request.getRequestURL()).thenReturn(new StringBuffer(requestURL)); //test server myJWSFilter.doFilter(request, response, chain); //validation verify(chain,times(1)).doFilter(any(ServletRequest.class), any(ServletResponse.class)); verify(response, times(0)).sendError(anyInt());//check sendError is not set }
@Override public RuntimeType getRuntimeType() { return get().getRuntimeType(); }
/** * <p>getRuntimeType.</p> * * @return a {@link javax.ws.rs.RuntimeType} object. */ public RuntimeType getRuntimeType() { return config.getRuntimeType(); }