src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } ImportProcess(Catalog catalog); @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") String execute(
@DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features,
@DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage,
@DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace,
@DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store,
@DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name,
@DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs,
@DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling,
@DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName); } | @Test public void testImportBuildings() throws Exception { FeatureTypeInfo ti = getCatalog().getFeatureTypeByName(getLayerId(SystemTestData.BUILDINGS)); SimpleFeatureCollection rawSource = (SimpleFeatureCollection) ti.getFeatureSource(null, null).getFeatures(); ForceCoordinateSystemFeatureResults forced = new ForceCoordinateSystemFeatureResults( rawSource, CRS.decode("EPSG:4326")); ImportProcess importer = new ImportProcess(getCatalog()); String result = importer.execute(forced, null, SystemTestData.CITE_PREFIX, SystemTestData.CITE_PREFIX, "Buildings2", null, null, null); checkBuildings2(result); }
@Test public void testImportBuildingsForceCRS() throws Exception { FeatureTypeInfo ti = getCatalog().getFeatureTypeByName(getLayerId(SystemTestData.BUILDINGS)); SimpleFeatureCollection rawSource = (SimpleFeatureCollection) ti.getFeatureSource(null, null).getFeatures(); ImportProcess importer = new ImportProcess(getCatalog()); String result = importer.execute(rawSource, null, SystemTestData.CITE_PREFIX, SystemTestData.CITE_PREFIX, "Buildings2", CRS.decode("EPSG:4326"), null, null); checkBuildings2(result); } |
WPSInitializer implements GeoServerInitializer { public void initialize(final GeoServer geoServer) throws Exception { initWPS(geoServer.getService(WPSInfo.class), geoServer); geoServer.addListener(new ConfigurationListenerAdapter() { @Override public void handlePostGlobalChange(GeoServerInfo global) { initWPS(geoServer.getService(WPSInfo.class), geoServer); } }); } WPSInitializer(WPSExecutionManager executionManager,
DefaultProcessManager processManager, WPSStorageCleaner cleaner); void initialize(final GeoServer geoServer); } | @Test public void testSingleSave() throws Exception { GeoServer gs = createMock(GeoServer.class); List<ConfigurationListener> listeners = new ArrayList(); gs.addListener(capture(listeners)); expectLastCall().atLeastOnce(); List<ProcessGroupInfo> procGroups = new ArrayList(); WPSInfo wps = createNiceMock(WPSInfo.class); expect(wps.getProcessGroups()).andReturn(procGroups).anyTimes(); replay(wps); expect(gs.getService(WPSInfo.class)).andReturn(wps).anyTimes(); gs.save(wps); expectLastCall().once(); replay(gs); initer.initialize(gs); assertEquals(1, listeners.size()); ConfigurationListener l = listeners.get(0); l.handleGlobalChange(null, null, null, null); l.handlePostGlobalChange(null); verify(gs); } |
WPSXStreamLoader extends XStreamServiceLoader<WPSInfo> { protected WPSInfo createServiceFromScratch(GeoServer gs) { WPSInfoImpl wps = new WPSInfoImpl(); wps.setName("WPS"); wps.setGeoServer( gs ); wps.getVersions().add( new Version( "1.0.0") ); wps.setMaxAsynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); wps.setMaxSynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); return wps; } WPSXStreamLoader(GeoServerResourceLoader resourceLoader); Class<WPSInfo> getServiceClass(); } | @Test public void testCreateFromScratch() throws Exception { WPSXStreamLoader loader = new WPSXStreamLoader(new GeoServerResourceLoader()); WPSInfo wps = loader.createServiceFromScratch(null); assertNotNull(wps); assertEquals("WPS", wps.getName()); } |
WPSResourceManager implements DispatcherCallback,
ApplicationListener<ApplicationEvent> { public void addResource(WPSResource resource) { String processId = getExecutionId(null); ExecutionResources resources = resourceCache.get(processId); if (resources == null) { throw new IllegalStateException("The executionId was not set for the current thread!"); } else { resources.temporary.add(resource); } } String getExecutionId(Boolean synch); void setCurrentExecutionId(String executionId); void addResource(WPSResource resource); File getOutputFile(String executionId, String fileName); File getTemporaryFile(String extension); File getStoredResponseFile(String executionId); File getWpsOutputStorage(); void finished(Request request); void finished(String executionId); Request init(Request request); Operation operationDispatched(Request request, Operation operation); Object operationExecuted(Request request, Operation operation, Object result); Response responseDispatched(Request request, Operation operation, Object result,
Response response); Service serviceDispatched(Request request, Service service); void onApplicationEvent(ApplicationEvent event); } | @Test public void testAddResourceNoExecutionId() throws Exception { File f = File.createTempFile("dummy", "dummy", new File("target")); resourceMgr.addResource(new WPSFileResource(f)); } |
PostController { @GetMapping("/{id}") public Mono<Post> get(@PathVariable("id") String id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping("") Flux<Post> all(); @PostMapping("") Mono<Post> create(@RequestBody Post post); @GetMapping("/{id}") Mono<Post> get(@PathVariable("id") String id); @PutMapping("/{id}") Mono<Post> update(@PathVariable("id") String id, @RequestBody Post post); @DeleteMapping("/{id}") Mono<Void> delete(@PathVariable("id") String id); } | @Test public void getAllPostsWillBeOk() throws Exception { this.client .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); } |
PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } | @Test public void getPostById() throws Exception { this.rest .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this.rest .get() .uri("/posts/2") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post two"); }
@Test public void getAllPostsWillBeOk() throws Exception { this.client .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); }
@Test public void getPostById() throws Exception { this.client .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this.client .get() .uri("/posts/2") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post two"); }
@Test public void getAllPostsWillBeOk() throws Exception { this.rest .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); } |
PostRepository { Flux<Post> findAll() { return Flux.fromIterable(data.values()); } PostRepository(); } | @Test public void testGetAllPosts() { StepVerifier.create(posts.findAll()) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post one"))) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post two"))) .expectComplete() .verify(); } |
VRaptor implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { validateServletEnvironment(req, res); final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (isWebsocketRequest(baseRequest)) { chain.doFilter(req, res); return; } if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.trace("VRaptor received a new request {}", req); try { encodingHandler.setEncoding(baseRequest, baseResponse); RequestStarted requestStarted = requestStartedFactory.createEvent(baseRequest, baseResponse, chain); cdiRequestFactories.setRequest(requestStarted); requestStartedEvent.fire(requestStarted); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } } @Override void init(FilterConfig cfg); @Override void doFilter(ServletRequest req, ServletResponse res, FilterChain chain); @Override void destroy(); static final String VERSION; } | @Test public void shoudlComplainIfNotInAServletEnviroment() throws Exception { exception.expect(ServletException.class); ServletRequest request = mock(ServletRequest.class); ServletResponse response = mock(ServletResponse.class); vRaptor.doFilter(request, response, null); }
@Test public void shouldDeferToContainerIfStaticFile() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); handler.setRequestingStaticFile(true); vRaptor.doFilter(request, response, chain); assertThat(handler.isDeferProcessingToContainerCalled(), is(true)); }
@Test public void shouldBypassWebsocketRequests() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); when(request.getHeader("Upgrade")).thenReturn("Websocket"); vRaptor.doFilter(request, response, chain); verify(request).getHeader("Upgrade"); verify(chain).doFilter(request, response); verifyNoMoreInteractions(request, response); } |
DefaultControllerTranslator implements UrlToControllerTranslator { @Override public ControllerMethod translate(MutableRequest request) { String controllerName = request.getRequestedUri(); logger.debug("trying to access {}", controllerName); HttpMethod method = getHttpMethod(request, controllerName); ControllerMethod controller = router.parse(controllerName, method, request); logger.debug("found controller {}", controller); return controller; } protected DefaultControllerTranslator(); @Inject DefaultControllerTranslator(Router router); @Override ControllerMethod translate(MutableRequest request); } | @Test public void canHandleUrlIfNonRootContextButPlainRequest() { when(request.getRequestURI()).thenReturn("/custom_context/"); when(request.getContextPath()).thenReturn("/custom_context"); when(request.getMethod()).thenReturn("GET"); when(router.parse("/", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void handlesInclude() { when(request.getAttribute(INCLUDE_REQUEST_URI)).thenReturn("/url"); when(request.getMethod()).thenReturn("POST"); when(router.parse("/url", HttpMethod.POST, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(sameInstance(method))); }
@Test public void canHandleTheCorrectMethod() { when(request.getRequestURI()).thenReturn("/url"); when(request.getMethod()).thenReturn("POST"); when(router.parse("/url", HttpMethod.POST,webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void shouldAcceptCaseInsensitiveRequestMethods() { when(request.getRequestURI()).thenReturn("/url"); when(request.getMethod()).thenReturn("pOsT"); when(router.parse("/url", HttpMethod.POST,webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void shouldAcceptCaseInsensitiveGetRequestUsingThe_methodParameter() { when(request.getRequestURI()).thenReturn("/url"); when(request.getParameter("_method")).thenReturn("gEt"); when(request.getMethod()).thenReturn("POST"); when(router.parse("/url", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void shouldThrowExceptionWhenRequestANotKnownMethod() { exception.expect(MethodNotAllowedException.class); exception.expectMessage("Method COOK is not allowed for requested URI. Allowed Methods are [GET, POST]"); when(request.getRequestURI()).thenReturn("/url"); when(request.getMethod()).thenReturn("COOK"); when(router.parse(anyString(), any(HttpMethod.class), any(MutableRequest.class))).thenReturn(method); when(router.allowedMethodsFor("/url")).thenReturn(EnumSet.of(HttpMethod.GET, HttpMethod.POST)); translator.translate(webRequest); }
@Test public void shouldOverrideTheHttpMethodByUsingThe_methodParameter() { when(request.getRequestURI()).thenReturn("/url"); when(request.getParameter("_method")).thenReturn("DELETE"); when(request.getMethod()).thenReturn("POST"); when(router.parse("/url", HttpMethod.DELETE, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void canHandleUrlIfRootContext() { when(request.getRequestURI()).thenReturn("/url"); when(request.getContextPath()).thenReturn(""); when(request.getMethod()).thenReturn("GET"); when(router.parse("/url", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void canHandleUrlIfNonRootContext() { when(request.getRequestURI()).thenReturn("/custom_context/url"); when(request.getContextPath()).thenReturn("/custom_context"); when(request.getMethod()).thenReturn("GET"); when(router.parse("/url", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void canHandleUrlIfPlainRootContext() { when(request.getRequestURI()).thenReturn("/"); when(request.getMethod()).thenReturn("GET"); when(router.parse("/", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void canHandleComposedUrlIfPlainRootContext() { when(request.getRequestURI()).thenReturn("/products/1"); when(request.getMethod()).thenReturn("GET"); when(router.parse("/products/1", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void canHandleComposedUrlIfNonRootContext() { when(request.getRequestURI()).thenReturn("/custom_context/products/1"); when(request.getContextPath()).thenReturn("/custom_context"); when(request.getMethod()).thenReturn("GET"); when(router.parse("/products/1", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); }
@Test public void canHandleUrlWithAppendedJSessionID() { when(request.getRequestURI()).thenReturn( "/custom_context/products/1;jsessionid=aslfasfaslkj22234lkjsdfaklsf", "/custom_context/products/1;JSESSIONID=aslfasfaslkj22234lkjsdfaklsf", "/custom_context/products/1;jsessionID=aslfasfaslkj22234lkjsdfaklsf"); when(request.getContextPath()).thenReturn("/custom_context"); when(request.getMethod()).thenReturn("GET"); when(router.parse("/products/1", HttpMethod.GET, webRequest)).thenReturn(method); assertThat(translator.translate(webRequest), is(equalTo(method))); assertThat(translator.translate(webRequest), is(equalTo(method))); assertThat(translator.translate(webRequest), is(equalTo(method))); } |
IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | @Test public void isCapableOfDealingWithGenericsAndMultipleParameters() throws Exception { requestParametersAre(ImmutableMap.of("key", new String[] { "age" }, "value", new String[] { "32" })); ControllerMethod generic = method(SpecificKeyValueResource.class, GenericKeyValueResource.class, "put", Object.class, Object.class); Object[] params = iogi.getParametersFor(generic, errors); String key = (String) params[0]; Long value = (Long) params[1]; assertThat(key, is("age")); assertThat(value, notNullValue()); assertThat(value, instanceOf(Long.class)); assertThat(value, is(32L)); }
@Test public void returnsAnEmptyObjectArrayForZeroArityMethods() throws Exception { thereAreNoParameters(); Object[] params = iogi.getParametersFor(method("doNothing"), errors); assertThat(params, emptyArray()); }
@Test public void returnsNullWhenInstantiatingAListForWhichThereAreNoParameters() throws Exception { thereAreNoParameters(); Object[] params = iogi.getParametersFor(method("list", List.class), errors); assertArrayEquals(new Object[] {null}, params); }
@Test public void shouldInstantiateTheObjectEvenWhenThereAreNoParameters() throws Exception { thereAreNoParameters(); ControllerMethod method = method(House.class, House.class, "setCat", Cat.class); Object[] params = iogi.getParametersFor(method, errors); assertThat(params[0], notNullValue()); assertThat(params[0], instanceOf(Cat.class)); }
@Test public void shouldnotInstantiateObjectWhenThereAreNoParameters() throws Exception { VRaptorInstantiator instantiator = new NullVRaptorInstantiator(converters, new VRaptorDependencyProvider(container), new VRaptorParameterNamesProvider(nameProvider), request); instantiator.createInstantiator(); IogiParametersProvider provider = new IogiParametersProvider(nameProvider, request, instantiator); thereAreNoParameters(); ControllerMethod method = method(House.class, House.class, "setCat", Cat.class); Object[] params = provider.getParametersFor(method, errors); assertThat(params[0], nullValue()); }
@Test public void returnsNullWhenInstantiatingAStringForWhichThereAreNoParameters() throws Exception { thereAreNoParameters(); Object[] params = iogi.getParametersFor(method("string", String.class), errors); assertArrayEquals(new Object[] {null}, params); }
@Test public void canInjectADependencyProvidedByVraptor() throws Exception { thereAreNoParameters(); ControllerMethod controllerMethod = method(OtherResource.class, OtherResource.class, "logic", NeedsMyResource.class); final MyResource providedInstance = new MyResource(); when(container.canProvide(MyResource.class)).thenReturn(true); when(container.instanceFor(MyResource.class)).thenReturn(providedInstance); Object[] params = iogi.getParametersFor(controllerMethod, errors); assertThat(((NeedsMyResource) params[0]).getMyResource(), is(sameInstance(providedInstance))); }
@Test public void willCreateAnIogiParameterForEachRequestParameterValue() throws Exception { requestParameterIs("name", "a", "b"); final InstantiatorWithErrors mockInstantiator = mock(InstantiatorWithErrors.class); final Parameters expectedParamters = new Parameters(new Parameter("name", "a"), new Parameter("name", "b")); IogiParametersProvider iogiProvider = new IogiParametersProvider(nameProvider, request, mockInstantiator); iogiProvider.getParametersFor(method("buyA", House.class), errors); verify(mockInstantiator).instantiate(any(Target.class), eq(expectedParamters), eq(errors)); }
@Test public void willCreateATargerForEachFormalParameterDeclaredByTheMethod() throws Exception { requestParameterIs("house", ""); final InstantiatorWithErrors mockInstantiator = mock(InstantiatorWithErrors.class); IogiParametersProvider iogiProvider = new IogiParametersProvider(nameProvider, request, mockInstantiator); final Target<House> expectedTarget = Target.create(House.class, "house"); iogiProvider.getParametersFor(method("buyA", House.class), errors); verify(mockInstantiator).instantiate(eq(expectedTarget), any(Parameters.class), eq(errors)); }
@Test public void shouldInjectOnlyAttributesWithSameType() throws Exception { Result result = mock(Result.class); when(request.getAttribute("result")).thenReturn(result); when(request.getParameterMap()).thenReturn(singletonMap("result", new String[] { "buggy" })); ControllerMethod method = method(OtherResource.class, OtherResource.class, "logic", String.class); Object[] out = iogi.getParametersFor(method, errors); assertThat(out[0], is(not((Object) result))); assertThat(out[0], is((Object) "buggy")); } |
DefaultParametersControl implements ParametersControl { @Override public void fillIntoRequest(String uri, MutableRequest request) { Matcher m = pattern.matcher(uri); m.matches(); for (int i = 1; i <= m.groupCount(); i++) { String name = parameters.get(i - 1); try { request.setParameter(name, URLDecoder.decode(m.group(i), encodingHandler.getEncoding())); } catch (UnsupportedEncodingException e) { logger.error("Error when decoding url parameters"); } } } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } | @Test public void registerParametersWithMultipleRegexes() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = new DefaultParametersControl("/test/{hash1:[a-z0-9]{16}}{id}{hash2:[a-z0-9]{16}}/", Collections.singletonMap("id", "\\d+"), converters, evaluator,encodingHandler); control.fillIntoRequest("/test/0123456789abcdef1234fedcba9876543210/", request); verify(request).setParameter("hash1", new String[] {"0123456789abcdef"}); verify(request).setParameter("id", new String[] {"1234"}); verify(request).setParameter("hash2", new String[] {"fedcba9876543210"}); }
@Test public void registerExtraParametersFromAcessedUrlWithGreedyParameters() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{pathToFile*}"); control.fillIntoRequest("/clients/my/path/to/file", request); verify(request).setParameter("pathToFile", new String[] {"my/path/to/file"}); }
@Test public void registerExtraParametersFromAcessedUrlWithGreedyAndDottedParameters() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{path.to.file*}"); control.fillIntoRequest("/clients/my/path/to/file", request); verify(request).setParameter("path.to.file", new String[] {"my/path/to/file"}); }
@Test public void shouldDecodeUriParameters() throws Exception { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{name}"); control.fillIntoRequest("/clients/Joao+Leno", request); verify(request).setParameter("name", "Joao Leno"); control.fillIntoRequest("/clients/Paulo%20Macartinei", request); verify(request).setParameter("name", "Paulo Macartinei"); }
@Test public void registerExtraParametersFromAcessedUrl() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{dog.id}"); control.fillIntoRequest("/clients/45", request); verify(request).setParameter("dog.id", new String[] {"45"}); }
@Test public void registerParametersWithAsterisks() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{my.path*}"); control.fillIntoRequest("/clients/one/path", request); verify(request).setParameter("my.path", new String[] {"one/path"}); }
@Test public void registerParametersWithRegexes() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{hexa:[0-9A-Z]+}"); control.fillIntoRequest("/clients/FAF323", request); verify(request).setParameter("hexa", new String[] {"FAF323"}); } |
DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } | @Test public void if_formatIsSpecifiedReturnIt() throws Exception { when(request.getParameter("_format")).thenReturn("xml"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); }
@Test public void if_formatIsSpecifiedReturnItEvenIfAcceptsHtml() throws Exception { when(request.getParameter("_format")).thenReturn("xml"); when(request.getHeader("Accept")).thenReturn("html"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); }
@Test public void if_formatNotSpecifiedShouldReturnRequestAcceptFormat() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn("application/xml"); when(acceptHeaderToFormat.getFormat("application/xml")).thenReturn("xml"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); verify(request).getHeader("Accept"); }
@Test public void if_formatNotSpecifiedAndNoAcceptsHaveFormat() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn("application/SOMETHING_I_DONT_HAVE"); String format = resolver.getAcceptFormat(); assertNull(format); verify(request).getHeader("Accept"); }
@Test public void ifAcceptHeaderIsNullShouldReturnDefault() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn(null); when(acceptHeaderToFormat.getFormat(null)).thenReturn("html"); String format = resolver.getAcceptFormat(); assertThat(format, is("html")); } |
JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } | @Test public void shouldProxifyInterfaces() { TheInterface proxy = proxifier.proxify(TheInterface.class, new MethodInvocation<TheInterface>() { @Override public Object intercept(TheInterface proxy, Method method, Object[] args, SuperMethod superMethod) { return true; } }); assertThat(proxy.wasCalled(), is(true)); }
@Test public void shouldProxifyConcreteClassesWithDefaultConstructors() { TheClass proxy = proxifier.proxify(TheClass.class, new MethodInvocation<TheClass>() { @Override public Object intercept(TheClass proxy, Method method, Object[] args, SuperMethod superMethod) { return true; } }); assertThat(proxy.wasCalled(), is(true)); }
@Test public void shouldNotProxifyJavaLangObjectMethods() throws Exception { Object proxy = proxifier.proxify(JavassistProxifierTest.class, new MethodInvocation<Object>() { @Override public Object intercept(Object proxy, Method method, Object[] args, SuperMethod superMethod) { fail("should not call this Method interceptor"); return null; } }); new Mirror().on(proxy).invoke().method("finalize").withoutArgs(); }
@Test public void shouldThrowProxyInvocationExceptionIfAnErrorOccurs() { C proxy = proxifier.proxify(C.class, new MethodInvocation<C>() { @Override public Object intercept(C proxy, Method method, Object[] args, SuperMethod superMethod) { return superMethod.invoke(proxy, args); } }); try { proxy.doThrow(); fail("Should throw exception"); } catch (ProxyInvocationException e) { } }
@Test public void shouldNotProxifyBridges() throws Exception { B proxy = proxifier.proxify(B.class, new MethodInvocation<B>() { @Override public Object intercept(B proxy, Method method, Object[] args, SuperMethod superMethod) { if (method.isBridge()) { fail("Method " + method + " is a bridge"); } return null; } }); Method[] methods = proxy.getClass().getMethods(); for (Method m : methods) { if (m.getName().equals("getT")) { m.invoke(proxy, ""); } } }
@Test public void shouldConsiderSuperclassWhenProxifiyngProxy() throws Exception { MethodInvocation<C> handler = new MethodInvocation<C>() { @Override public Object intercept(C proxy, Method method, Object[] args, SuperMethod superMethod) { return null; } }; C firstProxy = proxifier.proxify(C.class, handler); C secondProxy = proxifier.proxify(firstProxy.getClass(), handler); assertEquals(firstProxy.getClass(), secondProxy.getClass()); } |
DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } | @Test public void worksAsRegexWhenUsingParameters() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{dog.id}"); assertThat(control.matches("/clients/15"), is(equalTo(true))); }
@Test public void worksWithBasicRegexEvaluation() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients.*"); assertThat(control.matches("/clientsWhatever"), is(equalTo(true))); }
@Test public void shouldMatchPatternLazily() throws Exception { DefaultParametersControl wrong = getDefaultParameterControlForUrl("/clients/{client.id}/"); DefaultParametersControl right = getDefaultParameterControlForUrl("/clients/{client.id}/subtask/"); String uri = "/clients/3/subtask/"; assertThat(wrong.matches(uri), is(false)); assertThat(right.matches(uri), is(true)); }
@Test public void shouldMatchMoreThanOneVariable() throws Exception { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{client.id}/subtask/{task.id}/"); assertThat(control.matches("/clients/3/subtask/5/"), is(true)); }
@Test public void shouldBeGreedyWhenIPutAnAsteriskOnExpression() throws Exception { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{pathToFile*}"); assertThat(control.matches("/clients/my/path/to/file/"), is(true)); }
@Test public void whenNoParameterPatternsAreGivenShouldMatchAnything() throws Exception { ParametersControl control = new DefaultParametersControl("/any/{aParameter}/what", Collections.<String,String>emptyMap(), converters, evaluator,encodingHandler); assertTrue(control.matches("/any/ICanPutAnythingInHere/what")); }
@Test public void whenParameterPatternsAreGivenShouldMatchAccordingToGivenPatterns() throws Exception { ParametersControl control = new DefaultParametersControl("/any/{aParameter}/what", Collections.singletonMap("aParameter", "aaa\\d{3}bbb"), converters, evaluator,encodingHandler); assertFalse(control.matches("/any/ICantPutAnythingInHere/what")); assertFalse(control.matches("/any/aaa12bbb/what")); assertTrue(control.matches("/any/aaa123bbb/what")); } |
CDIProxies { public static boolean isCDIProxy(Class<?> type) { return ProxyObject.class.isAssignableFrom(type); } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); } | @Test public void shoulIdentifyCDIProxies() { assertTrue(isCDIProxy(proxiable.getClass())); assertFalse(isCDIProxy(nonProxiable.getClass())); } |
CDIProxies { @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unproxifyIfPossible(T source) { if (source instanceof TargetInstanceProxy) { TargetInstanceProxy<T> target = (TargetInstanceProxy) source; return target.getTargetInstance(); } return source; } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); } | @Test public void shouldReturnTheBeanIfItsNotCDIProxy() { NonProxiableBean bean = unproxifyIfPossible(nonProxiable); assertThat(bean, equalTo(nonProxiable)); } |
ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | @Test public void shouldInvokeTheMethodAndNotProceedWithInterceptorStack() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, DogAlike.class.getMethod("bark")); DogAlike auau = mock(DogAlike.class); when(methodInfo.getParametersValues()).thenReturn(new Object[0]); observer.execute(new InterceptorsExecuted(method, auau)); verify(auau).bark(); verify(messages).assertAbsenceOfErrors(); }
@Test public void shouldUseTheProvidedArguments() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, DogAlike.class.getMethod("bark", int.class)); DogAlike auau = mock(DogAlike.class); when(methodInfo.getParametersValues()).thenReturn(new Object[] { 3 }); observer.execute(new InterceptorsExecuted(method, auau)); verify(auau).bark(3); verify(messages).assertAbsenceOfErrors(); }
@Test public void shouldSetResultReturnedValueFromInvokedMethod() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, XController.class.getMethod("method", Object.class)); final XController controller = new XController(); when(methodInfo.getParametersValues()).thenReturn(new Object[] { "string" }); observer.execute(new InterceptorsExecuted(method, controller)); verify(messages).assertAbsenceOfErrors(); }
@Test public void shouldSetNullWhenNullReturnedFromInvokedMethod() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, XController.class.getMethod("method", Object.class)); final XController controller = new XController(); when(methodInfo.getParametersValues()).thenReturn(new Object[] { null }); observer.execute(new InterceptorsExecuted(method, controller)); verify(methodInfo).setResult(null); verify(messages).assertAbsenceOfErrors(); }
@Test public void shouldBeOkIfThereIsValidationErrorsAndYouSpecifiedWhereToGo() throws Exception { Method specifiedWhereToGo = AnyController.class.getMethod("specifiedWhereToGo"); ControllerMethod method = DefaultControllerMethod.instanceFor(AnyController.class, specifiedWhereToGo); AnyController controller = new AnyController(validator); when(methodInfo.getParametersValues()).thenReturn(new Object[0]); doThrow(new ValidationException(Collections.<Message> emptyList())).when(validator).onErrorUse(nothing()); observer.execute(new InterceptorsExecuted(method, controller)); }
@Test public void shouldThrowExceptionIfYouHaventSpecifiedWhereToGoOnValidationError() throws Exception { exception.expect(ValidationFailedException.class); Method didntSpecifyWhereToGo = AnyController.class.getMethod("didntSpecifyWhereToGo"); final ControllerMethod method = DefaultControllerMethod.instanceFor(AnyController.class, didntSpecifyWhereToGo); final AnyController controller = new AnyController(validator); doThrow(new ValidationFailedException("")).when(messages).assertAbsenceOfErrors(); when(methodInfo.getParametersValues()).thenReturn(new Object[0]); observer.execute(new InterceptorsExecuted(method, controller)); }
@Test public void shouldThrowApplicationLogicExceptionIfItsACheckedException() throws Exception { Method method = AnyController.class.getDeclaredMethod("throwException"); ControllerMethod controllerMethod = instanceFor(AnyController.class, method); AnyController controller = new AnyController(validator); expected.expect(ApplicationLogicException.class); expected.expectCause(any(TestCheckedException.class)); observer.execute(new InterceptorsExecuted(controllerMethod, controller)); verify(messages).assertAbsenceOfErrors(); }
@Test public void shouldThrowTheBusinessExceptionIfItsUnChecked() throws Exception { Method method = AnyController.class.getDeclaredMethod("throwUnCheckedException"); ControllerMethod controllerMethod = instanceFor(AnyController.class, method); AnyController controller = new AnyController(validator); expected.expect(TestException.class); observer.execute(new InterceptorsExecuted(controllerMethod, controller)); verify(messages).assertAbsenceOfErrors(); } |
DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | @Test public void shouldOnlyAcceptMethodsWithConsumesAnnotation() throws Exception { observer.deserializes(new InterceptorsReady(doesntConsume), request, methodInfo, status); verifyZeroInteractions(request); }
@Test public void willSetHttpStatusCode415IfTheControllerMethodDoesNotSupportTheGivenMediaTypes() throws Exception { when(request.getContentType()).thenReturn("image/jpeg"); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); verify(status).unsupportedMediaType("Request with media type [image/jpeg]. Expecting one of [application/xml]."); }
@Test public void willSetHttpStatusCode415IfThereIsNoDeserializerButIsAccepted() throws Exception { when(request.getContentType()).thenReturn("application/xml"); when(deserializers.deserializerFor("application/xml", container)).thenReturn(null); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); verify(status).unsupportedMediaType("Unable to handle media type [application/xml]: no deserializer found."); }
@Test public void willSetMethodParametersWithDeserializationAndContinueStackAfterDeserialization() throws Exception { final Deserializer deserializer = mock(Deserializer.class); methodInfo.setControllerMethod(consumeXml); when(request.getContentType()).thenReturn("application/xml"); when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {"abc", "def"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def"); }
@Test public void willSetMethodParametersWithDeserializationEvenIfTheContentTypeHasCharsetDeclaration() throws Exception { final Deserializer deserializer = mock(Deserializer.class); methodInfo.setControllerMethod(consumeXml); when(request.getContentType()).thenReturn("application/xml; charset=UTF-8"); when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {"abc", "def"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def"); }
@Test public void willDeserializeForAnyContentTypeIfPossible() throws Exception { final ControllerMethod consumesAnything = new DefaultControllerMethod(null, DummyResource.class.getDeclaredMethod("consumesAnything", String.class, String.class)); when(request.getContentType()).thenReturn("application/xml"); methodInfo.setControllerMethod(consumesAnything); final Deserializer deserializer = mock(Deserializer.class); when(deserializer.deserialize(null, consumesAnything)).thenReturn(new Object[] {"abc", "def"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumesAnything), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def"); }
@Test public void shouldNotDeserializeIfHasNoContentType() throws Exception { final ControllerMethod consumesAnything = new DefaultControllerMethod(null, DummyResource.class.getDeclaredMethod("consumesAnything", String.class, String.class)); when(request.getContentType()).thenReturn(null); methodInfo.setControllerMethod(consumesAnything); observer.deserializes(new InterceptorsReady(consumesAnything), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), null); assertEquals(methodInfo.getValuedParameters()[1].getValue(), null); }
@Test public void willSetOnlyNonNullParameters() throws Exception { final Deserializer deserializer = mock(Deserializer.class); methodInfo.setControllerMethod(consumeXml); methodInfo.getValuedParameters()[0].setValue("original1"); methodInfo.getValuedParameters()[1].setValue("original2"); when(request.getContentType()).thenReturn("application/xml"); when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {null, "deserialized"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "original1"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "deserialized"); } |
DefaultParametersControl implements ParametersControl { @Override public String fillUri(Parameter[] paramNames, Object... paramValues) { if (paramNames.length != paramValues.length) { String message = String.format("paramNames must have the same length as paramValues. Names: %s Values: %s", Arrays.toString(paramNames), Arrays.toString(paramValues)); throw new IllegalArgumentException(message); } String[] splittedPatterns = StringUtils.extractParameters(originalPattern); String base = originalPattern; for (int i=0; i<parameters.size(); i++) { String key = parameters.get(i); Object param = selectParam(key, paramNames, paramValues); Object result = evaluator.get(param, key); if (result != null) { Class<?> type = result.getClass(); if (converters.existsTwoWayFor(type)) { TwoWayConverter converter = converters.twoWayConverterFor(type); result = converter.convert(result); } } String parameter = encodeParameter(result == null ? "" : result.toString()); base = base.replace("{" + splittedPatterns[i] + "}", result == null ? "" : parameter); } return base.replaceAll("\\.\\*", ""); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } | @Test public void shouldTranslateAsteriskAsEmpty() throws Exception { Method method = Controller.class.getDeclaredMethod("store", Client.class); String uri = getDefaultParameterControlForUrl("/clients/.*").fillUri(nameProvider.parametersFor(method), client(3L)); assertThat(uri, is(equalTo("/clients/"))); }
@Test public void shouldTranslatePatternArgs() throws Exception { Method method = Controller.class.getDeclaredMethod("store", Client.class); String uri = getDefaultParameterControlForUrl("/clients/{client.id}").fillUri(nameProvider.parametersFor(method), client(3L)); assertThat(uri, is(equalTo("/clients/3"))); }
@Test public void shouldTranslatePatternArgsWithRegex() throws Exception { Method method = Controller.class.getDeclaredMethod("show", Long.class); String uri = getDefaultParameterControlForUrl("/clients/{id:[0-9]{1,}}").fillUri(nameProvider.parametersFor(method), 30L); assertThat(uri, is(equalTo("/clients/30"))); }
@Test public void shouldTranslatePatternArgsWithMultipleRegexes() throws Exception { Method method = Controller.class.getDeclaredMethod("mregex", String.class, String.class, String.class); String uri = getDefaultParameterControlForUrl("/test/{hash1:[a-z0-9]{16}}{id}{hash2:[a-z0-9]{16}}/") .fillUri(nameProvider.parametersFor(method), "0123456789abcdef", "1234", "fedcba9876543210"); assertThat(uri, is(equalTo("/test/0123456789abcdef1234fedcba9876543210/"))); }
@Test public void shouldTranslatePatternArgNullAsEmpty() throws Exception { Method method = Controller.class.getDeclaredMethod("store", Client.class); String uri = getDefaultParameterControlForUrl("/clients/{client.id}") .fillUri(nameProvider.parametersFor(method), client(null)); assertThat(uri, is(equalTo("/clients/"))); }
@Test public void shouldUseConverterIfItExists() throws Exception { Method method = Controller.class.getDeclaredMethod("store", Client.class); when(converters.existsTwoWayFor(Client.class)).thenReturn(true); when(converters.twoWayConverterFor(Client.class)).thenReturn(converter); when(converter.convert(any(Client.class))).thenReturn("john"); String uri = getDefaultParameterControlForUrl("/clients/{client}") .fillUri(nameProvider.parametersFor(method), client(null)); assertThat(uri, is(equalTo("/clients/john"))); }
@Test public void shouldTranslatePatternArgInternalNullAsEmpty() throws Exception { Method method = Controller.class.getDeclaredMethod("store", Client.class); String uri = getDefaultParameterControlForUrl("/clients/{client.child.id}") .fillUri(nameProvider.parametersFor(method), client(null)); assertThat(uri, is(equalTo("/clients/"))); }
@Test public void fillURLWithGreedyParameters() throws SecurityException, NoSuchMethodException { when(encodingHandler.getEncoding()).thenReturn(null); DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{pathToFile*}"); Method method = Controller.class.getDeclaredMethod("pathToFile", String.class); String filled = control.fillUri(nameProvider.parametersFor(method), "my/path/to/file"); assertThat(filled, is("/clients/my/path/to/file")); }
@Test public void fillURLWithoutGreedyParameters() throws SecurityException, NoSuchMethodException { when(encodingHandler.getEncoding()).thenReturn(null); DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{pathToFile}"); Method method = Controller.class.getDeclaredMethod("pathToFile", String.class); String filled = control.fillUri(nameProvider.parametersFor(method), "my/path/to/file"); assertThat(filled, is("/clients/my/path/to/file")); }
@Test public void shouldEncodeUriParameters() throws Exception { Method method = Controller.class.getDeclaredMethod("lang", String.class); when(encodingHandler.getEncoding()).thenReturn("UTF-8"); String uri = getDefaultParameterControlForUrl("/language/{lang}/about") .fillUri(nameProvider.parametersFor(method), "c#"); assertThat(uri, is(equalTo("/language/c%23/about"))); } |
UploadedFileConverter implements Converter<UploadedFile> { @Override public UploadedFile convert(String value, Class<? extends UploadedFile> type) { Object upload = request.getAttribute(value); return type.cast(upload); } protected UploadedFileConverter(); @Inject UploadedFileConverter(HttpServletRequest request); @Override UploadedFile convert(String value, Class<? extends UploadedFile> type); } | @Test public void testIfUploadedFileIsConverted() { when(request.getAttribute("myfile")).thenReturn(file); UploadedFileConverter converter = new UploadedFileConverter(request); UploadedFile uploadedFile = converter.convert("myfile", UploadedFile.class); assertEquals(file, uploadedFile); } |
CommonsUploadMultipartObserver { public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax(uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax(uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug("Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } } void upload(@Observes ControllerFound event, MutableRequest request,
MultipartConfig config, Validator validator); } | @Test public void shouldNotAcceptFormURLEncoded() { MultipartConfig config = spy(new DefaultMultipartConfig()); when(request.getContentType()).thenReturn("application/x-www-form-urlencoded"); when(request.getMethod()).thenReturn("POST"); observer.upload(event, request, config, validator); verifyZeroInteractions(config); } |
RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } | @Test public void shouldHandle404() throws Exception { when(translator.translate(webRequest)).thenThrow(new ControllerNotFoundException()); observer.handle(requestStarted); verify(notFoundHandler).couldntFind(chain, webRequest, webResponse); verify(interceptorStack, never()).start(); }
@Test public void shouldHandle405() throws Exception { EnumSet<HttpMethod> allowedMethods = EnumSet.of(HttpMethod.GET); when(translator.translate(webRequest)).thenThrow(new MethodNotAllowedException(allowedMethods, POST.toString())); observer.handle(requestStarted); verify(methodNotAllowedHandler).deny(webRequest, webResponse, allowedMethods); verify(interceptorStack, never()).start(); }
@Test public void shouldHandle400() throws Exception { InvalidInputException invalidInputException = new InvalidInputException(""); when(translator.translate(webRequest)).thenThrow(invalidInputException); observer.handle(requestStarted); verify(interceptorStack, never()).start(); verify(invalidInputHandler).deny(invalidInputException); }
@Test public void shouldUseControllerMethodFoundWithNextInterceptor() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(interceptorStack).start(); }
@Test public void shouldFireTheControllerWasFound() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(controllerFoundEvent).fire(any(ControllerFound.class)); }
@Test public void shouldFireTheRequestSuceeded() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(requestSucceededEvent).fire(any(RequestSucceded.class)); } |
OutjectResult { public void outject(@Observes MethodExecuted event, Result result, MethodInfo methodInfo) { Type returnType = event.getMethodReturnType(); if (!returnType.equals(Void.TYPE)) { String name = extractor.nameFor(returnType); Object value = methodInfo.getResult(); logger.debug("outjecting {}={}", name, value); result.include(name, value); } } protected OutjectResult(); @Inject OutjectResult(TypeNameExtractor extractor); void outject(@Observes MethodExecuted event, Result result, MethodInfo methodInfo); } | @Test public void shouldOutjectWithASimpleTypeName() throws NoSuchMethodException { Method method = MyComponent.class.getMethod("returnsAString"); when(controllerMethod.getMethod()).thenReturn(method); when(methodInfo.getResult()).thenReturn("myString"); when(extractor.nameFor(String.class)).thenReturn("string"); outjectResult.outject(new MethodExecuted(controllerMethod, methodInfo), result, methodInfo); verify(result).include("string", "myString"); }
@Test public void shouldOutjectACollectionAsAList() throws NoSuchMethodException { Method method = MyComponent.class.getMethod("returnsStrings"); when(controllerMethod.getMethod()).thenReturn(method); when(methodInfo.getResult()).thenReturn("myString"); when(extractor.nameFor(method.getGenericReturnType())).thenReturn("stringList"); outjectResult.outject(new MethodExecuted(controllerMethod, methodInfo), result, methodInfo); verify(result).include("stringList", "myString"); } |
ForwardToDefaultView { public void forward(@Observes RequestSucceded event) { if (result.used() || event.getResponse().isCommitted()) { logger.debug("Request already dispatched and commited somewhere else, not forwarding."); return; } logger.debug("forwarding to the dafault page for this logic"); result.use(Results.page()).defaultView(); } protected ForwardToDefaultView(); @Inject ForwardToDefaultView(Result result); void forward(@Observes RequestSucceded event); } | @Test public void doesNothingIfResultWasAlreadyUsed() { when(result.used()).thenReturn(true); interceptor.forward(new RequestSucceded(request, response)); verify(result, never()).use(PageResult.class); }
@Test public void doesNothingIfResponseIsCommited() { when(response.isCommitted()).thenReturn(true); interceptor.forward(new RequestSucceded(request, response)); verify(result, never()).use(PageResult.class); }
@Test public void shouldForwardToViewWhenResultWasNotUsed() { when(result.used()).thenReturn(false); when(result.use(PageResult.class)).thenReturn(new MockedPage()); interceptor.forward(new RequestSucceded(request, response)); verify(result).use(PageResult.class); } |
ParametersInstantiator { public void instantiate(@Observes InterceptorsReady event) { if (!hasInstantiatableParameters()) return; fixIndexedParameters(request); addHeaderParametersToAttribute(); Object[] values = getParametersForCurrentMethod(); validator.addAll(errors); logger.debug("Conversion errors: {}", errors); logger.debug("Parameter values for {} are {}", methodInfo.getControllerMethod(), values); ValuedParameter[] valuedParameters = methodInfo.getValuedParameters(); for (int i = 0; i < valuedParameters.length; i++) { Parameter parameter = valuedParameters[i].getParameter(); if (parameter.isAnnotationPresent(HeaderParam.class)) { HeaderParam headerParam = parameter.getAnnotation(HeaderParam.class); valuedParameters[i].setValue(request.getHeader(headerParam.value())); } else { ValuedParameter valuedParameter = valuedParameters[i]; if (valuedParameter.getValue() == null) { valuedParameter.setValue(values[i]); } } } } protected ParametersInstantiator(); @Inject ParametersInstantiator(ParametersProvider provider, MethodInfo methodInfo, Validator validator,
MutableRequest request, FlashScope flash); void instantiate(@Observes InterceptorsReady event); } | @Test public void shouldNotAcceptIfMethodHasNoParameters() { methodInfo.setControllerMethod(method); verifyNoMoreInteractions(parametersProvider, validator, request, flash); instantiator.instantiate(new InterceptorsReady(method)); }
@Test public void shouldUseTheProvidedParameters() throws Exception { Object[] values = new Object[] { "bazinga" }; methodInfo.setControllerMethod(otherMethod); when(parametersProvider.getParametersFor(otherMethod, errors)).thenReturn(values); instantiator.instantiate(new InterceptorsReady(otherMethod)); verify(validator).addAll(Collections.<Message> emptyList()); assertEquals("bazinga", methodInfo.getValuedParameters()[0].getValue()); }
@Test public void shouldConvertArrayParametersToIndexParameters() throws Exception { when(request.getParameterNames()).thenReturn(enumeration(asList("someParam[].id", "unrelatedParam"))); when(request.getParameterValues("someParam[].id")).thenReturn(new String[] {"one", "two", "three"}); when(parametersProvider.getParametersFor(otherMethod, errors)).thenReturn(new Object[1]); methodInfo.setControllerMethod(otherMethod); instantiator.instantiate(new InterceptorsReady(otherMethod)); verify(request).setParameter("someParam[0].id", "one"); verify(request).setParameter("someParam[1].id", "two"); verify(request).setParameter("someParam[2].id", "three"); }
@Test public void shouldThrowExceptionWhenThereIsAParameterContainingDotClass() throws Exception { exception.expect(IllegalArgumentException.class); methodInfo.setControllerMethod(otherMethod); when(request.getParameterNames()).thenReturn(enumeration(asList("someParam.class.id", "unrelatedParam"))); when(request.getParameterValues("someParam.class.id")).thenReturn(new String[] {"whatever"}); instantiator.instantiate(new InterceptorsReady(otherMethod)); }
@Test public void shouldUseAndDiscardFlashParameters() throws Exception { Object[] values = new Object[] { "bazinga" }; methodInfo.setControllerMethod(otherMethod); when(flash.consumeParameters(otherMethod)).thenReturn(values); instantiator.instantiate(new InterceptorsReady(otherMethod)); verify(validator).addAll(Collections.<Message>emptyList()); verify(parametersProvider, never()).getParametersFor(otherMethod, errors); assertEquals("bazinga", methodInfo.getValuedParameters()[0].getValue()); }
@Test public void shouldValidateParameters() throws Exception { methodInfo.setControllerMethod(otherMethod); when(parametersProvider.getParametersFor(otherMethod, errors)) .thenAnswer(addErrorsToListAndReturn(new Object[] { 0 }, "error1")); instantiator.instantiate(new InterceptorsReady(otherMethod)); verify(validator).addAll(errors); assertEquals(methodInfo.getValuedParameters()[0].getValue(), 0); }
@Test public void shouldAddHeaderInformationToRequestWhenHeaderParamAnnotationIsPresent() throws Exception { Object[] values = new Object[] { "bazinga" }; Method method = HeaderParamComponent.class.getDeclaredMethod("method", String.class); ControllerMethod controllerMethod = DefaultControllerMethod.instanceFor(HeaderParamComponent.class, method); methodInfo.setControllerMethod(controllerMethod); when(request.getHeader("X-MyApp-Password")).thenReturn("123"); when(parametersProvider.getParametersFor(controllerMethod, errors)).thenReturn(values); instantiator.instantiate(new InterceptorsReady(controllerMethod)); verify(request).setParameter("password", "123"); verify(validator).addAll(Collections.<Message> emptyList()); }
@Test public void shouldNotAddHeaderInformationToRequestIfHeaderParamValueIsNull() throws Exception { Method method = HeaderParamComponent.class.getDeclaredMethod("method", String.class); ControllerMethod controllerMethod = DefaultControllerMethod.instanceFor(HeaderParamComponent.class, method); methodInfo.setControllerMethod(controllerMethod); when(request.getHeader("X-MyApp-Password")).thenReturn(null); when(parametersProvider.getParametersFor(controllerMethod, errors)).thenReturn(new Object[] { "" }); instantiator.instantiate(new InterceptorsReady(controllerMethod)); verify(request, never()).setParameter(anyString(), anyString()); }
@Test public void shouldNotAddHeaderInformationToRequestWhenHeaderParamAnnotationIsNotPresent() throws Exception { Object[] values = new Object[] { "bazinga" }; when(parametersProvider.getParametersFor(otherMethod, errors)).thenReturn(values); methodInfo.setControllerMethod(otherMethod); instantiator.instantiate(new InterceptorsReady(otherMethod)); verify(request, never()).setParameter(anyString(), anyString()); verify(validator).addAll(Collections.<Message>emptyList()); } |
DownloadObserver { public void download(@Observes MethodExecuted event, Result result) throws IOException { Object methodResult = event.getMethodInfo().getResult(); Download download = resolveDownload(methodResult); if (download != null && !result.used()) { logger.debug("Sending a file to the client"); result.use(DownloadView.class).of(download); } } void download(@Observes MethodExecuted event, Result result); Download resolveDownload(Object result); } | @Test public void whenResultIsADownloadShouldUseIt() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("download")); Download download = mock(Download.class); when(methodInfo.getResult()).thenReturn(download); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(download).write(response); }
@Test public void whenResultIsAnInputStreamShouldCreateAInputStreamDownload() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("asByte")); byte[] bytes = "abc".getBytes(); when(methodInfo.getResult()).thenReturn(new ByteArrayInputStream(bytes)); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(outputStream).write(argThat(is(arrayStartingWith(bytes))), eq(0), eq(3)); }
@Test public void whenResultIsAnInputStreamShouldCreateAByteArrayDownload() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("asByte")); byte[] bytes = "abc".getBytes(); when(methodInfo.getResult()).thenReturn(bytes); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(outputStream).write(argThat(is(arrayStartingWith(bytes))), eq(0), eq(3)); }
@Test public void whenResultIsAFileShouldCreateAFileDownload() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("file")); File tmp = tmpdir.newFile(); Files.write(tmp.toPath(), "abc".getBytes()); when(methodInfo.getResult()).thenReturn(tmp); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verify(outputStream).write(argThat(is(arrayStartingWith("abc".getBytes()))), eq(0), eq(3)); tmp.delete(); }
@Test public void whenResultIsNullShouldDoNothing() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("download")); when(result.used()).thenReturn(true); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verifyZeroInteractions(response); }
@Test public void whenResultWasUsedShouldDoNothing() throws Exception { when(controllerMethod.getMethod()).thenReturn(getMethod("download")); when(methodInfo.getResult()).thenReturn(null); downloadObserver.download(new MethodExecuted(controllerMethod, methodInfo), result); verifyZeroInteractions(response); } |
DownloadObserver { public Download resolveDownload(Object result) throws IOException { if (result instanceof InputStream) { return new InputStreamDownload((InputStream) result, null, null); } if (result instanceof byte[]) { return new ByteArrayDownload((byte[]) result, null, null); } if (result instanceof File) { return new FileDownload((File) result, null, null); } if (result instanceof Download) { return (Download) result; } return null; } void download(@Observes MethodExecuted event, Result result); Download resolveDownload(Object result); } | @Test public void shouldNotAcceptStringReturn() throws Exception { assertNull("String is not a Download", downloadObserver.resolveDownload("")); }
@Test public void shouldAcceptFile() throws Exception { File file = tmpdir.newFile(); assertThat(downloadObserver.resolveDownload(file), instanceOf(FileDownload.class)); }
@Test public void shouldAcceptInput() throws Exception { InputStream inputStream = mock(InputStream.class); assertThat(downloadObserver.resolveDownload(inputStream), instanceOf(InputStreamDownload.class)); }
@Test public void shouldAcceptDownload() throws Exception { Download download = mock(Download.class); assertEquals(downloadObserver.resolveDownload(download), download); }
@Test public void shouldAcceptByte() throws Exception { assertThat(downloadObserver.resolveDownload(new byte[]{}), instanceOf(ByteArrayDownload.class)); } |
ByteArrayDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { download.write(response); } ByteArrayDownload(byte[] buff, String contentType, String fileName); ByteArrayDownload(byte[] buff, String contentType, String fileName, boolean doDownload); @Override void write(HttpServletResponse response); } | @Test public void shouldFlushWholeStreamToHttpResponse() throws IOException { ByteArrayDownload fd = new ByteArrayDownload(bytes, "type", "x.txt"); fd.write(response); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { ByteArrayDownload fd = new ByteArrayDownload(bytes, "type", "x.txt"); fd.write(response); verify(response, times(1)).setHeader("Content-type", "type"); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void testConstructWithDownloadBuilder() throws Exception { Download fd = DownloadBuilder.of(bytes).withFileName("file.txt") .withContentType("text/plain").downloadable().build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(bytes.length)); verify(response).setHeader("Content-disposition", "attachment; filename=file.txt"); } |
InputStreamDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { writeDetails(response); OutputStream out = response.getOutputStream(); ByteStreams.copy(stream, out); stream.close(); } InputStreamDownload(InputStream input, String contentType, String fileName); InputStreamDownload(InputStream input, String contentType, String fileName, boolean doDownload, long size); @Override void write(HttpServletResponse response); } | @Test public void shouldFlushWholeStreamToHttpResponse() throws IOException { InputStreamDownload fd = new InputStreamDownload(inputStream, "type", "x.txt"); fd.write(response); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { InputStreamDownload fd = new InputStreamDownload(inputStream, "type", "x.txt"); fd.write(response); verify(response).setHeader("Content-type", "type"); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void testConstructWithDownloadBuilder() throws Exception { Download fd = DownloadBuilder.of(inputStream).withFileName("file.txt") .withSize(bytes.length) .withContentType("text/plain").downloadable().build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(bytes.length)); verify(response).setHeader("Content-disposition", "attachment; filename=file.txt"); }
@Test public void inputStreamNeedBeClosed() throws Exception { InputStream streamMocked = spy(inputStream); InputStreamDownload fd = new InputStreamDownload(streamMocked, "type", "x.txt"); fd.write(response); verify(streamMocked,times(1)).close(); } |
FileDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { try (InputStream stream = new FileInputStream(file)) { Download download = new InputStreamDownload(stream, contentType, fileName, doDownload, file.length()); download.write(response); } } FileDownload(File file, String contentType, String fileName); FileDownload(File file, String contentType); FileDownload(File file, String contentType, String fileName, boolean doDownload); @Override void write(HttpServletResponse response); } | @Test public void shouldFlushWholeFileToHttpResponse() throws IOException { FileDownload fd = new FileDownload(file, "type"); fd.write(response); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { FileDownload fd = new FileDownload(file, "type", "x.txt", false); fd.write(response); verify(response, times(1)).setHeader("Content-type", "type"); verify(response, times(1)).setHeader("Content-disposition", "inline; filename=x.txt"); assertArrayEquals(bytes, outputStream.toByteArray()); }
@Test public void builderShouldUseNameArgument() throws Exception { Download fd = DownloadBuilder.of(file).withFileName("file.txt") .withContentType("text/plain").downloadable().build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(file.length())); verify(response).setHeader("Content-disposition", "attachment; filename=file.txt"); }
@Test public void builderShouldUseFileNameWhenNameNotPresent() throws Exception { Download fd = DownloadBuilder.of(file).withContentType("text/plain").build(); fd.write(response); verify(response).setHeader("Content-Length", String.valueOf(file.length())); verify(response).setHeader("Content-disposition", "inline; filename=" + file.getName()); } |
ZipDownload implements Download { @Override public void write(HttpServletResponse response) throws IOException { response.setHeader("Content-disposition", "attachment; filename=" + filename); response.setHeader("Content-type", "application/zip"); CheckedOutputStream stream = new CheckedOutputStream(response.getOutputStream(), new CRC32()); try (ZipOutputStream zip = new ZipOutputStream(stream)) { for (Path file : files) { zip.putNextEntry(new ZipEntry(file.getFileName().toString())); copy(file, zip); zip.closeEntry(); } } } ZipDownload(String filename, Iterable<Path> files); ZipDownload(String filename, Path... files); @Override void write(HttpServletResponse response); } | @Test public void builderShouldThrowsExceptionIfFileDoesntExists() throws Exception { thrown.expect(NoSuchFileException.class); Download download = new ZipDownload("file.zip", Paths.get("/path/that/doesnt/exists/picture.jpg")); download.write(response); }
@Test public void shouldUseHeadersToHttpResponse() throws IOException { Download fd = new ZipDownload("download.zip", inpuFile0, inpuFile1); fd.write(response); verify(response, times(1)).setHeader("Content-type", "application/zip"); verify(response, times(1)).setHeader("Content-disposition", "attachment; filename=download.zip"); }
@Test public void testConstructWithDownloadBuilder() throws Exception { Download fd = DownloadBuilder.of(asList(inpuFile0, inpuFile1)) .withFileName("download.zip") .downloadable().build(); fd.write(response); verify(response).setHeader("Content-disposition", "attachment; filename=download.zip"); } |
EnvironmentPropertyProducer { @Produces @Property public String get(InjectionPoint ip) { Annotated annotated = ip.getAnnotated(); Property property = annotated.getAnnotation(Property.class); String key = property.value(); if (isNullOrEmpty(key)) { key = ip.getMember().getName(); } String defaultValue = property.defaultValue(); if(!isNullOrEmpty(defaultValue)){ return environment.get(key, defaultValue); } return environment.get(key); } protected EnvironmentPropertyProducer(); @Inject EnvironmentPropertyProducer(Environment environment); @Produces @Property String get(InjectionPoint ip); } | @Test public void shouldNotResolveUnexistentKeys() throws Exception { exception.expect(NoSuchElementException.class); nonExistent.get(); } |
DefaultEnvironment implements Environment { @Override public URL getResource(String name) { URL resource = getClass().getResource("/" + getEnvironmentType().getName() + name); if (resource != null) { LOG.debug("Loading resource {} from environment {}", name, getEnvironmentType().getName()); return resource; } return getClass().getResource(name); } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; } | @Test public void shouldUseEnvironmentBasedFileIfFoundUnderEnvironmentFolder() throws IOException { DefaultEnvironment env = buildEnvironment(EnvironmentType.DEVELOPMENT); URL resource = env.getResource("/rules.txt"); assertThat(resource, notNullValue()); assertThat(resource, is(getClass().getResource("/development/rules.txt"))); }
@Test public void shouldUseRootBasedFileIfNotFoundUnderEnvironmentFolder() throws IOException { DefaultEnvironment env = buildEnvironment(EnvironmentType.PRODUCTION); URL resource = env.getResource("/rules.txt"); assertThat(resource, notNullValue()); assertThat(resource, is(getClass().getResource("/rules.txt"))); } |
DefaultEnvironment implements Environment { @Override public String get(String key) { if (!has(key)) { throw new NoSuchElementException(String.format("Key %s not found in environment %s", key, getName())); } String systemProperty = System.getProperty(key); if (!isNullOrEmpty(systemProperty)) { return systemProperty; } else { return properties.getProperty(key); } } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; } | @Test public void shouldLoadConfigurationInDefaultFileEnvironment() throws IOException { when(context.getInitParameter(DefaultEnvironment.ENVIRONMENT_PROPERTY)).thenReturn("production"); DefaultEnvironment env = buildEnvironment(context); assertThat(env.get("env_name"), is("production")); assertThat(env.get("only_in_default_file"), is("only_in_default_file")); }
@Test public void shouldThrowExceptionIfKeyDoesNotExist() throws Exception { exception.expect(NoSuchElementException.class); DefaultEnvironment env = buildEnvironment(context); env.get("key_that_doesnt_exist"); }
@Test public void shouldGetValueWhenIsPresent() throws Exception { DefaultEnvironment env = buildEnvironment(context); String value = env.get("env_name", "fallback"); assertThat(value, is("development")); }
@Test public void shouldGetDefaultValueWhenIsntPresent() throws Exception { DefaultEnvironment env = buildEnvironment(context); String value = env.get("inexistent", "fallback"); assertThat(value, is("fallback")); } |
DefaultEnvironment implements Environment { @Override public boolean supports(String feature) { if (has(feature)) { return Boolean.parseBoolean(get(feature).trim()); } return false; } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; } | @Test public void shouldUseFalseWhenFeatureIsNotPresent() throws IOException { DefaultEnvironment env = buildEnvironment(context); assertThat(env.supports("feature_that_doesnt_exists"), is(false)); }
@Test public void shouldTrimValueWhenEvaluatingSupports() throws Exception { DefaultEnvironment env = buildEnvironment(context); assertThat(env.supports("untrimmed_boolean"), is(true)); } |
DefaultEnvironment implements Environment { @Override public String getName() { return getEnvironmentType().getName(); } protected DefaultEnvironment(); @Inject DefaultEnvironment(ServletContext context); DefaultEnvironment(EnvironmentType environmentType); @Override boolean supports(String feature); @Override boolean has(String key); @Override String get(String key); @Override String get(String key, String defaultValue); @Override void set(String key, String value); @Override Iterable<String> getKeys(); @Override boolean isProduction(); @Override boolean isDevelopment(); @Override boolean isTest(); @Override URL getResource(String name); @Override String getName(); static final String ENVIRONMENT_PROPERTY; static final String BASE_ENVIRONMENT_FILE; } | @Test public void shouldUseContextInitParameterWhenSystemPropertiesIsntPresent() { when(context.getInitParameter(DefaultEnvironment.ENVIRONMENT_PROPERTY)).thenReturn("acceptance"); DefaultEnvironment env = buildEnvironment(context); assertThat(env.getName(), is("acceptance")); }
@Test public void shouldUseSystemPropertiesWhenSysenvIsntPresent() { System.getProperties().setProperty(DefaultEnvironment.ENVIRONMENT_PROPERTY, "acceptance"); DefaultEnvironment env = buildEnvironment(context); verify(context, never()).getInitParameter(DefaultEnvironment.ENVIRONMENT_PROPERTY); assertThat(env.getName(), is("acceptance")); System.getProperties().remove(DefaultEnvironment.ENVIRONMENT_PROPERTY); } |
DefaultRepresentationResult implements RepresentationResult { @Override public <T> Serializer from(T object) { return from(object, null); } protected DefaultRepresentationResult(); @Inject DefaultRepresentationResult(FormatResolver formatResolver, Result result, @Any Instance<Serialization> serializations); @Override Serializer from(T object); @Override Serializer from(T object, String alias); } | @Test public void whenThereIsNoFormatGivenShouldForwardToDefaultPage() { when(formatResolver.getAcceptFormat()).thenReturn(null); Serializer serializer = representation.from(new Object()); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); verify(status).notAcceptable(); }
@Test public void shouldSend404IfNothingIsRendered() { when(formatResolver.getAcceptFormat()).thenReturn(null); Serializer serializer = representation.from(null); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); verify(status).notFound(); }
@Test public void whenThereIsNoFormatGivenShouldForwardToDefaultPageWithAlias() { when(formatResolver.getAcceptFormat()).thenReturn(null); Object object = new Object(); Serializer serializer = representation.from(object, "Alias!"); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); verify(status).notAcceptable(); }
@Test public void whenThereIsAFormatGivenShouldUseCorrectSerializer() { when(formatResolver.getAcceptFormat()).thenReturn("xml"); when(serialization.accepts("xml")).thenReturn(true); Object object = new Object(); representation.from(object); verify(serialization).from(object); }
@Test public void whenThereIsAFormatGivenShouldUseCorrectSerializerWithAlias() { when(formatResolver.getAcceptFormat()).thenReturn("xml"); when(serialization.accepts("xml")).thenReturn(true); Object object = new Object(); representation.from(object, "Alias!"); verify(serialization).from(object, "Alias!"); }
@Test public void whenSerializationDontAcceptsFormatItShouldntBeUsed() { when(formatResolver.getAcceptFormat()).thenReturn("xml"); when(serialization.accepts("xml")).thenReturn(false); Object object = new Object(); representation.from(object); verify(serialization, never()).from(object); } |
XStreamXMLDeserializer implements Deserializer { @Override public Object[] deserialize(InputStream inputStream, ControllerMethod method) { Method javaMethod = method.getMethod(); Class<?>[] types = javaMethod.getParameterTypes(); if (types.length == 0) { throw new IllegalArgumentException("Methods that consumes xml must receive just one argument: the xml root element"); } XStream xStream = getConfiguredXStream(javaMethod, types); Object[] params = new Object[types.length]; chooseParam(types, params, xStream.fromXML(inputStream)); return params; } protected XStreamXMLDeserializer(); @Inject XStreamXMLDeserializer(ParameterNameProvider provider, XStreamBuilder builder); @Override Object[] deserialize(InputStream inputStream, ControllerMethod method); XStream getConfiguredXStream(Method javaMethod, Class<?>[] types); } | @Test public void shouldNotAcceptMethodsWithoutArguments() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("Methods that consumes xml must receive just one argument"); deserializer.deserialize(new ByteArrayInputStream(new byte[0]), woof); }
@Test public void shouldBeAbleToDeserializeADog() throws Exception { InputStream stream = new ByteArrayInputStream("<dog><name>Brutus</name><age>7</age></dog>".getBytes()); Object[] deserialized = deserializer.deserialize(stream, bark); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }
@Test public void shouldBeAbleToDeserializeADogAsISO8601() throws Exception { InputStream stream = new ByteArrayInputStream("<dog><name>Otto</name><age>2</age><birthday>2013-07-23T17:14:14-03:00</birthday></dog>" .getBytes()); Object[] deserialized = deserializer.deserialize(stream, bark); Calendar birthday = new GregorianCalendar(2013, 6, 23, 17, 14, 14); birthday.setTimeZone(TimeZone.getTimeZone("GMT-0300")); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Otto")); assertThat(dog.age, is(2)); assertThat(dog.birthday.compareTo(birthday), is(0)); }
@Test public void shouldBeAbleToDeserializeADogWhenMethodHasMoreThanOneArgument() throws Exception { InputStream stream = new ByteArrayInputStream("<dog><name>Brutus</name><age>7</age></dog>".getBytes()); Object[] deserialized = deserializer.deserialize(stream, jump); assertThat(deserialized.length, is(2)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }
@Test public void shouldBeAbleToDeserializeADogWhenMethodHasMoreThanOneArgumentAndTheXmlIsTheLastOne() throws Exception { InputStream stream = new ByteArrayInputStream("<dog><name>Brutus</name><age>7</age></dog>".getBytes()); Object[] deserialized = deserializer.deserialize(stream, dropDead); assertThat(deserialized.length, is(2)); assertThat(deserialized[1], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[1]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }
@Test public void shouldBeAbleToDeserializeADogNamedDifferently() throws Exception { InputStream stream = new ByteArrayInputStream("<dog><name>Brutus</name><age>7</age></dog>".getBytes()); Object[] deserialized = deserializer.deserialize(stream, bark); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Dog.class))); Dog dog = (Dog) deserialized[0]; assertThat(dog.name, is("Brutus")); assertThat(dog.age, is(7)); }
@Test public void shouldBeAbleToDeserializeADogWhenAliasConfiguredByAnnotations() { InputStream stream = new ByteArrayInputStream("<dogAnnotated><nameAnnotated>Lubi</nameAnnotated><ageAnnotated>8</ageAnnotated></dogAnnotated>".getBytes()); Object[] deserialized = deserializer.deserialize(stream, annotated); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(DogWithAnnotations.class))); DogWithAnnotations dog = (DogWithAnnotations) deserialized[0]; assertThat(dog.name, is("Lubi")); assertThat(dog.age, is(8)); }
@Test public void shouldBeAbleToDeserializeAPersonWithDog() throws Exception { InputStream stream = new ByteArrayInputStream("<person><name>Renan</name><dog><name>Brutus</name><age>7</age></dog></person>".getBytes()); Object[] deserialized = deserializer.deserialize(stream, walk); assertThat(deserialized.length, is(1)); assertThat(deserialized[0], is(instanceOf(Person.class))); Person person = (Person) deserialized[0]; assertThat(person.name, is("Renan")); assertThat(person.dog.name, is("Brutus")); assertThat(person.dog.age, is(7)); } |
XStreamXMLSerialization implements XMLSerialization { @Override public <T> Serializer from(T object) { response.setContentType("application/xml"); return getSerializer().from(object); } protected XStreamXMLSerialization(); @Inject XStreamXMLSerialization(HttpServletResponse response, XStreamBuilder builder, Environment environment); @Override boolean accepts(String format); @Override XMLSerialization indented(); @Override Serializer from(T object); @Override Serializer from(T object, String alias); } | @Test public void shouldSerializeGenericClass() { String expectedResult = "<genericWrapper><entityList class=\"list\"><client><name>washington botelho</name></client><client><name>washington botelho</name></client></entityList><total>2</total></genericWrapper>"; Collection<Client> entityList = new ArrayList<>(); entityList.add(new Client("washington botelho")); entityList.add(new Client("washington botelho")); GenericWrapper<Client> wrapper = new GenericWrapper<>(entityList, entityList.size()); serialization.from(wrapper).include("entityList").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeCalendarAsISO8601() { String expectedResult = "<client><name>Otto</name><creation>2013-09-12T22:09:13-03:00</creation></client>"; Calendar calendar = Calendar.getInstance(); calendar.set(2013, 8, 12, 22, 9, 13); calendar.set(Calendar.MILLISECOND, 0); calendar.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo")); Client otto = new Client("Otto", null, calendar); serialization.from(otto).serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeMaps() { String expectedResult = "<properties><map><entry><string>test</string><string>true</string></entry></map></properties>"; serialization.from(new Properties("test", "true")).include("map").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeAllBasicFields() { String expectedResult = "<order><price>15.0</price><comments>pack it nicely, please</comments></order>"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order).serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldUseAlias() { String expectedResult = "<customOrder><price>15.0</price><comments>pack it nicely, please</comments></customOrder>"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order, "customOrder").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeEnumFields() { Order order = new BasicOrder(new Client("guilherme silveira"), 15.0, "pack it nicely, please", Type.basic); serialization.from(order).serialize(); String result = result(); assertThat(result, containsString("<type>basic</type>")); }
@Test public void shouldSerializeCollection() { String expectedResult = "<order><price>15.0</price><comments>pack it nicely, please</comments></order>"; expectedResult += expectedResult; expectedResult = "<list>" + expectedResult + "</list>"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(Arrays.asList(order, order)).serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeCollectionWithPrefixTag() { String expectedResult = "<order><price>15.0</price><comments>pack it nicely, please</comments></order>"; expectedResult += expectedResult; expectedResult = "<orders>" + expectedResult + "</orders>"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(Arrays.asList(order, order), "orders").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldIncludeFieldsFromACollection() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(Arrays.asList(order, order), "orders").include("items").serialize(); assertThat(result(), containsString("<items>")); assertThat(result(), containsString("<name>name</name>")); assertThat(result(), containsString("<price>12.99</price>")); assertThat(result(), containsString("</items>")); }
@Test public void shouldWorkWithEmptyCollections() { serialization.from(new ArrayList<Order>(), "orders").serialize(); assertThat(result(), containsString("<orders/>")); }
@Test public void shouldIncludeAllFieldsWhenRecursive() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).recursive().serialize(); assertThat(result(), containsString("<items>")); assertThat(result(), containsString("<name>name</name>")); assertThat(result(), containsString("<price>12.99</price>")); }
@Test public void shouldExcludeFieldsFromACollection() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(Arrays.asList(order, order), "orders").exclude("price").serialize(); assertThat(result(), not(containsString("<price>"))); }
@Test public void shouldThrowAnExceptionWhenYouIncludeANonExistantField() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Field path 'wrongFieldName' doesn't exists in class"); Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("wrongFieldName").serialize(); }
@Test public void shouldThrowAnExceptionWhenYouIncludeANonExistantFieldInsideOther() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Field path 'wrongFieldName.client' doesn't exists in class"); Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("wrongFieldName.client").serialize(); }
@Test public void shouldThrowAnExceptionWhenYouIncludeANonExistantFieldInsideOtherNonExistantField() { exception.expect(IllegalArgumentException.class); exception.expectMessage("Field path 'wrongFieldName.another' doesn't exists in class"); Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("wrongFieldName.another").serialize(); assertThat(result(), not(containsString("<order><price>15.0</price><comments>pack it nicely, please</comments></order>"))); }
@Test public void shouldIgnoreWhenIncludeANonExistantField() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("?wrongFieldName").serialize(); assertThat(result(), containsString("<order><price>15.0</price><comments>pack it nicely, please</comments></order>")); }
@Test public void shouldIgnoreWhenYouIncludeAOptionalNonExistantFieldInsideOther() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("?wrongFieldName.another").serialize(); assertThat(result(), containsString("<order><price>15.0</price><comments>pack it nicely, please</comments></order>")); }
@Test public void shouldIgnoreWhenYouIncludeANonExistantFieldInsideOther() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("?wrongFieldName.?another").serialize(); assertThat(result(), containsString("<order><price>15.0</price><comments>pack it nicely, please</comments></order>")); }
@Test public void shouldIncludeWhenYouIncludeAOptionsExistantFieldInsideOther() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("?client").serialize(); assertThat(result(), containsString("<client>")); }
@Test public void shouldIgnoreWhenYouIncludeANonExistantFieldInsideOtherNonExistantField() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("name", 12.99)); serialization.from(order).include("?wrongFieldName.?another").serialize(); assertThat(result(), containsString("<order><price>15.0</price><comments>pack it nicely, please</comments></order>")); }
@Test public void shouldSerializeParentFields() { Order order = new AdvancedOrder(null, 15.0, "pack it nicely, please", "complex package"); serialization.from(order).serialize(); assertThat(result(), containsString("<notes>complex package</notes>")); }
@Test public void shouldOptionallyExcludeFields() { String expectedResult = "<order><comments>pack it nicely, please</comments></order>"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order).exclude("price").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldOptionallyIncludeFieldAndNotItsNonPrimitiveFields() { Order order = new Order(new Client("guilherme silveira", new Address("R. Vergueiro")), 15.0, "pack it nicely, please"); serialization.from(order).include("client").serialize(); assertThat(result(), containsString("<name>guilherme silveira</name>")); assertThat(result(), not(containsString("R. Vergueiro"))); }
@Test public void shouldOptionallyIncludeChildField() { Order order = new Order(new Client("guilherme silveira", new Address("R. Vergueiro")), 15.0, "pack it nicely, please"); serialization.from(order).include("client", "client.address").serialize(); assertThat(result(), containsString("<street>R. Vergueiro</street>")); }
@Test public void shouldOptionallyExcludeChildField() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order).include("client").exclude("client.name").serialize(); assertThat(result(), containsString("<client/>")); assertThat(result(), not(containsString("<name>guilherme silveira</name>"))); }
@Test public void shouldOptionallyIncludeListChildFields() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("any item", 12.99)); serialization.from(order).include("items").serialize(); assertThat(result(), containsString("<items>")); assertThat(result(), containsString("<name>any item</name>")); assertThat(result(), containsString("<price>12.99</price>")); assertThat(result(), containsString("</items>")); }
@Test public void shouldOptionallyExcludeFieldsFromIncludedListChildFields() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item("any item", 12.99)); serialization.from(order).include("items").exclude("items.price").serialize(); assertThat(result(), containsString("<items>")); assertThat(result(), containsString("<name>any item</name>")); assertThat(result(), not(containsString("12.99"))); assertThat(result(), containsString("</items>")); }
@Test public void shouldExcludeAllPrimitiveFields() { String expectedResult = "<order/>"; Order order = new Order(new Client("nykolas lima"), 15.0, "gift bags, please"); serialization.from(order).excludeAll().serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldExcludeAllPrimitiveParentFields() { String expectedResult = "<advancedOrder/>"; Order order = new AdvancedOrder(null, 15.0, "pack it nicely, please", "complex package"); serialization.from(order).excludeAll().serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldExcludeAllThanIncludeAndSerialize() { Order order = new Order(new Client("nykolas lima"), 15.0, "gift bags, please"); serialization.from(order).excludeAll().include("price").serialize(); assertThat(result(), containsString("<order>")); assertThat(result(), containsString("<price>")); assertThat(result(), containsString("15.0")); assertThat(result(), containsString("</price>")); assertThat(result(), containsString("</order>")); }
@Test public void shouldAutomaticallyReadXStreamAnnotations() { WithAlias alias = new WithAlias(); alias.abc = "Duh!"; serialization.from(alias).serialize(); assertThat(result(), is("<withAlias><def>Duh!</def></withAlias>")); }
@Test public void shouldAutomaticallyReadXStreamAnnotationsForIncludedAttributes() { WithAlias alias = new WithAlias(); alias.abc = "Duh!"; WithAliasedAttribute attribute = new WithAliasedAttribute(); attribute.aliased = alias; serialization.from(attribute).include("aliased").serialize(); assertThat(result(), is("<withAliasedAttribute><aliased><def>Duh!</def></aliased></withAliasedAttribute>")); }
@Test public void shouldBeAbleToIncludeSubclassesFields() throws Exception { serialization.from(new B()).include("field2").serialize(); assertThat(result(), is("<b><field2/></b>")); } |
GsonJSONSerialization implements JSONSerialization { @Override public <T> Serializer from(T object) { return from(object, null); } protected GsonJSONSerialization(); @Inject GsonJSONSerialization(HttpServletResponse response, TypeNameExtractor extractor,
GsonSerializerBuilder builder, Environment environment, ReflectionProvider reflectionProvider); @Override boolean accepts(String format); @Override Serializer from(T object); @Override Serializer from(T object, String alias); @Override NoRootSerialization withoutRoot(); @Override JSONSerialization indented(); @Override JSONSerialization version(double versionNumber); @Override JSONSerialization serializeNulls(); } | @Test public void shouldSerializeGenericClass() { String expectedResult = "{\"genericWrapper\":{\"entityList\":[{\"name\":\"washington botelho\"},{\"name\":\"washington botelho\"}],\"total\":2}}"; Collection<Client> entityList = new ArrayList<>(); entityList.add(new Client("washington botelho")); entityList.add(new Client("washington botelho")); GenericWrapper<Client> wrapper = new GenericWrapper<>(entityList, entityList.size()); serialization.from(wrapper).include("entityList").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeAllBasicFields() { String expectedResult = "{\"order\":{\"price\":15.0,\"comments\":\"pack it nicely, please\"}}"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order).serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldUseAlias() { String expectedResult = "{\"customOrder\":{\"price\":15.0,\"comments\":\"pack it nicely, please\"}}"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order, "customOrder").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeEnumFields() { Order order = new BasicOrder(new Client("guilherme silveira"), 15.0, "pack it nicely, please", Type.basic); serialization.from(order).serialize(); String result = result(); assertThat(result, containsString("\"type\":\"basic\"")); }
@Test public void shouldSerializeCollection() { String expectedResult = "{\"price\":15.0,\"comments\":\"pack it nicely, please\"}"; expectedResult += "," + expectedResult; expectedResult = "{\"list\":[" + expectedResult + "]}"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(Arrays.asList(order, order)).serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeCollectionWithPrefixTag() { String expectedResult = "{\"price\":15.0,\"comments\":\"pack it nicely, please\"}"; expectedResult += "," + expectedResult; expectedResult = "{\"orders\":[" + expectedResult + "]}"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(Arrays.asList(order, order), "orders").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldExcludeNonPrimitiveFieldsFromACollection() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item( "name", 12.99)); serialization.from(Arrays.asList(order, order), "orders").exclude("price").serialize(); assertThat(result(), not(containsString("\"items\""))); assertThat(result(), not(containsString("name"))); assertThat(result(), not(containsString("\"price\""))); assertThat(result(), not(containsString("12.99"))); assertThat(result(), not(containsString("15.0"))); }
@Test public void shouldExcludeOnlyOmmitedFields() { User user = new User("caelum", "pwd12345", new UserPrivateInfo("123.456.789-00", "+55 (11) 1111-1111")); serialization.from(user).recursive().serialize(); assertThat(result(), not(containsString("\"pwd12345\""))); assertThat(result(), not(containsString("password"))); assertThat(result(), containsString("\"caelum\"")); assertThat(result(), containsString("login")); }
@Test public void shouldExcludeOmmitedClasses() { User user = new User("caelum", "pwd12345", new UserPrivateInfo("123.456.789-00", "+55 (11) 1111-1111")); serialization.from(user).recursive().serialize(); assertThat(result(), not(containsString("info"))); assertThat(result(), not(containsString("cpf"))); assertThat(result(), not(containsString("phone"))); }
@Test public void shouldSerializeParentFields() { Order order = new AdvancedOrder(null, 15.0, "pack it nicely, please", "complex package"); serialization.from(order).serialize(); assertThat(result(), containsString("\"notes\":\"complex package\"")); }
@Test public void shouldExcludeNonPrimitiveParentFields() { WithAdvanced advanced = new WithAdvanced(); advanced.order = new AdvancedOrder(new Client("john"), 15.0, "pack it nicely, please", "complex package"); serialization.from(advanced).include("order").serialize(); assertThat(result(), not(containsString("\"client\""))); }
@Test public void shouldExcludeParentFields() { Order order = new AdvancedOrder(null, 15.0, "pack it nicely, please", "complex package"); serialization.from(order).exclude("comments").serialize(); assertThat(result(), not(containsString("\"comments\""))); }
@Test public void shouldOptionallyExcludeFields() { String expectedResult = "{\"order\":{\"comments\":\"pack it nicely, please\"}}"; Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order).exclude("price").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldOptionallyIncludeFieldAndNotItsNonPrimitiveFields() { Order order = new Order(new Client("guilherme silveira", new Address("R. Vergueiro")), 15.0, "pack it nicely, please"); serialization.from(order).include("client").serialize(); assertThat(result(), containsString("\"name\":\"guilherme silveira\"")); assertThat(result(), not(containsString("R. Vergueiro"))); }
@Test public void shouldOptionallyIncludeChildField() { Order order = new Order(new Client("guilherme silveira", new Address("R. Vergueiro")), 15.0, "pack it nicely, please"); serialization.from(order).include("client", "client.address").serialize(); assertThat(result(), containsString("\"street\":\"R. Vergueiro\"")); }
@Test public void shouldOptionallyExcludeChildField() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please"); serialization.from(order).include("client").exclude("client.name").serialize(); assertThat(result(), containsString("\"client\"")); assertThat(result(), not(containsString("guilherme silveira"))); }
@Test public void shouldOptionallyIncludeListChildFields() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item( "any item", 12.99)); serialization.from(order).include("items").serialize(); assertThat(result(), containsString("\"items\"")); assertThat(result(), containsString("\"name\":\"any item\"")); assertThat(result(), containsString("\"price\":12.99")); }
@Test public void shouldExcludeAllPrimitiveFieldsInACollection() { String expectedResult = "{\"list\":[{},{}]}"; List<Order> orders = new ArrayList<>(); orders.add(new Order(new Client("nykolas lima"), 15.0, "gift bags, please")); orders.add(new Order(new Client("Rafael Dipold"), 15.0, "gift bags, please")); serialization.from(orders).excludeAll().serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldOptionallyExcludeFieldsFromIncludedListChildFields() { Order order = new Order(new Client("guilherme silveira"), 15.0, "pack it nicely, please", new Item( "any item", 12.99)); serialization.from(order).include("items").exclude("items.price").serialize(); assertThat(result(), containsString("\"items\"")); assertThat(result(), containsString("\"name\":\"any item\"")); assertThat(result(), not(containsString("12.99"))); }
@Test public void shouldSerializeCalendarTimeWithISO8601() { Client c = new Client("renan"); c.included = new GregorianCalendar(2012, 8, 3, 1, 5, 9); c.included.setTimeZone(TimeZone.getTimeZone("GMT-0300")); serialization.from(c).serialize(); String result = result(); String expectedResult = "{\"client\":{\"name\":\"renan\",\"included\":\"2012-09-03T01:05:09-03:00\"}}"; assertThat(result, is(equalTo(expectedResult))); }
@Test public void shouldSerializeDateWithISO8601() { Date date = new GregorianCalendar(1988, 0, 25, 1, 30, 15).getTime(); serialization.from(date).serialize(); String expectedResult = "{\"date\":\"1988-01-25T01:30:15-0300\"}"; assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldExcludeAllPrimitiveFields() { String expectedResult = "{\"order\":{}}"; Order order = new Order(new Client("nykolas lima"), 15.0, "gift bags, please"); serialization.from(order).excludeAll().serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldExcludeAllPrimitiveParentFields() { String expectedResult = "{\"advancedOrder\":{}}"; Order order = new AdvancedOrder(null, 15.0, "pack it nicely, please", "complex package"); serialization.from(order).excludeAll().serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldExcludeAllThanIncludeAndSerialize() { String expectedResult = "{\"order\":{\"price\":15.0}}"; Order order = new Order(new Client("nykolas lima"), 15.0, "gift bags, please"); serialization.from(order).excludeAll().include("price").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldSerializeWithCallback() { JSONPSerialization serialization = new GsonJSONPSerialization(response, extractor, builder, environment, new DefaultReflectionProvider()); String expectedResult = "calculate({\"order\":{\"price\":15.0}})"; Order order = new Order(new Client("nykolas lima"), 15.0, "gift bags, please"); serialization.withCallback("calculate").from(order).excludeAll().include("price").serialize(); assertThat(result(), is(equalTo(expectedResult))); }
@Test public void shouldNotSerializeNullFieldsByDefault(){ Address address = new Address("Alameda street", null); serialization.from(address).serialize(); String expectedResult = "{\"address\":{\"street\":\"Alameda street\"}}"; assertThat(result(), is(equalTo(expectedResult))); } |
DeserializesHandler { @SuppressWarnings("unchecked") public void handle(@Observes @DeserializesQualifier BeanClass beanClass) { Class<?> originalType = beanClass.getType(); checkArgument(Deserializer.class.isAssignableFrom(originalType), "%s must implement Deserializer", beanClass); deserializers.register((Class<? extends Deserializer>) originalType); } protected DeserializesHandler(); @Inject DeserializesHandler(Deserializers deserializers); @SuppressWarnings("unchecked") void handle(@Observes @DeserializesQualifier BeanClass beanClass); } | @Test public void shouldThrowExceptionWhenTypeIsNotADeserializer() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString("must implement Deserializer")); handler.handle(new DefaultBeanClass(NotADeserializer.class)); }
@Test public void shouldRegisterTypesOnDeserializers() throws Exception { handler.handle(new DefaultBeanClass(MyDeserializer.class)); verify(deserializers).register(MyDeserializer.class); } |
DefaultDeserializers implements Deserializers { @Override public Deserializer deserializerFor(String contentType, Container container) { if (deserializers.containsKey(contentType)) { return container.instanceFor(deserializers.get(contentType)); } return subpathDeserializerFor(contentType, container); } @Override Deserializer deserializerFor(String contentType, Container container); @Override void register(Class<? extends Deserializer> type); } | @Test public void shouldThrowExceptionWhenThereIsNoDeserializerRegisteredForGivenContentType() throws Exception { assertNull(deserializers.deserializerFor("bogus content type", container)); } |
DefaultDeserializers implements Deserializers { @Override public void register(Class<? extends Deserializer> type) { Deserializes deserializes = type.getAnnotation(Deserializes.class); checkArgument(deserializes != null, "You must annotate your deserializers with @Deserializes"); for (String contentType : deserializes.value()) { deserializers.put(contentType, type); } } @Override Deserializer deserializerFor(String contentType, Container container); @Override void register(Class<? extends Deserializer> type); } | @Test public void allDeserializersMustBeAnnotatedWithDeserializes() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("You must annotate your deserializers with @Deserializes"); deserializers.register(NotAnnotatedDeserializer.class); } |
HTMLSerialization implements Serialization { @Override public <T> Serializer from(T object, String alias) { result.include(alias, object); result.use(page()).defaultView(); return new IgnoringSerializer(); } protected HTMLSerialization(); @Inject HTMLSerialization(Result result, TypeNameExtractor extractor); @Override boolean accepts(String format); @Override Serializer from(T object, String alias); @Override Serializer from(T object); } | @Test public void shouldForwardToDefaultViewWithoutAlias() throws Exception { serialization.from(new Object()); verify(pageResult).defaultView(); }
@Test public void shouldForwardToDefaultViewWithAlias() throws Exception { serialization.from(new Object(), "Abc"); verify(pageResult).defaultView(); }
@Test public void shouldIncludeOnResultWithoutAlias() throws Exception { Object object = new Object(); when(extractor.nameFor(Object.class)).thenReturn("obj"); serialization.from(object); verify(result).include("obj", object); }
@Test public void shouldIncludeOnResultWithAlias() throws Exception { Object object = new Object(); serialization.from(object, "Abc"); verify(result).include("Abc", object); }
@Test public void shouldReturnAnIgnoringSerializerWithoutAlias() throws Exception { Serializer serializer = serialization.from(new Object()); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); }
@Test public void shouldReturnAnIgnoringSerializerWithAlias() throws Exception { Serializer serializer = serialization.from(new Object(), "Abc"); assertThat(serializer, is(instanceOf(IgnoringSerializer.class))); } |
FlashInterceptor implements Interceptor { @Override public boolean accepts(ControllerMethod method) { return true; } protected FlashInterceptor(); @Inject FlashInterceptor(HttpSession session, Result result, MutableResponse response); @Override boolean accepts(ControllerMethod method); @Override void intercept(InterceptorStack stack, ControllerMethod method, Object controllerInstance); } | @Test public void shouldAcceptAlways() { assertTrue(interceptor.accepts(null)); } |
FlashInterceptor implements Interceptor { @Override public void intercept(InterceptorStack stack, ControllerMethod method, Object controllerInstance) throws InterceptionException { Map<String, Object> parameters = (Map<String, Object>) session.getAttribute(FLASH_INCLUDED_PARAMETERS); if (parameters != null) { parameters = new HashMap<>(parameters); session.removeAttribute(FLASH_INCLUDED_PARAMETERS); for (Entry<String, Object> parameter : parameters.entrySet()) { result.include(parameter.getKey(), parameter.getValue()); } } response.addRedirectListener(new RedirectListener() { @Override public void beforeRedirect() { Map<String, Object> included = result.included(); if (!included.isEmpty()) { try { session.setAttribute(FLASH_INCLUDED_PARAMETERS, new HashMap<>(included)); } catch (IllegalStateException e) { LOGGER.warn("HTTP Session was invalidated. It is not possible to include " + "Result parameters on Flash Scope", e); } } } }); stack.next(method, controllerInstance); } protected FlashInterceptor(); @Inject FlashInterceptor(HttpSession session, Result result, MutableResponse response); @Override boolean accepts(ControllerMethod method); @Override void intercept(InterceptorStack stack, ControllerMethod method, Object controllerInstance); } | @Test public void shouldDoNothingWhenThereIsNoFlashParameters() throws Exception { when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); verifyZeroInteractions(result); }
@Test public void shouldAddAllFlashParametersToResult() throws Exception { when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(singletonMap("Abc", 1002)); interceptor.intercept(stack, null, null); verify(result).include("Abc", 1002); }
@Test public void shouldRemoveFlashIncludedParameters() throws Exception { when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(singletonMap("Abc", 1002)); interceptor.intercept(stack, null, null); verify(session).removeAttribute(FLASH_INCLUDED_PARAMETERS); }
@Test public void shouldIncludeFlashParametersWhenARedirectHappens() throws Exception { Map<String, Object> parameters = Collections.<String, Object>singletonMap("Abc", 1002); when(result.included()).thenReturn(parameters); when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); response.sendRedirect("Anything"); verify(session).setAttribute(FLASH_INCLUDED_PARAMETERS, parameters); }
@Test public void shouldNotIncludeFlashParametersWhenThereIsNoIncludedParameter() throws Exception { Map<String, Object> parameters = Collections.emptyMap(); when(result.included()).thenReturn(parameters); when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); response.sendRedirect("Anything"); verify(session, never()).setAttribute(anyString(), anyObject()); }
@Test public void shouldNotCrashWhenSessionIsInvalid() throws Exception { Map<String, Object> parameters = Collections.<String, Object>singletonMap("Abc", 1002); when(result.included()).thenReturn(parameters); doThrow(new IllegalStateException()).when(session).setAttribute(FLASH_INCLUDED_PARAMETERS, parameters); when(session.getAttribute(FLASH_INCLUDED_PARAMETERS)).thenReturn(null); interceptor.intercept(stack, null, null); response.sendRedirect("Anything"); } |
CustomAndInternalAcceptsValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { Method accepts = invoker.findMethod(methods, Accepts.class, originalType); List<Annotation> constraints = getCustomAcceptsAnnotations(originalType); checkState(accepts == null || constraints.isEmpty(), "Interceptor %s must declare internal accepts or custom, not both.", originalType); } protected CustomAndInternalAcceptsValidationRule(); @Inject CustomAndInternalAcceptsValidationRule(StepInvoker invoker); @Override void validate(Class<?> originalType, List<Method> methods); } | @Test public void mustNotUseInternalAcceptsAndCustomAccepts(){ exception.expect(IllegalStateException.class); exception.expectMessage("Interceptor class " + InternalAndCustomAcceptsInterceptor.class.getName() + " must declare internal accepts or custom, not both"); Class<?> type = InternalAndCustomAcceptsInterceptor.class; List<Method> methods = stepInvoker.findAllMethods(type); validationRule.validate(type, methods); }
@Test public void shouldValidateIfConstainsOnlyInternalAccepts(){ Class<?> type = InternalAcceptsInterceptor.class; List<Method> methods = stepInvoker.findAllMethods(type); validationRule.validate(type, methods); }
@Test public void shouldValidateIfConstainsOnlyCustomAccepts(){ Class<?> type = CustomAcceptsInterceptor.class; List<Method> methods = stepInvoker.findAllMethods(type); validationRule.validate(type, methods); } |
NoInterceptMethodsValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { boolean hasAfterMethod = hasAnnotatedMethod(AfterCall.class, originalType, methods); boolean hasAroundMethod = hasAnnotatedMethod(AroundCall.class, originalType, methods); boolean hasBeforeMethod = hasAnnotatedMethod(BeforeCall.class, originalType, methods); if (!hasAfterMethod && !hasAroundMethod && !hasBeforeMethod) { throw new InterceptionException(format("Interceptor %s must " + "declare at least one method whith @AfterCall, @AroundCall " + "or @BeforeCall annotation", originalType.getCanonicalName())); } } protected NoInterceptMethodsValidationRule(); @Inject NoInterceptMethodsValidationRule(StepInvoker stepInvoker); @Override void validate(Class<?> originalType, List<Method> methods); } | @Test public void shoulThrowExceptionIfInterceptorDontHaveAnyCallableMethod() { exception.expect(InterceptionException.class); exception.expectMessage("Interceptor " + SimpleInterceptor.class.getCanonicalName() +" must declare at least one method whith @AfterCall, @AroundCall or @BeforeCall annotation"); Class<?> type = SimpleInterceptor.class; List<Method> allMethods = stepInvoker.findAllMethods(type); new NoInterceptMethodsValidationRule(stepInvoker).validate(type, allMethods); }
@Test public void shoulWorksFineIfInterceptorHaveAtLeastOneCallableMethod() { Class<?> type = SimpleInterceptorWithCallableMethod.class; List<Method> allMethods = stepInvoker.findAllMethods(type); new NoInterceptMethodsValidationRule(stepInvoker).validate(type, allMethods); } |
CustomAcceptsVerifier { @SuppressWarnings({ "rawtypes", "unchecked" }) public boolean isValid(Object interceptor, ControllerMethod controllerMethod, ControllerInstance controllerInstance, List<Annotation> constraints) { for (Annotation annotation : constraints) { AcceptsConstraint constraint = annotation.annotationType().getAnnotation(AcceptsConstraint.class); Class<? extends AcceptsValidator<?>> validatorClass = constraint.value(); AcceptsValidator validator = container.instanceFor(validatorClass); validator.initialize(annotation); if (!validator.validate(controllerMethod, controllerInstance)) { return false; } } return true; } protected CustomAcceptsVerifier(); @Inject CustomAcceptsVerifier(Container container); @SuppressWarnings({ "rawtypes", "unchecked" }) boolean isValid(Object interceptor, ControllerMethod controllerMethod,
ControllerInstance controllerInstance, List<Annotation> constraints); static List<Annotation> getCustomAcceptsAnnotations(Class<?> clazz); } | @Test public void shouldValidateWithOne() throws Exception { InstanceContainer container = new InstanceContainer(withAnnotationAcceptor); CustomAcceptsVerifier verifier = new CustomAcceptsVerifier(container); assertTrue(verifier.isValid(interceptor, controllerMethod, controllerInstance, constraints)); }
@Test public void shouldValidateWithTwoOrMore() throws Exception { InstanceContainer container = new InstanceContainer(withAnnotationAcceptor,packagesAcceptor); CustomAcceptsVerifier verifier = new CustomAcceptsVerifier(container); assertTrue(verifier.isValid(interceptor, controllerMethod, controllerInstance, constraints)); }
@Test public void shouldEndProcessIfOneIsInvalid() throws Exception { InstanceContainer container = new InstanceContainer(withAnnotationAcceptor,packagesAcceptor); CustomAcceptsVerifier verifier = new CustomAcceptsVerifier(container); when(withAnnotationAcceptor.validate(controllerMethod, controllerInstance)).thenReturn(false); verify(packagesAcceptor, never()).validate(controllerMethod, controllerInstance); assertFalse(verifier.isValid(interceptor, controllerMethod, controllerInstance, constraints)); } |
AspectStyleInterceptorHandler implements InterceptorHandler { @Override public void execute(InterceptorStack stack, ControllerMethod controllerMethod, Object currentController) { Object interceptor = container.instanceFor(interceptorClass); logger.debug("Invoking interceptor {}", interceptor.getClass().getSimpleName()); List<Annotation> customAccepts = customAcceptsExecutor.getCustomAccepts(interceptor); if (customAccepts(interceptor, customAccepts) || internalAccepts(interceptor, customAccepts)) { interceptorExecutor.execute(interceptor, beforeMethod); interceptorExecutor.executeAround(interceptor, aroundMethod); interceptorExecutor.execute(interceptor, afterMethod); } else { stack.next(controllerMethod, currentController); } } AspectStyleInterceptorHandler(Class<?> interceptorClass, StepInvoker stepInvoker,
Container container, CustomAcceptsExecutor customAcceptsExecutor,
InterceptorAcceptsExecutor acceptsExecutor, InterceptorExecutor interceptorExecutor); @Override void execute(InterceptorStack stack, ControllerMethod controllerMethod, Object currentController); @Override String toString(); } | @Test public void shouldAlwaysCallAround() { AlwaysAcceptsAspectInterceptor interceptor = spy(new AlwaysAcceptsAspectInterceptor()); AspectStyleInterceptorHandler handler = newAspectStyleInterceptorHandler( AlwaysAcceptsAspectInterceptor.class, interceptor); handler.execute(stack, controllerMethod, currentController); verify(interceptor).intercept(Mockito.same(stack), Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class)); }
@Test public void shouldInvokeUsingBeforeAndAfter() { AlwaysAcceptsAspectInterceptor interceptor = spy(new AlwaysAcceptsAspectInterceptor()); AspectStyleInterceptorHandler handler = newAspectStyleInterceptorHandler( AlwaysAcceptsAspectInterceptor.class, interceptor); handler.execute(stack, controllerMethod, currentController); InOrder order = inOrder(interceptor); order.verify(interceptor).begin(); order.verify(interceptor).intercept( Mockito.same(stack), Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class)); order.verify(interceptor).after(); }
@Test public void shouldInvokeIfAccepts() { AcceptsInterceptor acceptsInterceptor = spy(new AcceptsInterceptor(true)); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( AcceptsInterceptor.class, acceptsInterceptor); aspectHandler.execute(stack, controllerMethod, currentController); InOrder order = inOrder(acceptsInterceptor); order.verify(acceptsInterceptor).accepts(controllerMethod); order.verify(acceptsInterceptor).before(); order.verify(acceptsInterceptor).around( Mockito.same(stack), Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class)); order.verify(acceptsInterceptor).after(); }
@Test public void shouldNotInvokeIfDoesNotAccept() { AcceptsInterceptor acceptsInterceptor = spy(new AcceptsInterceptor( false)); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( AcceptsInterceptor.class, acceptsInterceptor); aspectHandler.execute(stack, controllerMethod, currentController); verify(acceptsInterceptor).accepts(controllerMethod); verify(acceptsInterceptor, never()).before(); verify(acceptsInterceptor, never()).around(Mockito.same(stack), Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class)); verify(acceptsInterceptor, never()).after(); }
@Test public void shouldInvokeAcceptsWithoutArgs() { AcceptsWithoutArgsInterceptor acceptsWithoutArgsInterceptor = spy(new AcceptsWithoutArgsInterceptor()); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( AcceptsWithoutArgsInterceptor.class, acceptsWithoutArgsInterceptor); aspectHandler.execute(stack, controllerMethod, currentController); InOrder order = inOrder(acceptsWithoutArgsInterceptor); order.verify(acceptsWithoutArgsInterceptor).accepts(); order.verify(acceptsWithoutArgsInterceptor).before(); order.verify(acceptsWithoutArgsInterceptor).around( Mockito.same(stack), Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class)); order.verify(acceptsWithoutArgsInterceptor).after(); }
@Test public void shouldInvokeAroundWithSimpleStack() { ExampleOfSimpleStackInterceptor simpleStackInterceptor = spy(new ExampleOfSimpleStackInterceptor()); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( ExampleOfSimpleStackInterceptor.class, simpleStackInterceptor); aspectHandler.execute(stack, controllerMethod, currentController); verify(simpleStackInterceptor).around( Mockito.any(SimpleInterceptorStack.class)); }
@Test public void shouldInvokeNextIfNotAccepts() throws Exception { AcceptsInterceptor interceptor = spy(new AcceptsInterceptor(false)); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( AcceptsInterceptor.class, interceptor); aspectHandler.execute(stack, controllerMethod, null); verify(interceptor, never()).around( Mockito.any(InterceptorStack.class), Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class)); verify(stack).next(Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class)); }
@Test public void shouldNotInvokeIfDoesNotHaveAround() throws Exception { WithoutAroundInterceptor interceptor = spy(new WithoutAroundInterceptor()); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( WithoutAroundInterceptor.class, interceptor); aspectHandler.execute(stack, controllerMethod, null); verify(simpleInterceptorStack).next(); }
@Test public void shouldAcceptCustomizedAccepts() throws Exception { InterceptorWithCustomizedAccepts interceptor = new InterceptorWithCustomizedAccepts(); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( InterceptorWithCustomizedAccepts.class, interceptor, withAnnotationAcceptor); when(withAnnotationAcceptor.validate(Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class))).thenReturn(true); aspectHandler.execute(stack, controllerMethod, new MethodLevelAcceptsController()); assertTrue(interceptor.isBeforeCalled()); assertTrue(interceptor.isInterceptCalled()); assertTrue(interceptor.isAfterCalled()); }
@Test public void shouldNotAcceptCustomizedAccepts() throws Exception { InterceptorWithCustomizedAccepts interceptor = new InterceptorWithCustomizedAccepts(); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( InterceptorWithCustomizedAccepts.class, interceptor,withAnnotationAcceptor); when(withAnnotationAcceptor.validate(Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class))).thenReturn(false); aspectHandler.execute(stack, controllerMethod, new MethodLevelAcceptsController()); assertFalse(interceptor.isBeforeCalled()); assertFalse(interceptor.isInterceptCalled()); assertFalse(interceptor.isAfterCalled()); }
@Test public void shouldInvokeCustomAcceptsFailCallback() { InterceptorWithCustomizedAccepts interceptor = spy(new InterceptorWithCustomizedAccepts()); AspectStyleInterceptorHandler aspectHandler = newAspectStyleInterceptorHandler( InterceptorWithCustomizedAccepts.class, interceptor, withAnnotationAcceptor); when(withAnnotationAcceptor.validate(Mockito.same(controllerMethod), Mockito.any(ControllerInstance.class))).thenReturn(false); aspectHandler.execute(stack, controllerMethod, aspectHandler); verify(interceptor).customAcceptsFailCallback(); } |
DefaultTypeNameExtractor implements TypeNameExtractor { @Override public String nameFor(Type generic) { if (generic instanceof ParameterizedType) { return nameFor((ParameterizedType) generic); } if (generic instanceof WildcardType) { return nameFor((WildcardType) generic); } if (generic instanceof TypeVariable<?>) { return nameFor((TypeVariable<?>) generic); } return nameFor((Class<?>) generic); } @Override String nameFor(Type generic); } | @Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercased() throws NoSuchMethodException { Assert.assertEquals("urlClassLoader",extractor.nameFor(URLClassLoader.class)); Assert.assertEquals("bigDecimal",extractor.nameFor(BigDecimal.class)); Assert.assertEquals("string",extractor.nameFor(String.class)); Assert.assertEquals("aClass",extractor.nameFor(AClass.class)); Assert.assertEquals("url",extractor.nameFor(URL.class)); }
@Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercasedForListsAndArrays() throws NoSuchMethodException, SecurityException, NoSuchFieldException { Assert.assertEquals("stringList",extractor.nameFor(getField("strings"))); Assert.assertEquals("bigDecimalList",extractor.nameFor(getField("bigs"))); Assert.assertEquals("hashSet",extractor.nameFor(getField("bigsOld"))); Assert.assertEquals("class",extractor.nameFor(getField("clazz"))); Assert.assertEquals("aClassList",extractor.nameFor(AClass[].class)); Assert.assertEquals("urlClassLoaderList",extractor.nameFor(getField("urls"))); }
@Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercasedForListsAndArraysForBoundedGenericElements() throws NoSuchMethodException, SecurityException, NoSuchFieldException { Assert.assertEquals("bigDecimalList",extractor.nameFor(getField("bigsLimited"))); Assert.assertEquals("bigDecimalList",extractor.nameFor(getField("bigsLimited2"))); Assert.assertEquals("objectList",extractor.nameFor(getField("objects"))); }
@Test public void shouldDiscoverGenericTypeParametersWhenThereIsInheritance() throws Exception { Assert.assertEquals("t",extractor.nameFor(XController.class.getMethod("edit").getGenericReturnType())); Assert.assertEquals("tList",extractor.nameFor(XController.class.getMethod("list").getGenericReturnType())); } |
AcceptsNeedReturnBooleanValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { Method accepts = invoker.findMethod(methods, Accepts.class, originalType); if (accepts != null && !isBooleanReturn(accepts.getReturnType())) { throw new InterceptionException(format("@%s method must return boolean", Accepts.class.getSimpleName())); } } protected AcceptsNeedReturnBooleanValidationRule(); @Inject AcceptsNeedReturnBooleanValidationRule(StepInvoker invoker); @Override void validate(Class<?> originalType, List<Method> methods); } | @Test public void shouldVerifyIfAcceptsMethodReturnsVoid() { exception.expect(InterceptionException.class); exception.expectMessage("@Accepts method must return boolean"); Class<VoidAcceptsInterceptor> type = VoidAcceptsInterceptor.class; List<Method> allMethods = stepInvoker.findAllMethods(type); validationRule.validate(type, allMethods); }
@Test public void shouldVerifyIfAcceptsMethodReturnsNonBooleanType() { exception.expect(InterceptionException.class); exception.expectMessage("@Accepts method must return boolean"); Class<NonBooleanAcceptsInterceptor> type = NonBooleanAcceptsInterceptor.class; List<Method> allMethods = stepInvoker.findAllMethods(type); validationRule.validate(type, allMethods); } |
StepInvoker { public Method findMethod(List<Method> interceptorMethods, Class<? extends Annotation> step, Class<?> interceptorClass) { FluentIterable<Method> possibleMethods = FluentIterable.from(interceptorMethods).filter(hasStepAnnotation(step)); if (possibleMethods.size() > 1 && possibleMethods.allMatch(not(notSameClass(interceptorClass)))) { throw new IllegalStateException(String.format("%s - You should not have more than one @%s annotated method", interceptorClass.getCanonicalName(), step.getSimpleName())); } return possibleMethods.first().orNull(); } protected StepInvoker(); @Inject StepInvoker(ReflectionProvider reflectionProvider); Object tryToInvoke(Object interceptor, Method stepMethod, Object... params); List<Method> findAllMethods(Class<?> interceptorClass); Method findMethod(List<Method> interceptorMethods, Class<? extends Annotation> step, Class<?> interceptorClass); } | @Test public void shouldNotReadInheritedMethods() throws Exception { Class<?> interceptorClass = InterceptorWithInheritance.class; Method method = findMethod(interceptorClass, BeforeCall.class); assertEquals(method, interceptorClass.getDeclaredMethod("begin")); }
@Test public void shouldThrowsExceptionWhenInterceptorHasMoreThanOneAnnotatedMethod() { exception.expect(IllegalStateException.class); exception.expectMessage(InterceptorWithMoreThanOneBeforeCallMethod.class.getName() + " - You should not have more than one @BeforeCall annotated method"); Class<?> interceptorClass = InterceptorWithMoreThanOneBeforeCallMethod.class; findMethod(interceptorClass, BeforeCall.class); }
@Test public void shouldFindFirstMethodAnnotatedWithInterceptorStep(){ ExampleOfSimpleStackInterceptor proxy = spy(new ExampleOfSimpleStackInterceptor()); findMethod(proxy.getClass(), BeforeCall.class); }
@Test public void shouldFindMethodFromWeldStyleInterceptor() throws SecurityException, NoSuchMethodException{ Class<?> interceptorClass = WeldProxy$$$StyleInterceptor.class; assertNotNull(findMethod(interceptorClass, AroundCall.class)); } |
NoStackParamValidationRule implements ValidationRule { @Override public void validate(Class<?> originalType, List<Method> methods) { Method aroundCall = invoker.findMethod(methods, AroundCall.class, originalType); Method afterCall = invoker.findMethod(methods, AfterCall.class, originalType); Method beforeCall = invoker.findMethod(methods, BeforeCall.class, originalType); Method accepts = invoker.findMethod(methods, Accepts.class, originalType); String interceptorStack = InterceptorStack.class.getName(); String simpleInterceptorStack = SimpleInterceptorStack.class.getName(); checkState(aroundCall == null || containsStack(aroundCall), "@AroundCall method must receive %s or %s", interceptorStack, simpleInterceptorStack); checkState(!containsStack(beforeCall) && !containsStack(afterCall) && !containsStack(accepts), "Non @AroundCall method must not receive %s or %s", interceptorStack, simpleInterceptorStack); } protected NoStackParamValidationRule(); @Inject NoStackParamValidationRule(StepInvoker invoker); @Override void validate(Class<?> originalType, List<Method> methods); } | @Test public void mustReceiveStackAsParameterForAroundCall() { exception.expect(IllegalStateException.class); exception.expectMessage("@AroundCall method must receive br.com.caelum.vraptor.core.InterceptorStack or br.com.caelum.vraptor.interceptor.SimpleInterceptorStack"); Class<?> type = AroundInterceptorWithoutSimpleStackParameter.class; validationRule.validate(type, invoker.findAllMethods(type)); }
@Test public void mustNotReceiveStackAsParameterForAcceptsCall() { exception.expect(IllegalStateException.class); exception.expectMessage("Non @AroundCall method must not receive br.com.caelum.vraptor.core.InterceptorStack or br.com.caelum.vraptor.interceptor.SimpleInterceptorStack"); Class<?> type = AcceptsInterceptorWithStackAsParameter.class; validationRule.validate(type, invoker.findAllMethods(type)); }
@Test public void mustNotReceiveStackAsParameterForBeforeAfterCall() { exception.expect(IllegalStateException.class); exception.expectMessage("Non @AroundCall method must not receive br.com.caelum.vraptor.core.InterceptorStack or br.com.caelum.vraptor.interceptor.SimpleInterceptorStack"); Class<?> type = BeforeAfterInterceptorWithStackAsParameter.class; validationRule.validate(type, invoker.findAllMethods(type)); } |
DefaultTypeFinder implements TypeFinder { @Override public Map<String, Class<?>> getParameterTypes(Method method, String[] parameterPaths) { Map<String,Class<?>> types = new HashMap<>(); Parameter[] parametersFor = provider.parametersFor(method); for (String path : parameterPaths) { for (Parameter parameter: parametersFor) { if (path.startsWith(parameter.getName() + ".") || path.equals(parameter.getName())) { String[] items = path.split("\\."); Class<?> type = parameter.getType(); for (int j = 1; j < items.length; j++) { String item = items[j]; try { type = reflectionProvider.getMethod(type, "get" + capitalize(item)).getReturnType(); } catch (Exception e) { throw new IllegalArgumentException("Parameters paths are invalid: " + Arrays.toString(parameterPaths) + " for method " + method, e); } } types.put(path, type); } } } return types; } protected DefaultTypeFinder(); @Inject DefaultTypeFinder(ParameterNameProvider provider, ReflectionProvider reflectionProvider); @Override Map<String, Class<?>> getParameterTypes(Method method, String[] parameterPaths); } | @Test public void shouldGetTypesCorrectly() throws Exception { final Method method = new Mirror().on(AController.class).reflect().method("aMethod").withArgs(Bean.class, String.class); DefaultTypeFinder finder = new DefaultTypeFinder(provider, new DefaultReflectionProvider()); Map<String, Class<?>> types = finder.getParameterTypes(method, new String[] {"bean.bean2.id", "path"}); assertEquals(Integer.class, types.get("bean.bean2.id")); assertEquals(String.class, types.get("path")); }
@Test public void shouldGetTypesCorrectlyOnInheritance() throws Exception { final Method method = new Mirror().on(AController.class).reflect().method("otherMethod").withArgs(BeanExtended.class); DefaultTypeFinder finder = new DefaultTypeFinder(provider, new DefaultReflectionProvider()); Map<String, Class<?>> types = finder.getParameterTypes(method, new String[] {"extended.id"}); assertEquals(Integer.class, types.get("extended.id")); } |
DefaultControllerInstance implements ControllerInstance { @Override public BeanClass getBeanClass(){ Class<?> controllerClass = extractRawTypeIfPossible(controller.getClass()); return new DefaultBeanClass(controllerClass); } DefaultControllerInstance(Object instance); @Override Object getController(); @Override BeanClass getBeanClass(); } | @Test public void shouldUnwrapCDIProxyFromControllerType() { ControllerInstance controllerInstance = controllerInstance(); assertTrue(CDIProxies.isCDIProxy(controller.getClass())); BeanClass beanClass = controllerInstance.getBeanClass(); assertFalse(CDIProxies.isCDIProxy(beanClass.getType())); } |
DefaultMethodNotAllowedHandler implements MethodNotAllowedHandler { @Override public void deny(MutableRequest request, MutableResponse response, Set<HttpMethod> allowedMethods) { response.addHeader("Allow", Joiner.on(", ").join(allowedMethods)); try { if (!"OPTIONS".equalsIgnoreCase(request.getMethod())) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } catch (IOException e) { throw new InterceptionException(e); } } @Override void deny(MutableRequest request, MutableResponse response, Set<HttpMethod> allowedMethods); } | @Test public void shouldAddAllowHeader() throws Exception { this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); verify(response).addHeader("Allow", "GET, POST"); }
@Test public void shouldSendErrorMethodNotAllowed() throws Exception { this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); verify(response).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); }
@Test public void shouldNotSendMethodNotAllowedIfTheRequestMethodIsOptions() throws Exception { when(request.getMethod()).thenReturn("OPTIONS"); this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); verify(response, never()).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); }
@Test public void shouldThrowInterceptionExceptionIfAnIOExceptionOccurs() throws Exception { exception.expect(InterceptionException.class); doThrow(new IOException()).when(response).sendError(anyInt()); this.handler.deny(request, response, EnumSet.of(HttpMethod.GET, HttpMethod.POST)); } |
LinkToHandler extends ForwardingMap<Class<?>, Object> { @Override public Object get(Object key) { logger.debug("getting key {}", key); BeanClass beanClass = (BeanClass) key; final Class<?> controller = beanClass.getType(); Class<?> linkToInterface = interfaces.get(controller); if (linkToInterface == null) { logger.debug("interface not found, creating one {}", controller); lock.lock(); try { linkToInterface = interfaces.get(controller); if (linkToInterface == null) { String path = context.getContextPath().replace('/', '$'); String interfaceName = controller.getName() + "$linkTo" + path; linkToInterface = createLinkToInterface(controller, interfaceName); interfaces.put(controller, linkToInterface); logger.debug("created interface {} to {}", interfaceName, controller); } } finally { lock.unlock(); } } return proxifier.proxify(linkToInterface, new MethodInvocation<Object>() { @Override public Object intercept(Object proxy, Method method, Object[] args, SuperMethod superMethod) { String methodName = StringUtils.decapitalize(method.getName().replaceFirst("^get", "")); List<Object> params = args.length == 0 ? Collections.emptyList() : Arrays.asList(args); return linker(controller, methodName, params).getLink(); } }); } protected LinkToHandler(); @Inject LinkToHandler(ServletContext context, Router router, Proxifier proxifier, ReflectionProvider reflectionProvider); @PostConstruct void start(); @Override Object get(Object key); @PreDestroy void removeGeneratedClasses(); } | @Test public void shouldThrowExceptionWhenMethodIsAmbiguous() throws Throwable { try { invoke(handler.get(new DefaultBeanClass(TestController.class)), "method"); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), startsWith("ambiguous method")); } }
@Test public void shouldThrowExceptionWhenUsingParametersOfWrongTypes() throws Throwable { try { invoke(handler.get(new DefaultBeanClass(TestController.class)), "method", 123); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), startsWith("there are no methods")); } }
@Test public void shouldReturnWantedUrlWithoutArgs() throws Throwable { when(router.urlFor(TestController.class, anotherMethod, new Object[2])).thenReturn("/expectedURL"); String uri = invoke(handler.get(new DefaultBeanClass(TestController.class)), "anotherMethod"); assertThat(uri, is("/path/expectedURL")); }
@Test public void shouldReturnWantedUrlWithoutArgsUsingPropertyAccess() throws Throwable { when(router.urlFor(TestController.class, anotherMethod, new Object[2])).thenReturn("/expectedURL"); String uri = invoke(handler.get(new DefaultBeanClass(TestController.class)), "getAnotherMethod"); assertThat(uri, is("/path/expectedURL")); }
@Test public void shouldReturnWantedUrlWithParamArgs() throws Throwable { String a = "test"; int b = 3; when(router.urlFor(TestController.class, method2params, new Object[]{a, b})).thenReturn("/expectedURL"); String uri = invoke(handler.get(new DefaultBeanClass(TestController.class)), "method", a, b); assertThat(uri, is("/path/expectedURL")); }
@Test public void shouldReturnWantedUrlWithPartialParamArgs() throws Throwable { String a = "test"; when(router.urlFor(TestController.class, anotherMethod, new Object[]{a, null})).thenReturn("/expectedUrl"); String uri = invoke(handler.get(new DefaultBeanClass(TestController.class)), "anotherMethod", a); assertThat(uri, is("/path/expectedUrl")); }
@Test public void shouldReturnWantedUrlForOverrideMethodWithParamArgs() throws Throwable { String a = "test"; when(router.urlFor(SubGenericController.class, SubGenericController.class.getDeclaredMethod("method", new Class[]{String.class}), new Object[]{a})).thenReturn("/expectedURL"); String uri = invoke(handler.get(new DefaultBeanClass(SubGenericController.class)), "method", a); assertThat(uri, is("/path/expectedURL")); }
@Test public void shouldReturnWantedUrlForOverrideMethodWithParialParamArgs() throws Throwable { String a = "test"; when(router.urlFor(SubGenericController.class, SubGenericController.class.getDeclaredMethod("anotherMethod", new Class[]{String.class, String.class}), new Object[]{a, null})).thenReturn("/expectedURL"); String uri = invoke(handler.get(new DefaultBeanClass(SubGenericController.class)), "anotherMethod", a); assertThat(uri, is("/path/expectedURL")); }
@Test public void shouldUseExactlyMatchedMethodIfTheMethodIsOverloaded() throws Throwable { String a = "test"; when(router.urlFor(TestController.class, method1param, a)).thenReturn("/expectedUrl"); String uri = invoke(handler.get(new DefaultBeanClass(TestController.class)), "method", a); assertThat(uri, is("/path/expectedUrl")); }
@Test public void shouldThrowExceptionWhenPassingMoreArgsThanMethodSupports() throws Throwable { String a = "test"; int b = 3; String c = "anotherTest"; try { invoke(handler.get(new DefaultBeanClass(TestController.class)), "anotherMethod", a, b, c); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage().toLowerCase(), startsWith("wrong number of arguments")); } }
@Test public void shouldAvoidFrozenClassIfTwoVRaptorInstancesAreLoaded() throws Throwable { ServletContext context0 = Mockito.mock(ServletContext.class); ServletContext context1 = Mockito.mock(ServletContext.class); when(context0.getContextPath()).thenReturn(""); when(context1.getContextPath()).thenReturn("/another"); ReflectionProvider reflectionProvider = new DefaultReflectionProvider(); Proxifier proxifier = new JavassistProxifier(); LinkToHandler handler0 = new LinkToHandler(context0, router, proxifier, reflectionProvider); LinkToHandler handler1 = new LinkToHandler(context1, router, proxifier, reflectionProvider); Object object0 = handler0.get(new DefaultBeanClass(TestController.class)); assertThat(object0.getClass().getName(), containsString("$linkTo_$$")); Object object1 = handler1.get(new DefaultBeanClass(TestController.class)); assertThat(object1.getClass().getName(), containsString("$linkTo$another_$$")); } |
DefaultLogicResult implements LogicResult { @Override public <T> T forwardTo(final Class<T> type) { return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { logger.debug("Executing {}", method); ControllerMethod old = methodInfo.getControllerMethod(); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(type, method)); Object methodResult = method.invoke(container.instanceFor(type), args); methodInfo.setControllerMethod(old); Type returnType = method.getGenericReturnType(); if (!(returnType == void.class)) { request.setAttribute(extractor.nameFor(returnType), methodResult); } if (response.isCommitted()) { logger.debug("Response already commited, not forwarding."); return null; } String path = resolver.pathFor(DefaultControllerMethod.instanceFor(type, method)); logger.debug("Forwarding to {}", path); request.getRequestDispatcher(path).forward(request, response); return null; } catch (InvocationTargetException e) { propagateIfPossible(e.getCause()); throw new ProxyInvocationException(e); } catch (Exception e) { throw new ProxyInvocationException(e); } } }); } protected DefaultLogicResult(); @Inject DefaultLogicResult(Proxifier proxifier, Router router, MutableRequest request, HttpServletResponse response,
Container container, PathResolver resolver, TypeNameExtractor extractor, FlashScope flash, MethodInfo methodInfo); @Override T forwardTo(final Class<T> type); @Override T redirectTo(final Class<T> type); } | @Test public void shouldIncludeReturnValueOnForward() throws Exception { givenDispatcherWillBeReturnedWhenRequested(); when(extractor.nameFor(String.class)).thenReturn("string"); logicResult.forwardTo(MyComponent.class).returnsValue(); verify(dispatcher).forward(request, response); verify(request).setAttribute("string", "A value"); }
@Test public void shouldExecuteTheLogicAndRedirectToItsViewOnForward() throws Exception { final MyComponent component = givenDispatcherWillBeReturnedWhenRequested(); assertThat(component.calls, is(0)); logicResult.forwardTo(MyComponent.class).base(); assertThat(component.calls, is(1)); verify(dispatcher).forward(request, response); }
@Test public void shouldForwardToMethodsDefaultViewWhenResponseIsNotCommited() throws Exception { givenDispatcherWillBeReturnedWhenRequested(); when(response.isCommitted()).thenReturn(false); logicResult.forwardTo(MyComponent.class).base(); verify(dispatcher).forward(request, response); }
@Test public void shouldNotForwardToMethodsDefaultViewWhenResponseIsCommited() throws Exception { givenDispatcherWillBeReturnedWhenRequested(); when(response.isCommitted()).thenReturn(true); logicResult.forwardTo(MyComponent.class).base(); verify(dispatcher, never()).forward(request, response); }
@Test public void shouldNotWrapValidationExceptionWhenForwarding() throws Exception { exception.expect(ValidationException.class); givenDispatcherWillBeReturnedWhenRequested(); when(response.isCommitted()).thenReturn(true); logicResult.forwardTo(MyComponent.class).throwsValidationException(); }
@Test public void shouldForwardToTheRightDefaultValue() throws Exception { Result result = mock(Result.class); PageResult pageResult = new DefaultPageResult(request, response, methodInfo, resolver, proxifier); when(result.use(PageResult.class)).thenReturn(pageResult); when(container.instanceFor(TheComponent.class)).thenReturn(new TheComponent(result)); when(resolver.pathFor(argThat(sameMethodAs(TheComponent.class.getDeclaredMethod("method"))))).thenReturn("controlled!"); when(request.getRequestDispatcher(anyString())).thenThrow(new AssertionError("should have called with the right method!")); doReturn(dispatcher).when(request).getRequestDispatcher("controlled!"); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(MyComponent.class, MyComponent.class.getDeclaredMethod("base"))); logicResult.forwardTo(TheComponent.class).method(); } |
FixedMethodStrategy implements Route { @Override public ControllerMethod controllerMethod(MutableRequest request, String uri) { parameters.fillIntoRequest(uri, request); return this.controllerMethod; } FixedMethodStrategy(String originalUri, ControllerMethod method, Set<HttpMethod> methods,
ParametersControl control, int priority, Parameter[] parameterNames); @Override boolean canHandle(Class<?> type, Method method); @Override ControllerMethod controllerMethod(MutableRequest request, String uri); @Override EnumSet<HttpMethod> allowedMethods(); @Override boolean canHandle(String uri); @Override String urlFor(Class<?> type, Method m, Object... params); @Override int getPriority(); @Override String getOriginalUri(); @Override ControllerMethod getControllerMethod(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void canTranslate() { FixedMethodStrategy strategy = new FixedMethodStrategy("abc", list, methods(HttpMethod.POST), control, 0, new Parameter[0]); when(control.matches("/clients/add")).thenReturn(true); ControllerMethod match = strategy.controllerMethod(request, "/clients/add"); assertThat(match, is(VRaptorMatchers.controllerMethod(method("list")))); verify(control, only()).fillIntoRequest("/clients/add", request); } |
DefaultLogicResult implements LogicResult { @Override public <T> T redirectTo(final Class<T> type) { logger.debug("redirecting to class {}", type.getSimpleName()); return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { checkArgument(acceptsHttpGet(method), "Your logic method must accept HTTP GET method if you want to redirect to it"); try { String url = router.urlFor(type, method, args); String path = request.getContextPath() + url; includeParametersInFlash(type, method, args); logger.debug("redirecting to {}", path); response.sendRedirect(path); return null; } catch (IOException e) { throw new ProxyInvocationException(e); } } }); } protected DefaultLogicResult(); @Inject DefaultLogicResult(Proxifier proxifier, Router router, MutableRequest request, HttpServletResponse response,
Container container, PathResolver resolver, TypeNameExtractor extractor, FlashScope flash, MethodInfo methodInfo); @Override T forwardTo(final Class<T> type); @Override T redirectTo(final Class<T> type); } | @Test public void shouldPutParametersOnFlashScopeOnRedirect() throws Exception { logicResult.redirectTo(MyComponent.class).withParameter("a"); verify(flash).includeParameters(any(ControllerMethod.class), eq(new Object[] {"a"})); }
@Test public void shouldNotPutParametersOnFlashScopeOnRedirectIfThereAreNoParameters() throws Exception { logicResult.redirectTo(MyComponent.class).base(); verify(flash, never()).includeParameters(any(ControllerMethod.class), any(Object[].class)); }
@Test public void clientRedirectingWillRedirectToTranslatedUrl() throws NoSuchMethodException, IOException { final String url = "custom_url"; when(request.getContextPath()).thenReturn("/context"); when(router.urlFor(MyComponent.class, MyComponent.class.getDeclaredMethod("base"))).thenReturn(url); logicResult.redirectTo(MyComponent.class).base(); verify(response).sendRedirect("/context" + url); }
@Test public void canRedirectWhenLogicMethodIsNotAnnotatedWithHttpMethods() throws Exception { logicResult.redirectTo(MyComponent.class).base(); verify(response).sendRedirect(any(String.class)); }
@Test public void canRedirectWhenLogicMethodIsAnnotatedWithHttpGetMethod() throws Exception { logicResult.redirectTo(MyComponent.class).annotatedWithGet(); verify(response).sendRedirect(any(String.class)); }
@Test public void cannotRedirectWhenLogicMethodIsAnnotatedWithAnyHttpMethodButGet() throws Exception { try { logicResult.redirectTo(MyComponent.class).annotated(); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { verify(response, never()).sendRedirect(any(String.class)); } } |
DefaultAcceptHeaderToFormat implements AcceptHeaderToFormat { @Override public String getFormat(final String acceptHeader) { if (acceptHeader == null || acceptHeader.trim().equals("")) { return DEFAULT_FORMAT; } if (acceptHeader.contains(DEFAULT_FORMAT)) { return DEFAULT_FORMAT; } return acceptToFormatCache.fetch(acceptHeader, new Supplier<String>() { @Override public String get() { return chooseMimeType(acceptHeader); } }); } protected DefaultAcceptHeaderToFormat(); @Inject DefaultAcceptHeaderToFormat(@LRU CacheStore<String, String> acceptToFormatCache); @Override String getFormat(final String acceptHeader); } | @Test public void shouldComplainIfThereIsNothingRegistered() { Assert.assertEquals("unknown", mimeTypeToFormat.getFormat("unknown")); }
@Test public void shouldReturnHtmlWhenRequestingAnyContentType() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("*/*")); }
@Test public void shouldReturnHtmlWhenAcceptsIsBlankContentType() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("")); }
@Test public void shouldReturnHtmlWhenRequestingUnknownAsFirstAndAnyContentType() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("unknow, */*")); }
@Test public void testHtml() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("text/html")); }
@Test public void testJson() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json")); }
@Test public void testJsonWithQualifier() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json; q=0.4")); }
@Test public void testNull() { Assert.assertEquals("html", mimeTypeToFormat.getFormat(null)); }
@Test public void testJsonInAComplexAcceptHeader() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json, text/javascript, */*")); }
@Test public void testPrecendenceInAComplexAcceptHeaderHtmlShouldPrevailWhenTied() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("application/json, text/html, */*")); }
@Test public void testPrecendenceInABizzarreMSIE8AcceptHeader() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, */*")); }
@Test public void testPrecendenceInABizzarreMSIE8AcceptHeaderWithHtml() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, text/html, */*")); }
@Test public void testPrecendenceInAComplexAcceptHeaderHtmlShouldPrevailWhenTied2() { Assert.assertEquals("html", mimeTypeToFormat.getFormat("text/html, application/json, */*")); }
@Test public void testJsonInAComplexAcceptHeaderWithParameters() { Assert.assertEquals("json", mimeTypeToFormat.getFormat("application/json; q=0.7, application/xml; q=0.1, */*")); }
@Test public void testXMLInAComplexAcceptHeaderWithParametersNotOrdered() { Assert.assertEquals("xml", mimeTypeToFormat.getFormat("application/json; q=0.1, application/xml; q=0.7, */*")); } |
PathAnnotationRoutesParser implements RoutesParser { @Override public List<Route> rulesFor(BeanClass controller) { Class<?> baseType = controller.getType(); return registerRulesFor(baseType); } protected PathAnnotationRoutesParser(); @Inject PathAnnotationRoutesParser(Router router, ReflectionProvider reflectionProvider); @Override List<Route> rulesFor(BeanClass controller); } | @Test public void addsAPrefixToMethodsWhenTheControllerHasMoreThanOneAnnotatedPath() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("You must specify exactly one path on @Path at class " + MoreThanOnePathAnnotatedController.class.getName()); parser.rulesFor(new DefaultBeanClass(MoreThanOnePathAnnotatedController.class)); }
@Test public void addsAPrefixToMethodsWhenTheControllerAndTheMethodAreAnnotatedWithRelativePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(PathAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix/relativePath"); assertThat(route, canHandle(PathAnnotatedController.class, "withRelativePath")); }
@Test public void addsAPrefixToMethodsWhenTheControllerEndsWithSlashAndTheMethodAreAnnotatedWithRelativePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(EndSlashAnnotatedController.class)); Route route = getRouteMatching(routes, "/endSlash/relativePath"); assertThat(route, canHandle(EndSlashAnnotatedController.class, "withRelativePath")); }
@Test public void addsAPrefixToMethodsWhenTheControllerEndsWithSlashAndTheMethodAreAnnotatedWithAbsolutePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(EndSlashAnnotatedController.class)); Route route = getRouteMatching(routes, "/endSlash/absolutePath"); assertThat(route, canHandle(EndSlashAnnotatedController.class, "withAbsolutePath")); }
@Test public void addsAPrefixToMethodsWhenTheControllerEndsWithSlashAndTheMethodAreAnnotatedWithEmptyPath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(EndSlashAnnotatedController.class)); Route route = getRouteMatching(routes, "/endSlash/"); assertThat(route, canHandle(EndSlashAnnotatedController.class, "withEmptyPath")); }
@Test public void addsAPrefixToMethodsWhenTheControllerAndTheMethodAreAnnotatedWithAbsolutePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(PathAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix/absolutePath"); assertThat(route, canHandle(PathAnnotatedController.class, "withAbsolutePath")); }
@Test public void addsAPrefixToMethodsWhenTheControllerAndTheMethodAreAnnotatedWithEmptyPath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(PathAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix"); assertThat(route, canHandle(PathAnnotatedController.class, "withEmptyPath")); }
@Test public void addsAPrefixToMethodsWhenTheControllerIsAnnotatedWithPath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(PathAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix/withoutPath"); assertThat(route, canHandle(PathAnnotatedController.class, "withoutPath")); }
@Test public void findsTheCorrectAnnotatedMethodIfThereIsNoWebMethodAnnotationPresent() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients"); assertThat(route, canHandle(ClientsController.class, "list")); }
@Test public void suportsTheDefaultNameForANonAnnotatedMethod() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients/add"); assertThat(route, canHandle(ClientsController.class, "add")); }
@Test public void ignoresTheControllerSuffixForANonAnnotatedMethod() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients/add"); assertThat(route, canHandle(ClientsController.class, "add")); }
@Test public void addsASlashWhenUserForgotIt() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/noSlash"); assertThat(route, canHandle(ClientsController.class, "noSlash")); }
@Test public void matchesWhenUsingAWildcard() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/move/second/child"); assertThat(route, canHandle(ClientsController.class, "move")); }
@Test public void dontRegisterRouteIfMethodIsNotPublic() { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/protectMe"); assertNull(route); }
@Test public void dontRegisterRouteIfMethodIsStatic() { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/staticMe"); assertNull(route); }
@Test public void shouldThrowExceptionIfPathAnnotationHasEmptyArray() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString("You must specify at least one path on @Path at")); parser.rulesFor(new DefaultBeanClass(NoPath.class)); }
@Test public void shouldFindNonAnnotatedNonStaticPublicMethodWithComponentNameInVariableCamelCaseConventionAsURI() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients/add"); assertThat(route, canHandle(ClientsController.class, "add")); }
@Test public void shouldFindSeveralPathsForMethodWithManyValue() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/path1"); assertThat(route, canHandle(ClientsController.class, "manyPaths")); Route route2 = getRouteMatching(routes, "/path2"); assertThat(route2, canHandle(ClientsController.class, "manyPaths")); }
@Test public void shouldNotMatchIfAControllerHasTheWrongWebMethod() throws SecurityException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients/remove"); assertThat(route.allowedMethods(), not(contains(HttpMethod.POST))); }
@Test public void shouldAcceptAResultWithASpecificWebMethod() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients/head"); assertThat(route.allowedMethods(), is(EnumSet.of(HttpMethod.HEAD))); }
@Test public void shouldAcceptAResultWithOptionsWebMethod() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients/options"); assertThat(route.allowedMethods(), is(EnumSet.of(HttpMethod.OPTIONS))); }
@Test public void shouldAcceptAResultWithPatchWebMethod() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(ClientsController.class)); Route route = getRouteMatching(routes, "/clients/update"); assertThat(route.allowedMethods(), is(EnumSet.of(HttpMethod.PATCH))); }
@Test public void findsInheritedMethodsWithDefaultNames() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(NiceClients.class)); Route route = getRouteMatching(routes, "/niceClients/toInherit"); assertTrue(route.canHandle(NiceClients.class, ClientsController.class.getDeclaredMethod("toInherit"))); }
@Test public void supportMethodOverriding() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(NiceClients.class)); Route route = getRouteMatching(routes, "/niceClients/add"); assertThat(route, canHandle(NiceClients.class, "add")); }
@Test public void supportTypeHttpMethodAnnotation() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(AnnotatedController.class)); Route route = getRouteMatching(routes, "/annotated/test"); assertThat(route.allowedMethods(), is(EnumSet.of(HttpMethod.POST))); }
@Test public void supportOverrideTypeHttpMethodAnnotation() throws SecurityException, NoSuchMethodException { List<Route> routes = parser.rulesFor(new DefaultBeanClass(AnnotatedController.class)); Route route = getRouteMatching(routes, "/annotated/overridden"); assertThat(route.allowedMethods(), is(EnumSet.of(HttpMethod.GET))); }
@Test public void addsAPrefixToMethodsWhenTheGetControllerAndTheMethodAreAnnotatedWithRelativePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(GetAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix/relativePath"); assertThat(route, canHandle(GetAnnotatedController.class, "withRelativePath")); }
@Test public void priorityForGetAnnotationShouldBeDefault() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(GetAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix/relativePath"); assertThat(route.getPriority(), is(Path.DEFAULT)); }
@Test public void addsAPrefixToMethodsWhenTheGetControllerEndsWithSlashAndTheMethodAreAnnotatedWithRelativePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(EndSlashAnnotatedGetController.class)); Route route = getRouteMatching(routes, "/endSlash/relativePath"); assertThat(route, canHandle(EndSlashAnnotatedGetController.class, "withRelativePath")); }
@Test public void addsAPrefixToMethodsWhenTheGetControllerEndsWithSlashAndTheMethodAreAnnotatedWithAbsolutePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(EndSlashAnnotatedGetController.class)); Route route = getRouteMatching(routes, "/endSlash/absolutePath"); assertThat(route, canHandle(EndSlashAnnotatedGetController.class, "withAbsolutePath")); }
@Test public void addsAPrefixToMethodsWhenTheGetControllerAndTheMethodAreAnnotatedWithAbsolutePath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(GetAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix/absolutePath"); assertThat(route, canHandle(GetAnnotatedController.class, "withAbsolutePath")); }
@Test public void addsAPrefixToMethodsWhenTheGetControllerIsAnnotatedWithPath() throws Exception { List<Route> routes = parser.rulesFor(new DefaultBeanClass(GetAnnotatedController.class)); Route route = getRouteMatching(routes, "/prefix/withoutPath"); assertThat(route, canHandle(GetAnnotatedController.class, "withoutPath")); }
@Test public void throwsExceptionWhenTheGetControllerHasAmbiguousDeclaration() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("You should specify paths either in @Path(\"/path\") or @Get(\"/path\") (or @Post, @Put, @Delete), not both at"); parser.rulesFor(new DefaultBeanClass(WrongGetAnnotatedController.class)); } |
DefaultValidationViewsFactory implements ValidationViewsFactory { @Override public <T extends View> T instanceFor(final Class<T> view, final List<Message> errors) { if (view.equals(EmptyResult.class)) { throw new ValidationException(errors); } return proxifier.proxify(view, throwValidationErrorOnFinalMethods(view, errors, result.use(view))); } protected DefaultValidationViewsFactory(); @Inject DefaultValidationViewsFactory(Result result, Proxifier proxifier, ReflectionProvider reflectionProvider); @Override T instanceFor(final Class<T> view, final List<Message> errors); } | @Test public void shouldUseValidationVersionOfLogicResult() throws Exception { exception.expect(ValidationException.class); when(result.use(LogicResult.class)).thenReturn(new MockedLogic()); factory.instanceFor(LogicResult.class, errors).forwardTo(RandomComponent.class).random(); }
@Test public void shouldThrowExceptionOnlyAtTheEndOfValidationCall() throws Exception { when(result.use(LogicResult.class)).thenReturn(new MockedLogic()); when(result.use(PageResult.class)).thenReturn(new MockedPage()); factory.instanceFor(LogicResult.class, errors); factory.instanceFor(LogicResult.class, errors).forwardTo(RandomComponent.class); factory.instanceFor(PageResult.class, errors); factory.instanceFor(PageResult.class, errors).of(RandomComponent.class); }
@Test public void shouldUseValidationVersionOfPageResult() throws Exception { exception.expect(ValidationException.class); when(result.use(PageResult.class)).thenReturn(new MockedPage()); factory.instanceFor(PageResult.class, errors).forwardTo("any uri"); }
@Test public void shouldUseValidationVersionOfEmptyResult() throws Exception { exception.expect(ValidationException.class); when(result.use(EmptyResult.class)).thenReturn(new EmptyResult()); factory.instanceFor(EmptyResult.class, errors); }
@Test public void onHttpResultShouldNotThrowExceptionsOnHeaders() throws Exception { HttpResult httpResult = mock(HttpResult.class); when(result.use(HttpResult.class)).thenReturn(httpResult); factory.instanceFor(HttpResult.class, errors); factory.instanceFor(HttpResult.class, errors).addDateHeader("abc", 123l); factory.instanceFor(HttpResult.class, errors).addHeader("def", "ghi"); factory.instanceFor(HttpResult.class, errors).addIntHeader("jkl", 456); factory.instanceFor(HttpResult.class, errors).addIntHeader("jkl", 456); }
@Test public void onHttpResultShouldThrowExceptionsOnSendError() throws Exception { exception.expect(ValidationException.class); HttpResult httpResult = mock(HttpResult.class); when(result.use(HttpResult.class)).thenReturn(httpResult); factory.instanceFor(HttpResult.class, errors).sendError(404); }
@Test public void onHttpResultShouldThrowExceptionsOnSendErrorWithMessage() throws Exception { exception.expect(ValidationException.class); HttpResult httpResult = mock(HttpResult.class); when(result.use(HttpResult.class)).thenReturn(httpResult); factory.instanceFor(HttpResult.class, errors).sendError(404, "Not Found"); }
@Test public void onHttpResultShouldThrowExceptionsOnSetStatus() throws Exception { exception.expect(ValidationException.class); HttpResult httpResult = mock(HttpResult.class); when(result.use(HttpResult.class)).thenReturn(httpResult); factory.instanceFor(HttpResult.class, errors).setStatusCode(200); }
@Test public void shouldBeAbleToChainMethodsOnHttpResult() throws Exception { HttpResult httpResult = mock(HttpResult.class); when(result.use(HttpResult.class)).thenReturn(httpResult); factory.instanceFor(HttpResult.class, errors).addDateHeader("abc", 123l).addHeader("def", "ghi").addIntHeader("jkl", 234); }
@Test public void onStatusResultShouldThrowExceptionsOnMoved() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); when(status.movedPermanentlyTo(RandomComponent.class)).thenReturn(new RandomComponent()); try { factory.instanceFor(Status.class, errors).movedPermanentlyTo(RandomComponent.class); } catch (ValidationException e) { Assert.fail("The exception must occur only on method call"); } factory.instanceFor(Status.class, errors).movedPermanentlyTo(RandomComponent.class).random(); }
@Test public void onStatusResultShouldThrowExceptionsOnMovedToLogic() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).movedPermanentlyTo("anywhere"); }
@Test public void onRefererResultShouldThrowExceptionsOnForward() throws Exception { exception.expect(ValidationException.class); RefererResult referer = mock(RefererResult.class); when(result.use(RefererResult.class)).thenReturn(referer); factory.instanceFor(RefererResult.class, errors).forward(); }
@Test public void onRefererResultShouldThrowExceptionsOnRedirect() throws Exception { exception.expect(ValidationException.class); RefererResult referer = mock(RefererResult.class); when(result.use(RefererResult.class)).thenReturn(referer); factory.instanceFor(RefererResult.class, errors).redirect(); }
@Test public void onStatusResultShouldThrowExceptionsOnNotFound() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).notFound(); }
@Test public void onStatusResultShouldThrowExceptionsOnHeader() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).header("abc", "def"); }
@Test public void onStatusResultShouldThrowExceptionsOnCreated() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).created(); }
@Test public void onStatusResultShouldThrowExceptionsOnCreatedWithLocation() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).created("/newLocation"); }
@Test public void onStatusResultShouldThrowExceptionsOnOk() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).ok(); }
@Test public void onStatusResultShouldThrowExceptionsOnConflict() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).conflict(); }
@Test public void onStatusResultShouldThrowExceptionsOnMethodNotAllowed() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).methodNotAllowed(EnumSet.allOf(HttpMethod.class)); }
@Test public void onStatusResultShouldThrowExceptionsOnMovedPermanentlyTo() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); factory.instanceFor(Status.class, errors).movedPermanentlyTo("/newUri"); }
@Test public void onStatusResultShouldThrowExceptionsOnMovedPermanentlyToLogic() throws Exception { exception.expect(ValidationException.class); Status status = mock(Status.class); when(result.use(Status.class)).thenReturn(status); when(status.movedPermanentlyTo(RandomComponent.class)).thenReturn(new RandomComponent()); try { factory.instanceFor(Status.class, errors).movedPermanentlyTo(RandomComponent.class); } catch (ValidationException e) { Assert.fail("Should not throw exception yet"); } factory.instanceFor(Status.class, errors).movedPermanentlyTo(RandomComponent.class).random(); }
@Test public void onXMLSerializationResultShouldThrowExceptionOnlyOnSerializeMethod() throws Exception { exception.expect(ValidationException.class); JSONSerialization serialization = mock(JSONSerialization.class); serializerBuilder = mock(SerializerBuilder.class, new Answer<SerializerBuilder>() { @Override public SerializerBuilder answer(InvocationOnMock invocation) throws Throwable { return serializerBuilder; } }); when(result.use(JSONSerialization.class)).thenReturn(serialization); when(serialization.from(any())).thenReturn(serializerBuilder); try { factory.instanceFor(JSONSerialization.class, errors).from(new Object()); factory.instanceFor(JSONSerialization.class, errors).from(new Object()).include("abc"); factory.instanceFor(JSONSerialization.class, errors).from(new Object()).exclude("abc"); } catch (ValidationException e) { Assert.fail("Should not throw exception yet"); } factory.instanceFor(JSONSerialization.class, errors).from(new Object()).serialize(); }
@Test public void onSerializerResultsShouldBeAbleToCreateValidationInstancesEvenIfChildClassesUsesCovariantType() throws Exception { exception.expect(ValidationException.class); JSONSerialization serialization = mock(JSONSerialization.class); serializerBuilder = new RandomSerializer(); when(result.use(JSONSerialization.class)).thenReturn(serialization); when(serialization.from(any())).thenReturn(serializerBuilder); try { factory.instanceFor(JSONSerialization.class, errors).from(new Object()); factory.instanceFor(JSONSerialization.class, errors).from(new Object()).include("abc"); factory.instanceFor(JSONSerialization.class, errors).from(new Object()).exclude("abc"); } catch (ValidationException e) { Assert.fail("Should not throw exception yet"); } factory.instanceFor(JSONSerialization.class, errors).from(new Object()).serialize(); } |
DefaultStatus implements Status { @Override public void header(String key, String value) { response.addHeader(key, value); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @Test public void shouldSetHeader() throws Exception { status.header("Content-type", "application/xml"); verify(response).addHeader("Content-type", "application/xml"); } |
DefaultStatus implements Status { @Override public void created() { response.setStatus(HttpServletResponse.SC_CREATED); result.use(Results.nothing()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @Test public void shouldSetCreatedStatus() throws Exception { status.created(); verify(response).setStatus(201); }
@Test public void shouldSetCreatedStatusAndLocationWithAppPath() throws Exception { when(config.getApplicationPath()).thenReturn("http: status.created("/newResource"); verify(response).setStatus(201); verify(response).addHeader("Location", "http: } |
DefaultStatus implements Status { @Override public void ok() { response.setStatus(HttpServletResponse.SC_OK); result.use(Results.nothing()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @Test public void shouldSetOkStatus() throws Exception { status.ok(); verify(response).setStatus(200); } |
DefaultStatus implements Status { @Override public void accepted(){ response.setStatus(HttpServletResponse.SC_ACCEPTED ); result.use(Results.nothing()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @Test public void shouldSetAcceptedStatus() throws Exception { status.accepted(); verify(response).setStatus(202); } |
DefaultStatus implements Status { @Override public void notImplemented() { response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @Test public void shouldSetNotImplementedStatus() throws Exception { status.notImplemented(); verify(response).setStatus(501); } |
DefaultStatus implements Status { @Override public void internalServerError() { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @Test public void shouldSetInternalServerErrorStatus() throws Exception { status.internalServerError(); verify(response).setStatus(500); } |
DefaultStatus implements Status { @Override public void movedPermanentlyTo(String location) { this.response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); header("Location", fixLocation(location)); this.response.addIntHeader("Content-length", 0); this.response.addDateHeader("Date", System.currentTimeMillis()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @Test public void shouldSetMovedPermanentlyStatus() throws Exception { when(config.getApplicationPath()).thenReturn("http: status.movedPermanentlyTo("/newURL"); verify(response).setStatus(301); verify(response).addHeader("Location", "http: }
@Test public void shouldMoveToExactlyURIWhenItIsNotAbsolute() throws Exception { status.movedPermanentlyTo("http: verify(response).addHeader("Location", "http: verify(response).setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); }
@Test public void shouldSetMovedPermanentlyStatusOfLogic() throws Exception { when(config.getApplicationPath()).thenReturn("http: Method method = Resource.class.getDeclaredMethod("method"); when(router.urlFor(eq(Resource.class), eq(method), Mockito.anyVararg())).thenReturn("/resource/method"); status.movedPermanentlyTo(Resource.class).method(); verify(response).setStatus(301); verify(response).addHeader("Location", "http: } |
DefaultStatus implements Status { @Override public void badRequest(String message) { sendError(HttpServletResponse.SC_BAD_REQUEST, message); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); } | @SuppressWarnings("deprecation") @Test public void shouldSerializeErrorMessages() throws Exception { Message normal = new SimpleMessage("category", "The message"); I18nMessage i18ned = new I18nMessage("category", "message"); i18ned.setBundle(new SingletonResourceBundle("message", "Something else")); XStreamBuilder xstreamBuilder = cleanInstance(new MessageConverter()); MockSerializationResult result = new MockSerializationResult(null, xstreamBuilder, null, null); DefaultStatus status = new DefaultStatus(response, result, config, new JavassistProxifier(), router); status.badRequest(Arrays.asList(normal, i18ned)); String serialized = result.serializedResult(); assertThat(serialized, containsString("<message>The message</message>")); assertThat(serialized, containsString("<category>category</category>")); assertThat(serialized, containsString("<message>Something else</message>")); assertThat(serialized, not(containsString("<validationMessage>"))); assertThat(serialized, not(containsString("<i18nMessage>"))); }
@SuppressWarnings("deprecation") @Test public void shouldSerializeErrorMessagesInJSON() throws Exception { Message normal = new SimpleMessage("category", "The message"); I18nMessage i18ned = new I18nMessage("category", "message"); i18ned.setBundle(new SingletonResourceBundle("message", "Something else")); List<JsonSerializer<?>> gsonSerializers = new ArrayList<>(); List<JsonDeserializer<?>> gsonDeserializers = new ArrayList<>(); gsonSerializers.add(new MessageGsonConverter()); GsonSerializerBuilder gsonBuilder = new GsonBuilderWrapper(new MockInstanceImpl<>(gsonSerializers), new MockInstanceImpl<>(gsonDeserializers), new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider()); MockSerializationResult result = new MockSerializationResult(null, null, gsonBuilder, new DefaultReflectionProvider()) { @Override public <T extends View> T use(Class<T> view) { return view.cast(new DefaultRepresentationResult(new FormatResolver() { @Override public String getAcceptFormat() { return "json"; } }, this, new MockInstanceImpl<Serialization>(super.use(JSONSerialization.class)))); } }; DefaultStatus status = new DefaultStatus(response, result, config, new JavassistProxifier(), router); status.badRequest(Arrays.asList(normal, i18ned)); String serialized = result.serializedResult(); assertThat(serialized, containsString("\"message\":\"The message\"")); assertThat(serialized, containsString("\"category\":\"category\"")); assertThat(serialized, containsString("\"message\":\"Something else\"")); assertThat(serialized, not(containsString("\"validationMessage\""))); assertThat(serialized, not(containsString("\"i18nMessage\""))); } |
DefaultPageResult implements PageResult { @Override public void redirectTo(String url) { logger.debug("redirection to {}", url); try { if (url.startsWith("/")) { response.sendRedirect(request.getContextPath() + url); } else { response.sendRedirect(url); } } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); } | @Test public void shouldRedirectIncludingContext() throws Exception { when(request.getContextPath()).thenReturn("/context"); view.redirectTo("/any/url"); verify(response).sendRedirect("/context/any/url"); }
@Test public void shouldNotIncludeContextPathIfURIIsAbsolute() throws Exception { view.redirectTo("http: verify(request, never()).getContextPath(); verify(response, only()).sendRedirect("http: }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileRedirect() throws Exception { exception.expect(ResultException.class); doThrow(new IOException()).when(response).sendRedirect(anyString()); view.redirectTo("/any/url"); } |
VRaptorRequest extends HttpServletRequestWrapper implements MutableRequest { @Override public String getParameter(String name) { if (extraParameters.containsKey(name)) { return extraParameters.get(name)[0]; } return super.getParameter(name); } VRaptorRequest(HttpServletRequest request); @Override String getParameter(String name); @Override Enumeration<String> getParameterNames(); @Override String[] getParameterValues(String name); @Override Map<String, String[]> getParameterMap(); @Override void setParameter(String key, String... value); @Override String getRequestedUri(); static String getRelativeRequestURI(HttpServletRequest request); @Override String toString(); } | @Test public void searchesOnTheFallbackRequest() { assertThat(vraptor.getParameter("name"), is(equalTo("guilherme"))); }
@Test public void returnsNullIfNotFound() { assertThat(vraptor.getParameter("minimum"), is(nullValue())); } |
DefaultPageResult implements PageResult { @Override public void forwardTo(String url) { logger.debug("forwarding to {}", url); try { request.getRequestDispatcher(url).forward(request, response); } catch (ServletException | IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); } | @Test public void shouldForwardToGivenURI() throws Exception { when(request.getRequestDispatcher("/any/url")).thenReturn(dispatcher); view.forwardTo("/any/url"); verify(dispatcher, only()).forward(request, response); }
@Test public void shouldThrowResultExceptionIfServletExceptionOccursWhileForwarding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).forward(request, response); view.forwardTo("/any/url"); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileForwarding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).forward(request, response); view.forwardTo("/any/url"); } |
DefaultPageResult implements PageResult { @Override public void defaultView() { String to = resolver.pathFor(methodInfo.getControllerMethod()); logger.debug("forwarding to {}", to); try { request.getRequestDispatcher(to).forward(request, response); } catch (ServletException e) { throw new ApplicationLogicException(to + " raised an exception", e); } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); } | @Test public void shouldAllowCustomPathResolverWhileForwardingView() throws ServletException, IOException { when(request.getRequestDispatcher("fixed")).thenReturn(dispatcher); view.defaultView(); verify(dispatcher, only()).forward(request, response); }
@Test public void shouldThrowApplicationLogicExceptionIfServletExceptionOccursWhileForwardingView() throws Exception { exception.expect(ApplicationLogicException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).forward(request, response); view.defaultView(); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileForwardingView() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).forward(request, response); view.defaultView(); } |
DefaultPageResult implements PageResult { @Override public void include() { try { String to = resolver.pathFor(methodInfo.getControllerMethod()); logger.debug("including {}", to); request.getRequestDispatcher(to).include(request, response); } catch (ServletException e) { throw new ResultException(e); } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); } | @Test public void shouldAllowCustomPathResolverWhileIncluding() throws ServletException, IOException { when(request.getRequestDispatcher("fixed")).thenReturn(dispatcher); view.include(); verify(dispatcher, only()).include(request, response); }
@Test public void shouldThrowResultExceptionIfServletExceptionOccursWhileIncluding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).include(request, response); view.include(); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileIncluding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).include(request, response); view.include(); } |
DefaultPageResult implements PageResult { @Override public <T> T of(final Class<T> controllerType) { return proxifier.proxify(controllerType, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { request.getRequestDispatcher( resolver.pathFor(DefaultControllerMethod.instanceFor(controllerType, method))).forward( request, response); return null; } catch (Exception e) { throw new ProxyInvocationException(e); } } }); } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); } | @Test public void shoudNotExecuteLogicWhenUsingResultOf() { when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); try { view.of(SimpleController.class).notAllowedMethod(); } catch (UnsupportedOperationException e) { fail("Method should not be executed"); } }
@Test public void shoudThrowProxyInvocationExceptionIfAndExceptionOccursWhenUsingResultOf() { exception.expect(ProxyInvocationException.class); doThrow(new NullPointerException()).when(request).getRequestDispatcher(anyString()); view.of(SimpleController.class).notAllowedMethod(); } |
DefaultPathResolver implements PathResolver { @Override public String pathFor(ControllerMethod method) { logger.debug("Resolving path for {}", method); String format = resolver.getAcceptFormat(); String suffix = ""; if (format != null && !format.equals("html")) { suffix = "." + format; } String name = method.getController().getType().getSimpleName(); String folderName = extractControllerFromName(name); String path = getPrefix() + folderName + "/" + method.getMethod().getName() + suffix + "." + getExtension(); logger.debug("Returning path {} for {}", path, method); return path; } protected DefaultPathResolver(); @Inject DefaultPathResolver(FormatResolver resolver); @Override String pathFor(ControllerMethod method); } | @Test public void shouldUseResourceTypeAndMethodNameToResolveJsp(){ when(formatResolver.getAcceptFormat()).thenReturn(null); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.jsp")); }
@Test public void shouldUseTheFormatIfSupplied() throws NoSuchMethodException { when(formatResolver.getAcceptFormat()).thenReturn("json"); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.json.jsp")); }
@Test public void shouldIgnoreHtmlFormat() throws NoSuchMethodException { when(formatResolver.getAcceptFormat()).thenReturn("html"); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.jsp")); } |
DefaultHttpResult implements HttpResult { @Override public void sendError(int statusCode) { try { response.sendError(statusCode); } catch (IOException e) { throw new ResultException("Error while setting status code", e); } } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); } | @Test public void shouldSendError() throws Exception { httpResult.sendError(SC_INTERNAL_SERVER_ERROR); verify(response).sendError(SC_INTERNAL_SERVER_ERROR); }
@Test public void shouldThrowsResultExceptionIfAnIOExceptionWhenSendError() throws Exception { doThrow(new IOException()).when(response).sendError(anyInt()); try { httpResult.sendError(SC_INTERNAL_SERVER_ERROR); fail("should throw ResultException"); } catch (ResultException e) { verify(response, only()).sendError(anyInt()); } }
@Test public void shouldSendErrorWithMessage() throws Exception { httpResult.sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); verify(response).sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenSendErrorWithMessage() throws Exception { doThrow(new IOException()).when(response).sendError(anyInt(), anyString()); try { httpResult.sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); fail("should throw ResultException"); } catch (ResultException e) { verify(response, only()).sendError(anyInt(), anyString()); } } |
DefaultHttpResult implements HttpResult { @Override public void setStatusCode(int statusCode) { response.setStatus(statusCode); } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); } | @Test public void shouldSetStatusCode() throws Exception { httpResult.setStatusCode(SC_INTERNAL_SERVER_ERROR); verify(response).setStatus(SC_INTERNAL_SERVER_ERROR); } |
DefaultHttpResult implements HttpResult { @Override public HttpResult body(String body) { try { response.getWriter().print(body); } catch (IOException e) { throw new ResultException("Couldn't write to response body", e); } return this; } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); } | @Test public void shouldWriteStringBody() throws Exception { PrintWriter writer = mock(PrintWriter.class); when(response.getWriter()).thenReturn(writer); httpResult.body("The text"); verify(writer).print(anyString()); }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteStringBody() throws Exception { doThrow(new IOException()).when(response).getWriter(); try { httpResult.body("The text"); fail("should throw ResultException"); } catch (ResultException e) { } }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteInputStreamBody() throws Exception { doThrow(new IOException()).when(response).getOutputStream(); InputStream in = new ByteArrayInputStream("the text".getBytes()); try { httpResult.body(in); fail("should throw ResultException"); } catch (ResultException e) { } }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteReaderBody() throws Exception { doThrow(new IOException()).when(response).getWriter(); Reader reader = new StringReader("the text"); try { httpResult.body(reader); fail("should throw ResultException"); } catch (ResultException e) { } } |
DefaultRefererResult implements RefererResult { @Override public void forward() throws IllegalStateException { String referer = getReferer(); try { ControllerMethod method = router.parse(referer, HttpMethod.GET, request); executeMethod(method, result.use(logic()).forwardTo(method.getController().getType())); } catch (ControllerNotFoundException | MethodNotAllowedException e) { logger.warn("Could not find or doesn't allowed to get controller method", e); result.use(page()).forwardTo(referer); } } protected DefaultRefererResult(); @Inject DefaultRefererResult(Result result, MutableRequest request, Router router, ParametersProvider provider,
ReflectionProvider reflectionProvider); @Override void forward(); @Override void redirect(); } | @Test public void whenThereIsNoRefererShouldThrowExceptionOnForward() throws Exception { when(request.getHeader("Referer")).thenReturn(null); try { refererResult.forward(); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { } }
@Test public void whenRefererDontMatchAControllerShouldForwardToPage() throws Exception { PageResult page = mock(PageResult.class); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenThrow(new ControllerNotFoundException()); doReturn(page).when(result).use(page()); refererResult.forward(); verify(page).forwardTo("/no-controller"); }
@Test public void whenRefererMatchesAControllerShouldForwardToIt() throws Exception { LogicResult logic = mock(LogicResult.class); RefererController controller = mock(RefererController.class); Method index = RefererController.class.getMethod("index"); ControllerMethod method = DefaultControllerMethod.instanceFor(RefererController.class, index); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenReturn(method); doReturn(logic).when(result).use(logic()); when(logic.forwardTo(RefererController.class)).thenReturn(controller); refererResult.forward(); verify(logic).forwardTo(RefererController.class); verify(controller).index(); } |
DefaultRefererResult implements RefererResult { @Override public void redirect() throws IllegalStateException { String referer = getReferer(); try { ControllerMethod method = router.parse(referer, HttpMethod.GET, request); executeMethod(method, result.use(logic()).redirectTo(method.getController().getType())); } catch (ControllerNotFoundException | MethodNotAllowedException e) { logger.warn("Could not find or doesn't allowed to get controller method", e); result.use(page()).redirectTo(referer); } } protected DefaultRefererResult(); @Inject DefaultRefererResult(Result result, MutableRequest request, Router router, ParametersProvider provider,
ReflectionProvider reflectionProvider); @Override void forward(); @Override void redirect(); } | @Test public void whenThereIsNoRefererShouldThrowExceptionOnRedirect() throws Exception { when(request.getHeader("Referer")).thenReturn(null); try { refererResult.redirect(); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { } }
@Test public void whenRefererDontMatchAControllerShouldRedirectToPage() throws Exception { PageResult page = mock(PageResult.class); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenThrow(new ControllerNotFoundException()); doReturn(page).when(result).use(page()); refererResult.redirect(); verify(page).redirectTo("/no-controller"); }
@Test public void whenRefererMatchesAControllerShouldRedirectToIt() throws Exception { LogicResult logic = mock(LogicResult.class); RefererController controller = mock(RefererController.class); Method index = RefererController.class.getMethod("index"); ControllerMethod method = DefaultControllerMethod.instanceFor(RefererController.class, index); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenReturn(method); doReturn(logic).when(result).use(logic()); when(logic.redirectTo(RefererController.class)).thenReturn(controller); refererResult.redirect(); verify(logic).redirectTo(RefererController.class); verify(controller).index(); } |
DefaultRefererResult implements RefererResult { protected String getReferer() { String referer = request.getHeader("Referer"); checkState(referer != null, "The Referer header was not specified"); String refererPath = null; try { refererPath = new URL(referer).getPath(); } catch(MalformedURLException e) { refererPath = referer; } String ctxPath = request.getContextPath(); return refererPath.startsWith(ctxPath+"/") || refererPath.equals(ctxPath) ? refererPath.substring(ctxPath.length()) : refererPath; } protected DefaultRefererResult(); @Inject DefaultRefererResult(Result result, MutableRequest request, Router router, ParametersProvider provider,
ReflectionProvider reflectionProvider); @Override void forward(); @Override void redirect(); } | @Test public void whenCtxPathAppearsInItsPlaceRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/test"); assertEquals("/anything/ok", refererResult.getReferer()); }
@Test public void whenCtxPathAppearsAmongURLButNotInRightPlaceRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vrap"); assertEquals("/vrapanything/ok/vrap/ok/vrap", refererResult.getReferer()); }
@Test public void whenCtxPathEqualsURLPathRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vrap"); assertEquals("/", refererResult.getReferer()); }
@Test public void whenRefererIsARelativePathRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("/vrap/anything/ok/vrap"); when(request.getContextPath()).thenReturn("/vrap"); assertEquals("/anything/ok/vrap", refererResult.getReferer()); } |
CDIBasedContainer implements Container { @Override @SuppressWarnings("unchecked") public <T> T instanceFor(Class<T> type) { type = (Class<T>) CDIProxies.extractRawTypeIfPossible(type); logger.debug("asking cdi to get instance for {}", type); Bean<?> bean = getBeanFrom(type); CreationalContext<?> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, type, ctx); } protected CDIBasedContainer(); @Inject CDIBasedContainer(BeanManager beanManager); @Override @SuppressWarnings("unchecked") T instanceFor(Class<T> type); @Override @SuppressWarnings("unchecked") boolean canProvide(Class<T> type); } | @Test public void shouldCreateComponentsWithCache(){ UsingCacheComponent component = cdiBasedContainer.instanceFor(UsingCacheComponent.class); component.putWithLRU("test","test"); component.putWithDefault("test2","test2"); assertEquals(component.putWithLRU("test","test"),"test"); assertEquals(component.putWithDefault("test2","test2"),"test2"); }
@Test public void shoudRegisterResourcesInRouter() { initEvent.fire(new VRaptorInitialized(null)); Router router = instanceFor(Router.class); Matcher<Iterable<? super Route>> hasItem = hasItem(canHandle(ControllerInTheClasspath.class, ControllerInTheClasspath.class.getDeclaredMethods()[0])); assertThat(router.allRoutes(), hasItem); }
@Test public void shoudRegisterConvertersInConverters() { Converters converters = instanceFor(Converters.class); Converter<?> converter = converters.to(Void.class); assertThat(converter, is(instanceOf(ConverterInTheClasspath.class))); }
@Test public void shouldReturnAllDefaultDeserializers() { Deserializers deserializers = instanceFor(Deserializers.class); List<String> types = asList("application/json", "json", "application/xml", "xml", "text/xml", "application/x-www-form-urlencoded"); for (String type : types) { assertThat("deserializer not found: " + type, deserializers.deserializerFor(type, cdiBasedContainer), is(notNullValue())); } }
@Test public void shouldReturnAllDefaultConverters() { Converters converters = instanceFor(Converters.class); final HashMap<Class<?>, Class<?>> EXPECTED_CONVERTERS = new HashMap<Class<?>, Class<?>>() { { put(int.class, PrimitiveIntConverter.class); put(long.class, PrimitiveLongConverter.class); put(short.class, PrimitiveShortConverter.class); put(byte.class, PrimitiveByteConverter.class); put(double.class, PrimitiveDoubleConverter.class); put(float.class, PrimitiveFloatConverter.class); put(boolean.class, PrimitiveBooleanConverter.class); put(Integer.class, IntegerConverter.class); put(Long.class, LongConverter.class); put(Short.class, ShortConverter.class); put(Byte.class, ByteConverter.class); put(Double.class, DoubleConverter.class); put(Float.class, FloatConverter.class); put(Boolean.class, BooleanConverter.class); put(Calendar.class, CalendarConverter.class); put(Date.class, DateConverter.class); put(Enum.class, EnumConverter.class); } private static final long serialVersionUID = 8559316558416038474L; }; for (Entry<Class<?>, Class<?>> entry : EXPECTED_CONVERTERS.entrySet()) { Converter<?> converter = converters.to((Class<?>) entry.getKey()); assertThat(converter, is(instanceOf(entry.getValue()))); } }
@Test public void shoudRegisterInterceptorsInInterceptorRegistry() { InterceptorRegistry registry = instanceFor(InterceptorRegistry.class); assertThat(registry.all(), hasOneCopyOf(InterceptorInTheClasspath.class)); } |
InterceptorStereotypeHandler { public void handle(@Observes @InterceptsQualifier BeanClass beanClass) { Class<?> originalType = beanClass.getType(); interceptorValidator.validate(originalType); logger.debug("Found interceptor for {}", originalType); registry.register(originalType); } protected InterceptorStereotypeHandler(); @Inject InterceptorStereotypeHandler(InterceptorRegistry registry, InterceptorValidator validator); void handle(@Observes @InterceptsQualifier BeanClass beanClass); } | @Test public void shouldRegisterInterceptorsOnRegistry() throws Exception { handler.handle(new DefaultBeanClass(InterceptorA.class)); verify(interceptorRegistry, times(1)).register(InterceptorA.class); } |
DefaultResult extends AbstractResult { @Override public <T extends View> T use(Class<T> view) { messages.assertAbsenceOfErrors(); responseCommitted = true; return container.instanceFor(view); } protected DefaultResult(); @Inject DefaultResult(HttpServletRequest request, Container container, ExceptionMapper exceptions, TypeNameExtractor extractor,
Messages messages); @Override T use(Class<T> view); @Override Result on(Class<? extends Exception> exception); @Override Result include(String key, Object value); @Override boolean used(); @Override Map<String, Object> included(); @Override Result include(Object value); } | @Test public void shouldUseContainerForNewView() { final MyView expectedView = new MyView(); when(container.instanceFor(MyView.class)).thenReturn(expectedView); MyView view = result.use(MyView.class); assertThat(view, is(expectedView)); }
@Test public void shouldCallAssertAbsenceOfErrorsMethodFromMessages() throws Exception { result.use(Results.json()); verify(messages).assertAbsenceOfErrors(); } |
DefaultResult extends AbstractResult { @Override public Result include(String key, Object value) { logger.debug("including attribute {}: {}", key, value); includedAttributes.put(key, value); request.setAttribute(key, value); return this; } protected DefaultResult(); @Inject DefaultResult(HttpServletRequest request, Container container, ExceptionMapper exceptions, TypeNameExtractor extractor,
Messages messages); @Override T use(Class<T> view); @Override Result on(Class<? extends Exception> exception); @Override Result include(String key, Object value); @Override boolean used(); @Override Map<String, Object> included(); @Override Result include(Object value); } | @Test public void shouldSetRequestAttribute() { result.include("my_key", "my_value"); verify(request).setAttribute("my_key", "my_value"); }
@Test public void shouldIncludeExtractedNameWhenSimplyIncluding() throws Exception { Account account = new Account(); when(extractor.nameFor(Account.class)).thenReturn("account"); result.include(account); verify(request).setAttribute("account", account); }
@Test public void shouldNotIncludeTheAttributeWhenTheValueIsNull() throws Exception { result.include(null); verify(request, never()).setAttribute(anyString(), anyObject()); } |
InterceptorStackHandlersCache { public LinkedList<InterceptorHandler> getInterceptorHandlers() { return new LinkedList<>(interceptorHandlers); } protected InterceptorStackHandlersCache(); @Inject InterceptorStackHandlersCache(InterceptorRegistry registry, InterceptorHandlerFactory handlerFactory); void init(); LinkedList<InterceptorHandler> getInterceptorHandlers(); } | @Test public void shouldReturnHandlersListInTheSameOrderThatRegistry() { LinkedList<InterceptorHandler> handlers = cache.getInterceptorHandlers(); assertEquals(FirstInterceptor.class, extractInterceptor(handlers.get(0))); assertEquals(SecondInterceptor.class, extractInterceptor(handlers.get(1))); }
@Test public void cacheShouldBeImmutable() { cache.getInterceptorHandlers().remove(0); assertEquals(2, cache.getInterceptorHandlers().size()); } |
JstlLocalization { @Produces public Locale getLocale() { Locale localeFromConfig = localeFor(Config.FMT_LOCALE); return firstNonNull(localeFromConfig, Locale.getDefault()); } protected JstlLocalization(); @Inject JstlLocalization(HttpServletRequest request); @Produces ResourceBundle getBundle(Locale locale); @Produces Locale getLocale(); } | @Test public void shouldGetLocaleFromRequestFirst() { when(request.getAttribute(FMT_LOCALE + ".request")).thenReturn(PT_BR); when(session.getAttribute(FMT_LOCALE + ".session")).thenReturn(Locale.ENGLISH); when(servletContext.getAttribute(FMT_LOCALE + ".application")).thenReturn(Locale.ENGLISH); when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(Locale.ENGLISH.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromSessionWhenNotFoundInRequest() { when(session.getAttribute(FMT_LOCALE + ".session")).thenReturn(PT_BR); when(servletContext.getAttribute(FMT_LOCALE + ".application")).thenReturn(Locale.ENGLISH); when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(Locale.ENGLISH.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromServletContextWhenNotFoundInSession() { when(servletContext.getAttribute(FMT_LOCALE + ".application")).thenReturn(PT_BR); when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(Locale.ENGLISH.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromInitParameterWhenNotFoundInServletContext() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(PT_BR.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromRequestLocaleWhenNotFoundUnderAnyOtherScope() { when(request.getLocale()).thenReturn(PT_BR); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void findLocaleFromDefaultWhenNotFoundInAnyOtherScope() { assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(Locale.ENGLISH)); }
@Test public void parseLocaleWithLanguage() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn("pt"); assertThat(localization.getLocale().getLanguage(), equalTo("pt")); }
@Test public void parseLocaleWithLanguageAndCountry() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn("pt_BR"); assertThat(localization.getLocale().getLanguage(), equalTo("pt")); assertThat(localization.getLocale().getCountry(), equalTo("BR")); }
@Test public void parseLocaleWithLanguageAndCountryAndVariant() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn("pt_BR_POSIX"); assertThat(localization.getLocale().getLanguage(), equalTo("pt")); assertThat(localization.getLocale().getCountry(), equalTo("BR")); assertThat(localization.getLocale().getVariant(), equalTo("POSIX")); } |
DefaultInterceptorStack implements InterceptorStack { @Override public void start() { ControllerMethod method = controllerMethod.get(); interceptorsReadyEvent.fire(new InterceptorsReady(method)); LinkedList<InterceptorHandler> handlers = cache.getInterceptorHandlers(); internalStack.addFirst(handlers.iterator()); this.next(method, controllerInstance.get().getController()); internalStack.poll(); } protected DefaultInterceptorStack(); @Inject DefaultInterceptorStack(InterceptorStackHandlersCache cache, Instance<ControllerMethod>
controllerMethod, Instance<ControllerInstance> controllerInstance, Event<InterceptorsExecuted> event,
Event<InterceptorsReady> stackStartingEvent); @Override void next(ControllerMethod method, Object controllerInstance); @Override void start(); } | @Test public void firesStartEventOnStart() throws Exception { stack.start(); verify(interceptorsReadyEvent).fire(any(InterceptorsReady.class)); }
@Test public void executesTheFirstHandler() throws Exception { stack.start(); verify(handler).execute(stack, controllerMethod, controller); }
@Test public void doesntFireEndOfStackIfTheInterceptorsDontContinueTheStack() throws Exception { stack.start(); verify(interceptorsExecutedEvent, never()).fire(any(InterceptorsExecuted.class)); }
@Test public void firesEndOfStackIfAllInterceptorsWereExecuted() throws Exception { doAnswer(callNext()).when(handler).execute(stack, controllerMethod, controller); stack.start(); verify(interceptorsExecutedEvent).fire(any(InterceptorsExecuted.class)); } |
ExceptionRecorder implements MethodInvocation<T> { public void replay(Result result) { Object current = result; for (ExceptionRecorderParameter p : parameters) { current = reflectionProvider.invoke(current, p.getMethod(), p.getArgs()); } } ExceptionRecorder(Proxifier proxifier, ReflectionProvider reflectionProvider); @Override @SuppressWarnings({ "unchecked", "rawtypes" }) Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod); void replay(Result result); } | @Test public void withRootException() { mapper.record(Exception.class).forwardTo(DEFAULT_REDIRECT); mapper.findByException(new Exception()).replay(result); verify(result).forwardTo(DEFAULT_REDIRECT); }
@Test public void withNestedException() { mapper.record(IllegalStateException.class).forwardTo(DEFAULT_REDIRECT); mapper.findByException(new RuntimeException(new IllegalStateException())).replay(result); verify(result).forwardTo(DEFAULT_REDIRECT); } |
ToInstantiateInterceptorHandler implements InterceptorHandler { @Override public void execute(final InterceptorStack stack, final ControllerMethod method, final Object controllerInstance) throws InterceptionException { final Interceptor interceptor = (Interceptor) container.instanceFor(type); if (interceptor == null) { throw new InterceptionException("Unable to instantiate interceptor for " + type.getName() + ": the container returned null."); } if (interceptor.accepts(method)) { logger.debug("Invoking interceptor {}", interceptor.getClass().getSimpleName()); executeSafely(stack, method, controllerInstance, interceptor); } else { stack.next(method, controllerInstance); } } ToInstantiateInterceptorHandler(Container container, Class<?> type, ExecuteMethodExceptionHandler executeMethodExceptionHandler); @Override void execute(final InterceptorStack stack, final ControllerMethod method, final Object controllerInstance); @Override String toString(); } | @Test public void shouldComplainWhenUnableToInstantiateAnInterceptor() throws InterceptionException, IOException { exception.expect(InterceptionException.class); exception.expectMessage(containsString("Unable to instantiate interceptor for")); when(container.instanceFor(MyWeirdInterceptor.class)).thenReturn(null); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, MyWeirdInterceptor.class, new ExecuteMethodExceptionHandler()); handler.execute(null, null, null); }
@Test public void shouldInvokeInterceptorsMethodIfAbleToInstantiateIt() throws InterceptionException, IOException { final Object instance = new Object(); when(container.instanceFor(Interceptor.class)).thenReturn(interceptor); when(interceptor.accepts(method)).thenReturn(true); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, Interceptor.class, new ExecuteMethodExceptionHandler()); handler.execute(stack, method, instance); verify(interceptor).intercept(stack, method, instance); }
@Test public void shouldNotInvokeInterceptorsMethodIfInterceptorDoesntAcceptsResource() throws InterceptionException, IOException { final Object instance = new Object(); when(container.instanceFor(Interceptor.class)).thenReturn(interceptor); when(interceptor.accepts(method)).thenReturn(false); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, Interceptor.class, new ExecuteMethodExceptionHandler()); handler.execute(stack, method, instance); verify(interceptor, never()).intercept(stack, method, instance); verify(stack).next(method, instance); }
@Test public void shouldCatchValidationExceptionOfValidatedInterceptor() { MyValidatedInterceptor validatedInterceptor = new MyValidatedInterceptor(); when(container.instanceFor(MyValidatedInterceptor.class)).thenReturn(validatedInterceptor); ExecuteMethodExceptionHandler exceptionHandler = Mockito.spy(new ExecuteMethodExceptionHandler()); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, MyValidatedInterceptor.class, exceptionHandler); handler.execute(stack, method, new Object()); verify(exceptionHandler).handle(Mockito.any(ValidationException.class)); } |
DefaultConverters implements Converters { @SuppressWarnings("unchecked") @Override public <T> Converter<T> to(Class<T> clazz) { Class<? extends Converter<?>> converterType = findConverterTypeFromCache(clazz); checkState(!converterType.equals(NullConverter.class), "Unable to find converter for %s", clazz.getName()); logger.debug("found converter {} to {}", converterType.getName(), clazz.getName()); return (Converter<T>) container.instanceFor(converterType); } protected DefaultConverters(); @Inject DefaultConverters(Container container, @LRU CacheStore<Class<?>, Class<? extends Converter<?>>> cache); @Override void register(Class<? extends Converter<?>> converterClass); @SuppressWarnings("unchecked") @Override Converter<T> to(Class<T> clazz); @Override boolean existsFor(Class<?> type); @Override boolean existsTwoWayFor(Class<?> type); @Override TwoWayConverter<?> twoWayConverterFor(Class<?> type); } | @Test public void complainsIfNoConverterFound() { exception.expect(IllegalStateException.class); exception.expectMessage("Unable to find converter for " + getClass().getName()); converters.to(DefaultConvertersTest.class); } |
DefaultConverters implements Converters { @Override public void register(Class<? extends Converter<?>> converterClass) { Convert type = converterClass.getAnnotation(Convert.class); checkState(type != null, "The converter type %s should have the Convert annotation", converterClass.getName()); Class<? extends Converter<?>> currentConverter = findConverterType(type.value()); if (!currentConverter.equals(NullConverter.class)) { int priority = getConverterPriority(converterClass); int priorityCurrent = getConverterPriority(currentConverter); Convert currentType = currentConverter.getAnnotation(Convert.class); checkState(priority != priorityCurrent || !type.value().equals(currentType.value()), "Converter %s have same priority than %s", converterClass, currentConverter); if (priority > priorityCurrent) { logger.debug("Overriding converter {} with {} because have more priority", currentConverter, converterClass); classes.remove(currentConverter); classes.add(converterClass); } else { logger.debug("Converter {} not registered because have less priority than {}", converterClass, currentConverter); } } logger.debug("adding converter {} to {}", converterClass, type.value()); classes.add(converterClass); } protected DefaultConverters(); @Inject DefaultConverters(Container container, @LRU CacheStore<Class<?>, Class<? extends Converter<?>>> cache); @Override void register(Class<? extends Converter<?>> converterClass); @SuppressWarnings("unchecked") @Override Converter<T> to(Class<T> clazz); @Override boolean existsFor(Class<?> type); @Override boolean existsTwoWayFor(Class<?> type); @Override TwoWayConverter<?> twoWayConverterFor(Class<?> type); } | @Test public void convertingANonAnnotatedConverterEndsUpComplaining() { exception.expect(IllegalStateException.class); exception.expectMessage("The converter type " + WrongConverter.class.getName() + " should have the Convert annotation"); converters.register(WrongConverter.class); }
@Test public void shouldForbidConverterWithSamePriority() { exception.expect(IllegalStateException.class); exception.expectMessage(String.format("Converter %s have same priority than %s", MyThirdConverter.class, MySecondConverter.class)); converters.register(MySecondConverter.class); converters.register(MyThirdConverter.class); } |
DefaultStaticContentHandler implements StaticContentHandler { @Override public boolean requestingStaticFile(HttpServletRequest request) throws MalformedURLException { URL resourceUrl = context.getResource(uriRelativeToContextRoot(request)); return resourceUrl != null && isAFile(resourceUrl); } protected DefaultStaticContentHandler(); @Inject DefaultStaticContentHandler(ServletContext context); @Override boolean requestingStaticFile(HttpServletRequest request); @Override void deferProcessingToContainer(FilterChain filterChain, HttpServletRequest request,
HttpServletResponse response); } | @Test public void returnsTrueForRealStaticResources() throws Exception { String key = file.getAbsolutePath(); when(request.getRequestURI()).thenReturn("/contextName/" +key); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(file.toURI().toURL()); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(true))); }
@Test public void returnsTrueForRealStaticResourcesWithQueryString() throws Exception { String key = file.getAbsolutePath(); when(request.getRequestURI()).thenReturn("/contextName/" + key + "?jsesssionid=12lkjahfsd12414"); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(file.toURI().toURL()); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(true))); }
@Test public void returnsTrueForRealStaticResourcesWithJSessionId() throws Exception { String key = file.getAbsolutePath(); when(request.getRequestURI()).thenReturn("/contextName/" + key + ";jsesssionid=12lkjahfsd12414"); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(file.toURI().toURL()); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(true))); }
@Test public void returnsFalseForNonStaticResources() throws Exception { String key = "thefile.xml"; when(request.getRequestURI()).thenReturn("/contextName/" + key); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(null); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(false))); } |
DefaultInterceptorHandlerFactory implements InterceptorHandlerFactory { @Override public InterceptorHandler handlerFor(final Class<?> type) { return cachedHandlers.fetch(type, new Supplier<InterceptorHandler>() { @Override public InterceptorHandler get() { if(type.isAnnotationPresent(Intercepts.class) && !Interceptor.class.isAssignableFrom(type)){ return new AspectStyleInterceptorHandler(type, stepInvoker, container, customAcceptsExecutor, acceptsExecutor, interceptorExecutor); } return new ToInstantiateInterceptorHandler(container, type, executeMethodExceptionHandler); } }); } protected DefaultInterceptorHandlerFactory(); @Inject DefaultInterceptorHandlerFactory(Container container, StepInvoker stepInvoker,
CacheStore<Class<?>, InterceptorHandler> cachedHandlers, InterceptorAcceptsExecutor acceptsExecutor,
CustomAcceptsExecutor customAcceptsExecutor, InterceptorExecutor interceptorExecutor,
ExecuteMethodExceptionHandler executeMethodExceptionHandler); @Override InterceptorHandler handlerFor(final Class<?> type); } | @Test public void handlerForRegularInterceptorsShouldBeDynamic() throws Exception { assertThat(factory.handlerFor(RegularInterceptor.class), is(instanceOf(ToInstantiateInterceptorHandler.class))); }
@Test public void handlerForAspectStyleInterceptorsShouldBeDynamic() throws Exception { assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(instanceOf(AspectStyleInterceptorHandler.class))); }
@Test public void aspectStyleHandlersShouldBeCached() throws Exception { InterceptorHandler handler = factory.handlerFor(AspectStyleInterceptor.class); assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(sameInstance(handler))); } |
ReplicatorOutjector implements Outjector { @Override public void outjectRequestMap() { for (ValuedParameter vparameter : methodInfo.getValuedParameters()) { result.include(vparameter.getName(), vparameter.getValue()); } } protected ReplicatorOutjector(); @Inject ReplicatorOutjector(Result result, MethodInfo method); @Override void outjectRequestMap(); } | @Test public void shouldReplicateMethodParametersToNextRequest() throws Exception { methodInfo.setParameter(0, 1); methodInfo.setParameter(1, 2.0); methodInfo.setParameter(2, 3l); outjector.outjectRequestMap(); verify(result).include("first", 1); verify(result).include("second", 2.0); verify(result).include("third", 3l); } |
DefaultValidator extends AbstractValidator { @Override public Validator add(Message message) { message.setBundle(bundle); messages.add(message); return this; } protected DefaultValidator(); @Inject DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier,
ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale,
Messages messages); @Override Validator check(boolean condition, Message message); @Override Validator ensure(boolean expression, Message message); @Override Validator addIf(boolean expression, Message message); @Override Validator validate(Object object, Class<?>... groups); @Override Validator validate(String alias, Object object, Class<?>... groups); @Override Validator add(Message message); @Override Validator addAll(Collection<? extends Message> messages); @Override Validator addAll(Set<ConstraintViolation<T>> errors); @Override Validator addAll(String alias, Set<ConstraintViolation<T>> errors); @Override T onErrorUse(Class<T> view); @Override boolean hasErrors(); @Override List<Message> getErrors(); } | @Test public void outjectsTheRequestParameters() { try { validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); } catch (ValidationException e) { } verify(outjector).outjectRequestMap(); }
@Test public void addsTheErrorsOnTheResult() { try { validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); } catch (ValidationException e) { } verify(result).include(eq("errors"), argThat(is(not(empty())))); }
@Test public void forwardToCustomOnErrorPage() { try { when(logicResult.forwardTo(MyComponent.class)).thenReturn(instance); validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); fail("should stop flow"); } catch (ValidationException e) { verify(instance).logic(); } } |
Subsets and Splits