method2testcases
stringlengths
118
6.63k
### Question: PathAnnotationHandler extends AbstractResourceAnnotationHandler { public Class<?> getAnnotationType() { return Path.class; } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); static final Set<Class<? extends Annotation>> httpMethods; }### Answer: @Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), Path.class); }
### Question: PathAnnotationHandler extends AbstractResourceAnnotationHandler { public void handle(ResourceMetaData metaData, Annotation annotation, Method method) { if (! hasHttpMethod(method)) { ResourceMetaData subResource = new ResourceMetaData(method.getReturnType(), HttpUtil.concatPaths(metaData.getPath(), ((Path)annotation).value())); metaData.addSubResource(subResource); } } void handle(ResourceMetaData metaData, Annotation annotation, Method method); Class<?> getAnnotationType(); @Override void handle(ResourceMetaData metaData, Annotation annotation, Field field); static final Set<Class<? extends Annotation>> httpMethods; }### Answer: @Test public void shouldAddSubResourceLocatorToResource() throws Exception { Path path = mock(Path.class); when(path.value()).thenReturn("/sub"); handler.handle(metaData, path, DummyResource.class.getMethod("subResource")); assertTrue(! metaData.getSubResources().isEmpty()); assertEquals(metaData.getSubResources().iterator().next(), new ResourceMetaData(DummySubResource.class, "/dummy/sub")); } @Test public void shouldNotAddSubResourceMethodToResource() throws Exception { Path path = mock(Path.class); when(path.value()).thenReturn("/sub1"); handler.handle(metaData, path, DummyResource.class.getMethod("methodWithHttpMethodAnnotation")); assertTrue(metaData.getSubResources().isEmpty()); }
### Question: AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { @SuppressWarnings("rawtypes") protected User retrieveProfile(Session session) { Object profile = session.getAttribute(PRINCIPAL); if (profile == null) { return null; } Client client = getClient(session); Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class); if (type.isAssignableFrom(profile.getClass())) { return new User((UserProfile) profile); } if (profile instanceof Map) { String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile); profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type); User user = new User((UserProfile) profile); session.addAttribute(PRINCIPAL, profile); return user; } return null; } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); static final String PRINCIPAL; }### Answer: @Test public void shouldReturnNullProfileIfNotFoundInSession() { Session session = mock(Session.class); when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(null); assertNull(filter.retrieveProfile(session)); }
### Question: ResourceMetaDataBuilder extends MetaDataBuilder<ResourceMetaData, AbstractResourceAnnotationHandler> { @Override public ResourceMetaData build() { ResourceMetaData metaData = super.build(); for (ResourceMetaData subResource : metaData.getSubResources()) { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(subResource); builder.build(); } return metaData; } ResourceMetaDataBuilder(Class<?> resourceClass); ResourceMetaDataBuilder(ResourceMetaData metaData); @Override ResourceMetaData build(); }### Answer: @Test public void shouldBuildResourceMetaData() throws Exception { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(DummyResource.class); ResourceMetaData metaData = builder.build(); assertEquals(metaData.getResourceMethods().size(), 1); assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/sub1", HttpMethod.GET, DummyResource.class.getMethod("getMethod"))); } @Test public void shouldBuildSubResourceMetaData() throws Exception { ResourceMetaDataBuilder builder = new ResourceMetaDataBuilder(DummyResource.class); ResourceMetaData metaData = builder.build(); assertEquals(metaData.getSubResources().size(), 1); ResourceMetaData subResource = metaData.getSubResources().iterator().next(); assertEquals(subResource.getResourceMethods().size(), 1); assertEquals(subResource.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/sub/get", HttpMethod.GET, DummySubResource.class.getMethod("subGetMethod"))); }
### Question: CallbackFilter extends AuthenticationFilter { @Override public void filter(ContainerRequestContext request) { URI uri = URI.create(getClients().getCallbackUrl()); if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) { logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath()); return; } Session session = getSession(request, true); JaxrsWebContext context = getContext(request, session); Client client = getClient(session); if (client == null) { client = getClient(context); } if (client == null) { context.setResponseStatus(422); if (listener != null) { listener.authFailed(session); } } else { try { Credentials credentials = client.getCredentials(context); UserProfile userProfile = client.getUserProfile(credentials, context); session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName()); session.addAttribute(PRINCIPAL, userProfile); if (listener != null) { listener.authSuccess(session, userProfile); } getConfiguration().getSessionStore().save(session); context.setResponseStatus(Response.Status.OK.getStatusCode()); } catch (RequiresHttpAction e) { context.setResponseStatus(e.getCode()); if (listener != null) { listener.authFailed(session); } } } request.abortWith(context.getResponse()); } CallbackFilter(Clients clients, SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); }### Answer: @Test public void shouldNotFilterIfRequestIsNotACallback() { when(uriInfo.getPath()).thenReturn("/dummy"); filter.filter(context); verify(filter, never()).getSession(context, true); } @Test public void shouldReturnUnAcceptableIfClientNameNotSet() { Session session = mock(Session.class); Response response = mock(Response.class); JaxrsWebContext webContext = mock(JaxrsWebContext.class); when(webContext.getResponse()).thenReturn(response); doReturn(session).when(filter).getSession(context, true); doReturn(webContext).when(filter).getContext(context, session); doReturn(null).when(filter).getClient(session); filter.filter(context); verify(webContext).setResponseStatus(422); verify(context).abortWith(response); verify(listener).authFailed(session); } @Test public void shouldReturnOkIfClientNameIsSet() throws RequiresHttpAction { Session session = mock(Session.class); Response response = mock(Response.class); JaxrsWebContext webContext = mock(JaxrsWebContext.class); when(webContext.getResponse()).thenReturn(response); doReturn(session).when(filter).getSession(context, true); doReturn(webContext).when(filter).getContext(context, session); doReturn(client).when(filter).getClient(session); Credentials credentials = mock(Credentials.class); HttpProfile profile = mock(HttpProfile.class); when(client.getCredentials(webContext)).thenReturn(credentials); when(client.getUserProfile(credentials, webContext)).thenReturn(profile); filter.filter(context); verify(session).addAttribute(AuthenticationFilter.PRINCIPAL, profile); verify(session).addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "client1"); verify(sessionStore).save(session); verify(webContext).setResponseStatus(Response.Status.OK.getStatusCode()); verify(listener).authSuccess(session, profile); verify(context).abortWith(response); }
### Question: ResourceUtil { public static Filter getFilter(MultivaluedMap<String, String> queryParams) { Integer perPage = (Integer) ConvertUtils.convert(queryParams.getFirst(PER_PAGE), Integer.class); Integer pageNo = (Integer) ConvertUtils.convert(queryParams.getFirst(PAGE_NO), Integer.class); return new Filter(perPage, pageNo); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; }### Answer: @Test public void shouldCreateFilter() { MultivaluedMap<String, String> map = mock(MultivaluedMap.class); when(map.getFirst(ResourceUtil.PAGE_NO)).thenReturn("1"); when(map.getFirst(ResourceUtil.PER_PAGE)).thenReturn("10"); assertEquals(ResourceUtil.getFilter(map), new Filter(10, 1)); } @Test public void shouldCreateFilterWithSearchParams() { MultivaluedMap<String, String> map = mock(MultivaluedMap.class); when(map.getFirst(ResourceUtil.PAGE_NO)).thenReturn("1"); when(map.getFirst(ResourceUtil.PER_PAGE)).thenReturn("10"); when(map.getFirst("param1")).thenReturn("value1"); when(map.getFirst("param2")).thenReturn("value2"); List<String> params = Arrays.asList("param1", "param2"); assertEquals(ResourceUtil.getFilter(map, params), new Filter(10, 1, new Condition("param1", "value1"), new Condition("param2", "value2"))); } @Test public void shouldCreateFilterWithUnderscoreSeparatedSearchParams() { MultivaluedMap<String, String> map = mock(MultivaluedMap.class); when(map.getFirst(ResourceUtil.PAGE_NO)).thenReturn("1"); when(map.getFirst(ResourceUtil.PER_PAGE)).thenReturn("10"); when(map.getFirst("param_name1")).thenReturn("value1"); when(map.getFirst("param_name2")).thenReturn("value2"); List<String> params = Arrays.asList("param_name1", "param_name2"); assertEquals(ResourceUtil.getFilter(map, params), new Filter(10, 1, new Condition("paramName1", "value1"), new Condition("paramName2", "value2"))); }
### Question: ResourceUtil { public static <T> T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations) { MessageBodyReader<T> reader = providers.getMessageBodyReader(type, genericType, annotations, httpHeaders.getMediaType()); try { return reader.readFrom(type, genericType, annotations, httpHeaders.getMediaType(), httpHeaders.getRequestHeaders(), inputStream); } catch (Exception e) {e.printStackTrace(); throw new MinnalInstrumentationException("Failed while getting the content from the request stream", e); } } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; }### Answer: @Test public void shouldGetContentAsMap() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("key1", "value1"); byte[] bytes = new byte[10]; MediaType mediaType = mock(MediaType.class); HttpHeaders httpHeaders = mock(HttpHeaders.class); when(httpHeaders.getMediaType()).thenReturn(mediaType); MessageBodyReader reader = mock(MessageBodyReader.class); when(reader.readFrom(eq(Map.class), eq(Map.class), eq(new Annotation[]{}), eq(mediaType), isNull(MultivaluedMap.class), any(InputStream.class))).thenReturn(map); Providers providers = mock(Providers.class); when(providers.getMessageBodyReader(Map.class, Map.class, new Annotation[]{}, mediaType)).thenReturn(reader); Object content = ResourceUtil.getContent(bytes, providers, httpHeaders, Map.class); assertTrue(content instanceof Map); assertEquals(content, map); }
### Question: ResourceUtil { public static boolean isCommaSeparated(String value) { return value.contains(","); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; }### Answer: @Test public void shouldCheckIfStringIsCommaSeparated() { assertTrue(ResourceUtil.isCommaSeparated("test,test1")); assertFalse(ResourceUtil.isCommaSeparated("testtest1")); }
### Question: ResourceUtil { public static String[] getCommaSeparatedValues(String value) { return value.split(","); } static Filter getFilter(MultivaluedMap<String, String> queryParams); static Filter getFilter(MultivaluedMap<String, String> queryParams, final List<String> paramNames); static boolean isCommaSeparated(String value); static String[] getCommaSeparatedValues(String value); static T getContent(InputStream inputStream, Providers providers, HttpHeaders httpHeaders, Class<T> type, Type genericType, Annotation[] annotations); static Object getContent(byte[] raw, Providers providers, HttpHeaders httpHeaders, Class<?> type); static Object invokeAction(Object model, String actionName, List<ParameterMetaData> parameters, byte[] rawContent, Providers providers, HttpHeaders httpHeaders, Map<String, Object> values); static final String PER_PAGE; static final String PAGE_NO; static final String TOTAL; static final String COUNT; static final String DATA; }### Answer: @Test public void shouldGetCommaSeparatedValues() { assertEquals(ResourceUtil.getCommaSeparatedValues("test,test1"), new String[]{"test", "test1"}); assertEquals(ResourceUtil.getCommaSeparatedValues("testtest1"), new String[]{"testtest1"}); }
### Question: ApplicationEnhancer { protected List<Class<?>> scanClasses(Scanner<Class<?>> scanner) { final List<Class<?>> classes = new ArrayList<Class<?>>(); scanner.scan(new Listener<Class<?>>() { public void handle(Class<?> t) { classes.add(t); } }); return classes; } ApplicationEnhancer(Application application, NamingStrategy namingStrategy, String[] entityPackages, String[] resourcePackages); void enhance(); }### Answer: @Test public void shouldScanClasses() { Scanner<Class<?>> scanner = mock(Scanner.class); enhancer.scanClasses(scanner); verify(scanner).scan(any(Listener.class)); }
### Question: ResponseMetricCollector extends MessageListenerAdapter { protected String getMetricName(MessageContext context, String metricName) { String name = null; if (! Strings.isNullOrEmpty(context.getMatchedRoute())) { name = context.getMatchedRoute(); } else { name = context.getApplication().getConfiguration().getName(); } name = formatName(name); return MetricRegistry.name(name, context.getRequest().getMethod().toString(), metricName); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; }### Answer: @Test void shouldFormatMetricName(){ FullHttpResponse response = mock(FullHttpResponse.class); when(response.getStatus()).thenReturn(HttpResponseStatus.OK); when(context.getResponse()).thenReturn(response); when(context.getMatchedRoute()).thenReturn("/facilities/{id}/stations/{station_id}"); when(request.getMethod()).thenReturn(HttpMethod.GET); assertEquals("facilities.id.stations.station_id.GET.responseTime",collector.getMetricName(context, collector.RESPONSE_TIME)); }
### Question: ResponseMetricCollector extends MessageListenerAdapter { @Override public void onReceived(MessageContext context) { context.addAttribute(START_TIME, clock.getTick()); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; }### Answer: @Test public void shouldSetStartTimeOnMessageReceive() { collector.onReceived(context); verify(context).addAttribute(eq(ResponseMetricCollector.START_TIME), any(Long.class)); }
### Question: ResponseMetricCollector extends MessageListenerAdapter { @Override public void onSuccess(MessageContext context) { context.addAttribute(SUCCESSFUL, context.getResponse().getStatus().code() < 400); } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; }### Answer: @Test public void shouldSetSuccessfulOnSuccess() { FullHttpResponse response = mock(FullHttpResponse.class); when(response.getStatus()).thenReturn(HttpResponseStatus.OK); when(context.getResponse()).thenReturn(response); collector.onSuccess(context); verify(context).addAttribute(eq(ResponseMetricCollector.SUCCESSFUL), eq(Boolean.TRUE)); } @Test public void shouldSetNotSuccessfulOn4xx() { FullHttpResponse response = mock(FullHttpResponse.class); when(response.getStatus()).thenReturn(HttpResponseStatus.NOT_FOUND); when(context.getResponse()).thenReturn(response); collector.onSuccess(context); verify(context).addAttribute(eq(ResponseMetricCollector.SUCCESSFUL), eq(Boolean.FALSE)); }
### Question: ResponseMetricCollector extends MessageListenerAdapter { @Override public void onComplete(MessageContext context) { String name = null; Boolean successful = (Boolean) context.getAttribute(SUCCESSFUL); if (successful == null) { name = MetricRegistry.name(context.getApplication().getConfiguration().getName(), EXCEPTIONS); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } else { if (! successful) { name = getMetricName(context, Integer.toString(context.getResponse().getStatus().code())); MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).meter(name).mark(); } name = getMetricName(context, RESPONSE_TIME); Timer timer = MetricRegistries.getRegistry(context.getApplication().getConfiguration().getName()).timer(name); timer.update(clock.getTick() - (Long) context.getAttribute(START_TIME), TimeUnit.NANOSECONDS); } } @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onComplete(MessageContext context); static final String EXCEPTIONS; static final String RESPONSE_TIME; static final String SUCCESSFUL; static final String START_TIME; }### Answer: @Test public void shouldLogExceptionOnCompletion() { when(context.getAttribute(ResponseMetricCollector.SUCCESSFUL)).thenReturn(null); when(context.getApplication()).thenReturn(application); Meter meter = mock(Meter.class); when(metricRegistry.meter("test." + ResponseMetricCollector.EXCEPTIONS)).thenReturn(meter); collector.onComplete(context); verify(meter).mark(); }
### Question: MetricsBundle extends ContainerAdapter implements Bundle<MetricsBundleConfiguration> { @Override public void init(Container container, MetricsBundleConfiguration configuration) { this.configuration = configuration; container.registerListener(this); container.registerListener(responseMetricCollector); } @Override void init(Container container, MetricsBundleConfiguration configuration); @Override void start(); @Override void stop(); @Override int getOrder(); @Override void postMount(Application<ApplicationConfiguration> application); @Override void postUnMount(Application<ApplicationConfiguration> application); }### Answer: @Test public void shouldInitializeMetrics() { bundle.init(container, configuration); verify(container).registerListener(bundle); verify(container).registerListener(any(ResponseMetricCollector.class)); }
### Question: HttpUtil { public static String structureUrl(String url) { if (url == null || url.equals("")) { return SEPARATOR; } if (! url.startsWith(SEPARATOR)) { url = SEPARATOR + url; } if (url.endsWith(SEPARATOR)) { url = url.substring(0, url.length() - 1); } return url; } static Map<String, String> getQueryParameters(URI uri); static String decode(String value); static String encode(String value); static URI createURI(String scheme, String host, String path); static URI createURI(String uri); static Map<String, String> getCookies(String cookieHeader); static String createCookie(Map<String, String> cookies); static String structureUrl(String url); static String getRootSegment(String path); static String concatPaths(String... paths); static String deriveRelativePath(String basePath, String absolutePath); static void main(String[] args); static final String SEPARATOR; }### Answer: @Test public void shouldStructureUrlIfEmptyOrNull() { assertEquals(HttpUtil.structureUrl(null), HttpUtil.SEPARATOR); assertEquals(HttpUtil.structureUrl(""), HttpUtil.SEPARATOR); }
### Question: RoutePattern { public List<RouteElement> getElements() { List<RouteElement> elements = new ArrayList<RoutePattern.RouteElement>(); for (String element : Splitter.on("/").split(pathPattern)) { elements.add(new RouteElement(element, PLACEHOLDER_PATTERN.matcher(element).matches())); } if (elements.isEmpty()) { System.out.println(""); } elements.remove(0); return elements; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetRouteElements() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items"); assertEquals(pattern.getElements().size(), 3); assertEquals(pattern.getElements().get(0).getName(), "orders"); assertFalse(pattern.getElements().get(0).isParameter()); assertTrue(pattern.getElements().get(1).isParameter()); }
### Question: RoutePattern { public List<String> getParameterNames() { return parameterNames; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldFetchParameterNames() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); assertNotNull(pattern.getParameterNames()); assertEquals(pattern.getParameterNames(), Arrays.asList("order_id", "id")); }
### Question: RoutePattern { public boolean matches(String path) { return regex.matcher(path).matches(); } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldMatchAPathWithAlphaNumericParamsToPattern() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); assertTrue(pattern.matches("/orders/code1/order_items/1code")); } @Test public void shouldMatchAPathWithSpecialCharacterParamsToPattern() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); assertTrue(pattern.matches("/orders/order_1/order_items/order-item-1")); }
### Question: RoutePattern { public Map<String, String> match(String path) { Map<String, String> params = new HashMap<String, String>(); Matcher matcher = regex.matcher(path); if (!matcher.matches()) { return null; } for (int i = 1; i <= matcher.groupCount(); i++) { params.put(parameterNames.get(i-1), decode(matcher.group(i))); } return params; } RoutePattern(String pathPattern); Map<String, String> match(String path); boolean matches(String path); List<String> getParameterNames(); String getPathPattern(); boolean isExactMatch(); List<RouteElement> getElements(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetParameterMapForAValidPath() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); Map<String, String> params = pattern.match("/orders/1/order_items/124"); assertNotNull(params); assertEquals(params.get("order_id"), "1"); assertEquals(params.get("id"), "124"); } @Test public void shouldNotGetParameterMapForAnInvalidPath() { RoutePattern pattern = new RoutePattern("/orders/{order_id}/order_items/{id}"); Map<String, String> params = pattern.match("/orders/order_items/124"); assertNull(params); } @Test public void shouldGetEmptyParameterMapForAPathWithoutParameters() { RoutePattern pattern = new RoutePattern("/orders/1/order_items/124"); Map<String, String> params = pattern.match("/orders/1/order_items/124"); assertNotNull(params); assertTrue(params.isEmpty()); } @Test public void shouldMatchUrlEncodedString() { RoutePattern pattern = new RoutePattern("/orders/{order_id}"); Map<String, String> params = pattern.match("/orders/1234%2F1"); assertEquals(params.get("order_id"), "1234/1"); }
### Question: JerseyApplicationEventListener implements ApplicationEventListener { @Override public RequestEventListener onRequest(RequestEvent requestEvent) { return new OpenSessionInViewFilter(configuration); } JerseyApplicationEventListener(DatabaseConfiguration configuration); @Override void onEvent(ApplicationEvent event); @Override RequestEventListener onRequest(RequestEvent requestEvent); }### Answer: @Test public void shouldReturnOpenSessionInViewFilterOnRequestEvent() { DatabaseConfiguration configuration = mock(DatabaseConfiguration.class); JerseyApplicationEventListener listener = new JerseyApplicationEventListener(configuration); RequestEvent requestEvent = mock(RequestEvent.class); RequestEventListener eventListener = listener.onRequest(requestEvent); assertTrue(eventListener instanceof OpenSessionInViewFilter); assertEquals(((OpenSessionInViewFilter)eventListener).getConfiguration(), configuration); }
### Question: OpenSessionInViewFilter implements RequestEventListener { protected void requestReceived(ContainerRequest request) { JPAContext context = getContext(); context.getEntityManager(); contextCreated.set(true); } OpenSessionInViewFilter(DatabaseConfiguration configuration); @Override void onEvent(RequestEvent event); DatabaseConfiguration getConfiguration(); }### Answer: @Test public void shouldInitializeEntityManagerWhenRequestReceived() throws IOException { filter.requestReceived(request); verify(context).getEntityManager(); }
### Question: JPAPlugin implements Plugin { public void init(Application<? extends ApplicationConfiguration> application) { List<PersistenceProvider> providers = getProviders(); if (providers == null || providers.isEmpty()) { throw new MinnalException("No JPA persistence provider found"); } PersistenceProvider provider = providers.get(0); PersistenceUnitInfo info = createPersistenceUnitInfo(application.getConfiguration(), provider); factory = provider.createContainerEntityManagerFactory(info, null); JPA.instance.addPersistenceUnit(info.getPersistenceUnitName(), factory); application.addListener(new JerseyApplicationEventListener(application.getConfiguration().getDatabaseConfiguration())); } void init(Application<? extends ApplicationConfiguration> application); void destroy(); }### Answer: @Test public void shouldInitPlugin() { EntityManagerFactory factory = mock(EntityManagerFactory.class); when(provider.createContainerEntityManagerFactory(persistenceUnitInfo, null)).thenReturn(factory); plugin.init(application); assertEquals(JPA.instance.getDefaultConfig().getEntityManagerFactory(), factory); }
### Question: JpaSessionStore implements SessionStore { public Session createSession(String id) { JpaSession session = new JpaSession(id); session.persist(); return session; } Session createSession(String id); JpaSession getSession(String id); void deleteSession(String id); void save(Session session); JpaSession findSessionBy(String key, String value); }### Answer: @Test public void shouldCreateSession() { Session session = sessionStore.createSession("test123"); assertNotNull(session); assertEquals(JpaSession.one("id", "test123"), session); }
### Question: ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(ConstraintViolationException exception) { ConstraintViolationException ex = (ConstraintViolationException) exception; List<FieldError> errors = new ArrayList<FieldError>(); for (ConstraintViolation<?> violation : ex.getConstraintViolations()) { errors.add(new FieldError(Inflector.underscore(violation.getPropertyPath().toString()), violation.getMessage(), violation.getInvalidValue())); } Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", errors); return Response.status(UnprocessableEntityStatusType.INSTANCE).entity(message).build(); } @Override Response toResponse(ConstraintViolationException exception); }### Answer: @Test public void shouldHandleException() { ConstraintViolation<?> violation = mock(ConstraintViolation.class); Path path = mock(Path.class); when(path.toString()).thenReturn("dummyField"); when(violation.getPropertyPath()).thenReturn(path); when(violation.getMessage()).thenReturn("dummy message"); when(violation.getInvalidValue()).thenReturn("dummy"); ConstraintViolationException exception = new ConstraintViolationException(Sets.newHashSet(violation)); ConstraintViolationExceptionHandler handler = new ConstraintViolationExceptionHandler(); Response response = handler.toResponse(exception); Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>(); message.put("fieldErrors", Arrays.asList(new FieldError("dummy_field", "dummy message", "dummy"))); assertEquals(response.getEntity(), message); assertEquals(response.getStatus(), 422); }
### Question: ValidationPlugin implements Plugin { @Override public void init(Application<? extends ApplicationConfiguration> application) { application.addExceptionMapper(ConstraintViolationExceptionHandler.class); } @Override void init(Application<? extends ApplicationConfiguration> application); @Override void destroy(); }### Answer: @Test public void shouldAddConstraintViolationExceptionHandler() { Application application = mock(Application.class); ValidationPlugin plugin = new ValidationPlugin(); plugin.init(application); verify(application).addExceptionMapper(ConstraintViolationExceptionHandler.class); }
### Question: JpaSession extends Model implements Session { @Override public void persist() { encodeData(); super.persist(); } JpaSession(); JpaSession(String id); @Override @Id String getId(); @Transient Map<String, Object> getAttributes(); @SuppressWarnings("unchecked") T getAttribute(String name); boolean containsAttribute(String name); void removeAttribute(String name); void addAttribute(String name, Object value); Timestamp getCreatedAt(); void setCreatedAt(Timestamp createdAt); boolean hasExpired(long timeoutInSecs); String getServiceTicket(); void setServiceTicket(String serviceTicket); @Override void persist(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldCreateSession() { JpaSession session = new JpaSession("test123"); session.persist(); assertEquals(JpaSession.one("id", "test123"), session); }
### Question: MinnalSecurityContext implements SecurityContext { @Override public User getUserPrincipal() { UserProfile profile = session.getAttribute(AuthenticationFilter.PRINCIPAL); if (profile != null) { return new User(profile); } return null; } MinnalSecurityContext(Authorizer authorizer, Session session); @Override User getUserPrincipal(); @Override boolean isUserInRole(String role); @Override boolean isSecure(); @Override String getAuthenticationScheme(); }### Answer: @Test public void shouldGetPrincipal() { HttpProfile profile = mock(HttpProfile.class); when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(profile); User user = context.getUserPrincipal(); assertEquals(user.getProfile(), profile); } @Test public void shouldReturnNullIfPrincipalNotFound() { when(session.getAttribute(AuthenticationFilter.PRINCIPAL)).thenReturn(null); User user = context.getUserPrincipal(); assertNull(user); }
### Question: SimpleRolePermissionMapper implements RolePermissionMapper { @Override public List<String> getPermissions(String role) { if (permissions == null) { loadPermissions(); } return permissions.get(role); } SimpleRolePermissionMapper(String mappingFile); SimpleRolePermissionMapper(); @Override List<String> getPermissions(String role); String getMappingFile(); void setMappingFile(String mappingFile); }### Answer: @Test public void shouldLoadRolePermissionsFromDefaultProperties() { String role = "role1"; assertEquals(mapper.getPermissions(role).size(), 2); assertEquals(mapper.getPermissions(role), Lists.newArrayList("permission1", "permission2")); } @Test public void shouldLoadUserRolesFromCustomPropertiesFile() { mapper = new SimpleRolePermissionMapper("role_permissions.properties"); String role = "role1"; assertEquals(mapper.getPermissions(role).size(), 2); assertEquals(mapper.getPermissions(role), Lists.newArrayList("permission1", "permission2")); } @Test public void shouldReturnEmptyListForRoleWithoutPermission() { String role = "role3"; assertEquals(mapper.getPermissions(role).size(), 0); }
### Question: SimpleUserRoleMapper implements UserRoleMapper { @Override public List<String> getRoles(User user) { if (roles == null) { loadRoles(); } return roles.get(user.getName()); } SimpleUserRoleMapper(String mappingFile); SimpleUserRoleMapper(); @Override List<String> getRoles(User user); String getMappingFile(); void setMappingFile(String mappingFile); }### Answer: @Test public void shouldLoadUserRolesFromDefaultProperties() { assertEquals(mapper.getRoles(user).size(), 2); assertEquals(mapper.getRoles(user), Lists.newArrayList("role1", "role2")); } @Test public void shouldLoadUserRolesFromCustomPropertiesFile() { mapper = new SimpleUserRoleMapper("user_roles.properties"); assertEquals(mapper.getRoles(user).size(), 2); assertEquals(mapper.getRoles(user), Lists.newArrayList("role1", "role2")); } @Test public void shouldReturnEmptyListForUserWithoutRole() { UserProfile profile = new UserProfile(); profile.setId("user3"); User user = new User(profile); assertEquals(mapper.getRoles(user).size(), 0); }
### Question: SimpleAuthorizer implements Authorizer { @Override public boolean authorize(User user, List<String> permissions) { if (user.getRoles() == null || user.getRoles().isEmpty()) { List<String> roles = roleMapper.getRoles(user); if (roles != null) { user.setRoles(roles); } } if (user.getPermissions() == null || user.getPermissions().isEmpty()) { List<String> perms = new ArrayList<String>(); if (user.getRoles() != null) { for (String role : user.getRoles()) { List<String> rolePerms = permissionMapper.getPermissions(role); if (rolePerms != null) { perms.addAll(rolePerms); } } } user.setPermissions(perms); } return user.hasPermissions(permissions); } SimpleAuthorizer(RolePermissionMapper permissionMapper, UserRoleMapper roleMapper); SimpleAuthorizer(); @Override boolean authorize(User user, List<String> permissions); RolePermissionMapper getPermissionMapper(); void setPermissionMapper(RolePermissionMapper permissionMapper); UserRoleMapper getRoleMapper(); void setRoleMapper(UserRoleMapper roleMapper); @Override boolean authorize(User user, String permission); }### Answer: @Test public void shouldAuthorizeIfAllPermissionsMatch() { assertTrue(authorizer.authorize(user, user.getPermissions())); } @Test public void shouldAuthorizeIfPermissionMatch() { user.setPermissions(Arrays.asList("permission1")); assertTrue(authorizer.authorize(user, "permission1")); } @Test public void shouldNotAuthorizeIfAllPermissionsDontMatch() { assertFalse(authorizer.authorize(user, Arrays.asList("permission1", "permission3"))); } @Test public void shouldNotAuthorizeIfPermissionDontMatch() { assertFalse(authorizer.authorize(user, "permission3")); } @Test public void shouldGetRolesFromPropertiesIfNotPopulatedAlready() { user.setPermissions(Lists.newArrayList("permission3", "permission1")); authorizer.authorize(user, Lists.newArrayList("permission3")); verify(userRoleMapper).getRoles(user); } @Test public void shouldGetPermissionsFromPropertiesIfNotPopulatedAlready() { user.setRoles(Lists.newArrayList("role2")); authorizer.authorize(user, Lists.newArrayList("permission3")); verify(rolePermissionMapper).getPermissions("role2"); }
### Question: SecurityPlugin implements Plugin { @Override public void init(Application<? extends ApplicationConfiguration> application) { ApplicationConfiguration applicationConfiguration = application.getConfiguration(); if (! (applicationConfiguration instanceof SecurityAware)) { return; } SecurityConfiguration configuration = ((SecurityAware) applicationConfiguration).getSecurityConfiguration(); clients.init(); CallbackFilter callbackFilter = new CallbackFilter(clients, configuration); callbackFilter.registerListener(listener); application.addFilter(callbackFilter); application.addFilter(new AuthenticationFilter(clients, configuration)); application.addFilter(new SecurityContextFilter(configuration)); application.getResourceConfig().register(RolesAllowedDynamicFeature.class); } SecurityPlugin(String callbackUrl, Client... clients); SecurityPlugin(String callbackUrl, AuthenticationListener listener, Client... clients); SecurityPlugin(Clients clients); @Override void init(Application<? extends ApplicationConfiguration> application); @Override void destroy(); }### Answer: @Test public void shouldInitPlugin() { Application application = mock(Application.class); SecureApplicationConfiguration securityAware = mock(SecureApplicationConfiguration.class); ResourceConfig resourceConfig = mock(ResourceConfig.class); when(application.getConfiguration()).thenReturn(securityAware); when(application.getResourceConfig()).thenReturn(resourceConfig); plugin.init(application); verify(application, atLeast(1)).addFilter(any(SecurityContextFilter.class)); verify(application, atLeast(1)).addFilter(any(AuthenticationFilter.class)); verify(application, atLeast(1)).addFilter(any(CallbackFilter.class)); verify(resourceConfig).register(RolesAllowedDynamicFeature.class); }
### Question: JaxrsWebContext implements WebContext { @Override public Map<String, String[]> getRequestParameters() { Set<Entry<String, List<String>>> entries = request.getUriInfo().getQueryParameters().entrySet(); Map<String, String[]> params = new HashMap<String, String[]>(); for (Entry<String, List<String>> entry : entries) { params.put(entry.getKey(), entry.getValue().toArray(new String[0])); } return params; } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetRequestParameters() { MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>(); params.addAll("key1", Lists.newArrayList("value1", "value2")); params.add("key2", "value3"); UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(params); when(request.getUriInfo()).thenReturn(uriInfo); Map<String, String[]> reqParams = context.getRequestParameters(); assertEquals(reqParams.get("key1"), new String[]{"value1", "value2"}); assertEquals(reqParams.get("key2"), new String[]{"value3"}); }
### Question: JaxrsWebContext implements WebContext { @Override public String getRequestParameter(String name) { return request.getUriInfo().getQueryParameters().getFirst(name); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetRequestParameter() { MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>(); params.addAll("key1", Lists.newArrayList("value1", "value2")); params.add("key2", "value3"); UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(params); when(request.getUriInfo()).thenReturn(uriInfo); assertEquals(context.getRequestParameter("key1"), "value1"); }
### Question: JaxrsWebContext implements WebContext { @Override public String getRequestHeader(String name) { return request.getHeaderString(name); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetRequestHeader() { when(request.getHeaderString("header1")).thenReturn("value1"); assertEquals(context.getRequestHeader("header1"), "value1"); }
### Question: JaxrsWebContext implements WebContext { @Override public void setSessionAttribute(String name, Object value) { session.addAttribute(name, value); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldSetSessionAttribute() { context.setSessionAttribute("key1", "value1"); verify(session).addAttribute("key1", "value1"); }
### Question: JaxrsWebContext implements WebContext { @Override public Object getSessionAttribute(String name) { return session.getAttribute(name); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetSessionAttribute() { when(session.getAttribute("key1")).thenReturn("value1"); assertEquals(context.getSessionAttribute("key1"), "value1"); }
### Question: JaxrsWebContext implements WebContext { @Override public String getRequestMethod() { return request.getMethod(); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetRequestMethod() { when(request.getMethod()).thenReturn("GET"); assertEquals(context.getRequestMethod(), "GET"); }
### Question: JaxrsWebContext implements WebContext { @Override public void writeResponseContent(String content) { try { context.getEntityStream().write(content.getBytes(Charsets.UTF_8)); } catch (IOException e) { logger.error("Failed while writing the response content", e); throw new MinnalException("Failed while writing the response content", e); } } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldWriteResponseContent() throws IOException { OutputStream os = mock(OutputStream.class); outboundMessageContext.setEntityStream(os); context.writeResponseContent("test"); verify(os).write("test".getBytes()); }
### Question: SecurityContextFilter extends AbstractSecurityFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext request) { Session session = getSession(request, true); MinnalSecurityContext context = new MinnalSecurityContext(getConfiguration().getAuthorizer(), session); request.setSecurityContext(context); } SecurityContextFilter(SecurityConfiguration configuration); @Override void filter(ContainerRequestContext request); }### Answer: @Test public void shouldSetSecurityContextToTheRequest() { Session session = mock(Session.class); doReturn(session).when(filter).getSession(context, true); filter.filter(context); verify(context).setSecurityContext(any(MinnalSecurityContext.class)); }
### Question: JaxrsWebContext implements WebContext { public String getServerName() { return request.getUriInfo().getRequestUri().getHost(); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetServerName() { UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getRequestUri()).thenReturn(URI.create("http: when(request.getUriInfo()).thenReturn(uriInfo); assertEquals(context.getServerName(), "localhost"); }
### Question: JaxrsWebContext implements WebContext { @Override public String getScheme() { return request.getUriInfo().getRequestUri().getScheme(); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetScheme() { UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getRequestUri()).thenReturn(URI.create("https: when(request.getUriInfo()).thenReturn(uriInfo); assertEquals(context.getScheme(), "https"); }
### Question: JaxrsWebContext implements WebContext { @Override public int getServerPort() { return request.getUriInfo().getRequestUri().getPort(); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetPort() { UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getRequestUri()).thenReturn(URI.create("https: when(request.getUriInfo()).thenReturn(uriInfo); assertEquals(context.getServerPort(), 8080); }
### Question: JaxrsWebContext implements WebContext { @Override public String getFullRequestURL() { return request.getUriInfo().getRequestUri().toASCIIString(); } JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session); ContainerRequestContext getRequest(); Response getResponse(); Session getSession(); @Override String getRequestParameter(String name); @Override Map<String, String[]> getRequestParameters(); @Override String getRequestHeader(String name); @Override void setSessionAttribute(String name, Object value); @Override Object getSessionAttribute(String name); @Override String getRequestMethod(); @Override void writeResponseContent(String content); @Override void setResponseStatus(final int code); @Override void setResponseHeader(String name, String value); String getServerName(); @Override int getServerPort(); @Override String getScheme(); @Override String getFullRequestURL(); }### Answer: @Test public void shouldGetFullRequestUrl() { UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getRequestUri()).thenReturn(URI.create("https: when(request.getUriInfo()).thenReturn(uriInfo); assertEquals(context.getFullRequestURL(), "https: }
### Question: ApiPlugin implements Plugin { @Override public void init(Application<? extends ApplicationConfiguration> application) { application.addProvider(new ApiDeclarationProvider()); application.addProvider(new ResourceListingProvider()); application.addResource(ApiListingResourceJSON.class); if (enableCors) { application.addFilter(CorsFilter.class); } } ApiPlugin(boolean enableCors); @Override void init(Application<? extends ApplicationConfiguration> application); @Override void destroy(); }### Answer: @Test public void shouldAddCorsFilterIfEnabled() { apiPlugin = new ApiPlugin(true); apiPlugin.init(application); verify(application).addFilter(CorsFilter.class); } @Test public void shouldNotAddCorsFilterIfNotEnabled() { apiPlugin = new ApiPlugin(false); apiPlugin.init(application); verify(application, never()).addFilter(CorsFilter.class); } @Test public void shouldAddProvidersOnInit() { apiPlugin = new ApiPlugin(false); apiPlugin.init(application); verify(application, atLeastOnce()).addProvider(any(ApiDeclarationProvider.class)); verify(application, atLeastOnce()).addProvider(any(ResourceListingProvider.class)); } @Test public void shouldAddResource() { apiPlugin = new ApiPlugin(false); apiPlugin.init(application); verify(application).addResource(ApiListingResourceJSON.class); }
### Question: CorsFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { responseContext.getHeaders().add("Access-Control-Allow-Origin", "*"); responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); String reqHead = requestContext.getHeaderString("Access-Control-Request-Headers"); if (! Strings.isNullOrEmpty(reqHead)) { responseContext.getHeaders().add("Access-Control-Allow-Headers", reqHead); } } @Override void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext); }### Answer: @Test public void shouldAddCorsHeaders() { CorsFilter filter = new CorsFilter(); ContainerRequestContext reqContext = mock(ContainerRequestContext.class); ContainerResponseContext resContext = mock(ContainerResponseContext.class); MultivaluedMap<String, Object> headers = mock(MultivaluedMap.class); when(resContext.getHeaders()).thenReturn(headers); filter.filter(reqContext, resContext); verify(headers).add("Access-Control-Allow-Origin", "*"); verify(headers).add("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); } @Test public void shouldCopyAccessControleHeadersToResponse() { CorsFilter filter = new CorsFilter(); ContainerRequestContext reqContext = mock(ContainerRequestContext.class); when(reqContext.getHeaderString("Access-Control-Request-Headers")).thenReturn("*"); ContainerResponseContext resContext = mock(ContainerResponseContext.class); MultivaluedMap<String, Object> resHeaders = mock(MultivaluedMap.class); when(resContext.getHeaders()).thenReturn(resHeaders); filter.filter(reqContext, resContext); verify(resHeaders).add("Access-Control-Allow-Headers", "*"); }
### Question: AuthenticationFilter extends AbstractSecurityFilter implements ContainerRequestFilter, ContainerResponseFilter { protected boolean isWhiteListed(ContainerRequestContext request) { for (String url : getConfiguration().getWhiteListedUrls()) { if (request.getUriInfo().getPath().startsWith(url)) { return true; } } return false; } AuthenticationFilter(Clients clients, SecurityConfiguration configuration); Clients getClients(); @Override void filter(ContainerRequestContext request); @Override void filter(ContainerRequestContext request, ContainerResponseContext response); void registerListener(AuthenticationListener listener); static final String PRINCIPAL; }### Answer: @Test public void shouldReturnTrueIfWhiteListedUrl() { when(configuration.getWhiteListedUrls()).thenReturn(Lists.newArrayList("/dummy", "/dummy1")); assertTrue(filter.isWhiteListed(context)); } @Test public void shouldReturnFalseIfWhiteNotListedUrl() { when(configuration.getWhiteListedUrls()).thenReturn(Lists.newArrayList("/dummy2", "/dummy1")); assertFalse(filter.isWhiteListed(context)); } @Test public void shouldReturnTrueForWhiteListedUrlWithParams() { when(configuration.getWhiteListedUrls()).thenReturn(Lists.newArrayList("/dummy", "/dummy1")); when(uriInfo.getPath()).thenReturn("/dummy?key=value"); assertTrue(filter.isWhiteListed(context)); }
### Question: MinnalApiSpecFilter extends JaxrsFilter { @Override public boolean isParamAllowed(Parameter parameter, Operation operation, ApiDescription api, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { if (parameter.paramAccess().nonEmpty()) { return !parameter.paramAccess().get().equals("internal"); } return super.isParamAllowed(parameter, operation, api, params, cookies, headers); } @Override boolean isParamAllowed(Parameter parameter, Operation operation, ApiDescription api, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers); }### Answer: @Test public void shouldReturnFalseIfParamAccessIsInternal() { MinnalApiSpecFilter filter = spy(new MinnalApiSpecFilter()); Parameter parameter = mock(Parameter.class); when(parameter.paramAccess()).thenReturn(Option.apply("internal")); assertFalse(filter.isParamAllowed(parameter, null, null, null, null, null)); } @Test public void shouldReturnTrueIfParamAccessIsNotInternal() { MinnalApiSpecFilter filter = spy(new MinnalApiSpecFilter()); Parameter parameter = mock(Parameter.class); when(parameter.paramAccess()).thenReturn(Option.apply("internal1")); assertTrue(filter.isParamAllowed(parameter, null, null, null, null, null)); } @Test public void shouldReturnTrueIfParamAccessIsNotSet() { MinnalApiSpecFilter filter = spy(new MinnalApiSpecFilter()); Parameter parameter = mock(Parameter.class); when(parameter.paramAccess()).thenReturn(Option.<String>empty()); assertTrue(filter.isParamAllowed(parameter, null, null, null, null, null)); }
### Question: ExcludeAnnotationsConvertor extends SwaggerSchemaConverter { protected void handleExcludedAnnotations(Class<?> clazz, Field field, Option<Model> model) { for (Class<? extends Annotation> annotationClass : excludeAnnotations) { if (ClassUtils.hasAnnotation(clazz, field.getName(), annotationClass)) { model.get().properties().remove(field.getName()); } } } ExcludeAnnotationsConvertor(List<Class<? extends Annotation>> excludeAnnotations); @Override Option<Model> read(Class<?> cls, Map<String, String> typeMap); List<Class<? extends Annotation>> getExcludeAnnotations(); }### Answer: @Test public void shouldRemoveExcludedFieldAnnotationsFromModel() throws NoSuchFieldException, SecurityException { convertor.handleExcludedAnnotations(DummyModel.class, DummyModel.class.getDeclaredField("field1"), Option.apply(model)); verify(properties).remove("field1"); } @Test public void shouldRemoveExcludedMethodAnnotationsFromModel() throws NoSuchFieldException, SecurityException { convertor.handleExcludedAnnotations(DummyModel.class, DummyModel.class.getDeclaredField("field2"), Option.apply(model)); verify(properties).remove("field2"); } @Test public void shouldNotRemoveFieldsWithoutAnnotations() throws NoSuchFieldException, SecurityException { convertor.handleExcludedAnnotations(DummyModel.class, DummyModel.class.getDeclaredField("field3"), Option.apply(model)); verify(properties, never()).remove("field3"); }
### Question: ApiBundle extends ContainerAdapter implements Bundle<ApiBundleConfiguration> { @Override public void init(Container container, ApiBundleConfiguration configuration) { this.configuration = configuration; container.registerListener(this); SwaggerConfig config = ConfigFactory.config(); config.setApiVersion("1.0.1"); for (ConnectorConfiguration connector : container.getConfiguration().getServerConfiguration().getConnectorConfigurations()) { if (connector.getScheme() == Scheme.http) { config.setBasePath(connector.getScheme().toString() + ": break; } } ScannerFactory.setScanner(new DefaultJaxrsScanner()); ClassReaders.setReader(new DefaultJaxrsApiReader()); FilterFactory.setFilter(new MinnalApiSpecFilter()); ModelConverters.addConverter(getExcludeAnnotationsConvertor(), true); ModelConverters.addConverter(getOverrideConverter(), true); } @Override void init(Container container, ApiBundleConfiguration configuration); @Override void start(); @Override void stop(); @Override void preMount(Application<ApplicationConfiguration> application); @Override int getOrder(); }### Answer: @Test public void shouldRegisterContainerListenerOnInit() { apiBundle.init(container, bundleConfiguration); verify(container).registerListener(apiBundle); }
### Question: ApiBundle extends ContainerAdapter implements Bundle<ApiBundleConfiguration> { protected String getHostName() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { return "localhost"; } } @Override void init(Container container, ApiBundleConfiguration configuration); @Override void start(); @Override void stop(); @Override void preMount(Application<ApplicationConfiguration> application); @Override int getOrder(); }### Answer: @Test public void shouldGetLocalHost() throws UnknownHostException { assertEquals(apiBundle.getHostName(), InetAddress.getLocalHost().getHostAddress()); }
### Question: ApplicationMapping { public String getBasePath() { return basePath; } ApplicationMapping(String basePath); void addApplication(Application<ApplicationConfiguration> application); Application<ApplicationConfiguration> removeApplication(String mountPath); Application<ApplicationConfiguration> resolve(HttpRequest request); Collection<Application<ApplicationConfiguration>> getApplications(); String getBasePath(); }### Answer: @Test public void shouldStructureBasePath() { ApplicationMapping mapping = new ApplicationMapping(""); assertEquals(mapping.getBasePath(), "/"); mapping = new ApplicationMapping("test"); assertEquals(mapping.getBasePath(), "/test"); mapping = new ApplicationMapping("test/"); assertEquals(mapping.getBasePath(), "/test"); mapping = new ApplicationMapping("test/test1/"); assertEquals(mapping.getBasePath(), "/test/test1"); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public int getTotalConnections() { try { return dataSource.getNumConnectionsAllUsers(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetTotalConnections() throws SQLException { when(dataSource.getNumConnectionsAllUsers()).thenReturn(10); assertEquals(statistics.getTotalConnections(), 10); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public int getActiveConnections() { try { return dataSource.getNumBusyConnectionsAllUsers(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetActiveConnections() throws SQLException { when(dataSource.getNumBusyConnectionsAllUsers()).thenReturn(10); assertEquals(statistics.getActiveConnections(), 10); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public int getIdleConnections() { try { return dataSource.getNumIdleConnectionsAllUsers(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetIdleConnections() throws SQLException { when(dataSource.getNumIdleConnectionsAllUsers()).thenReturn(10); assertEquals(statistics.getIdleConnections(), 10); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public int getAwaitingCheckout() { try { return dataSource.getNumThreadsAwaitingCheckoutDefaultUser(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetAwaitingCheckout() throws SQLException { when(dataSource.getNumThreadsAwaitingCheckoutDefaultUser()).thenReturn(10); assertEquals(statistics.getAwaitingCheckout(), 10); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public int getCachedStatements() { try { return dataSource.getStatementCacheNumStatementsAllUsers(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetCachedStatements() throws SQLException { when(dataSource.getStatementCacheNumStatementsAllUsers()).thenReturn(10); assertEquals(statistics.getCachedStatements(), 10); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public long getFailedCheckins() { try { return dataSource.getNumFailedCheckinsDefaultUser(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetFailedCheckins() throws SQLException { when(dataSource.getNumFailedCheckinsDefaultUser()).thenReturn(10L); assertEquals(statistics.getFailedCheckins(), 10L); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public long getFailedCheckouts() { try { return dataSource.getNumFailedCheckoutsDefaultUser(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetFailedCheckouts() throws SQLException { when(dataSource.getNumFailedCheckoutsDefaultUser()).thenReturn(10L); assertEquals(statistics.getFailedCheckouts(), 10L); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public long getFailedIdleTests() { try { return dataSource.getNumFailedIdleTestsDefaultUser(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetFailedIdleTests() throws SQLException { when(dataSource.getNumFailedIdleTestsDefaultUser()).thenReturn(10L); assertEquals(statistics.getFailedIdleTests(), 10L); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public long getStartTime() { try { return dataSource.getStartTimeMillisDefaultUser(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetStartTime() throws SQLException { when(dataSource.getStartTimeMillisDefaultUser()).thenReturn(10010101001L); assertEquals(statistics.getStartTime(), 10010101001L); }
### Question: C3P0DataSourceStatistics implements DataSourceStatistics { @Override public long getUpTime() { try { return dataSource.getUpTimeMillisDefaultUser(); } catch (SQLException e) { throw new MinnalException(e); } } C3P0DataSourceStatistics(PooledDataSource dataSource); @Override int getActiveConnections(); @Override int getIdleConnections(); @Override long getFailedCheckins(); @Override long getFailedCheckouts(); @Override int getAwaitingCheckout(); @Override long getFailedIdleTests(); @Override int getTotalConnections(); @Override int getCachedStatements(); @Override long getStartTime(); @Override long getUpTime(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldGetUpTime() throws SQLException { when(dataSource.getUpTimeMillisDefaultUser()).thenReturn(10010101001L); assertEquals(statistics.getUpTime(), 10010101001L); }
### Question: C3P0DataSourceProvider implements DataSourceProvider { protected PooledDataSource createDataSource() { logger.info("Creating the data source with the configuration {}", configuration); if (configuration == null) { logger.error("Database configuration is not set"); throw new MinnalException("Database configuration is not set"); } ComboPooledDataSource dataSource = new ComboPooledDataSource(); try { Class.forName(configuration.getDriverClass()); dataSource.setJdbcUrl(configuration.getUrl()); dataSource.setUser(configuration.getUsername()); dataSource.setPassword(configuration.getPassword()); dataSource.setIdleConnectionTestPeriod(configuration.getIdleConnectionTestPeriod()); dataSource.setInitialPoolSize(configuration.getMinSize()); dataSource.setMaxPoolSize(configuration.getMaxSize()); } catch (Exception e) { logger.error("Failed while creating the data source", e); throw new MinnalException("Failed while configuring the data source", e); } return dataSource; } C3P0DataSourceProvider(); C3P0DataSourceProvider(DatabaseConfiguration configuration); @Override DataSource getDataSource(); @Override void close(); @Override DataSourceStatistics getStatistics(); DatabaseConfiguration getConfiguration(); void setConfiguration(DatabaseConfiguration configuration); }### Answer: @Test public void shouldCreateDataSource() { assertNotNull(provider.createDataSource()); }
### Question: Router { public void route(MessageContext context) { logger.trace("Routing the context {}", context); Application<ApplicationConfiguration> application = applicationMapping.resolve(context.getRequest()); if (application == null) { throw new NotFoundException("Request path not found"); } context.setApplication(application); if (listener != null) { listener.onApplicationResolved(context); } ApplicationHandler handler = getApplicationHandler(application); ContainerRequest containerRequest = createContainerRequest(context); ByteBuf buffer = Unpooled.buffer(); ContainerResponse response = null; try { response = Futures.getUnchecked(handler.apply(containerRequest, new ByteBufOutputStream(buffer))); } catch (Exception e) { logger.debug("Failed while handling the request - " + containerRequest, e); response = new ContainerResponse(containerRequest, Response.serverError().build()); } UriInfo uriInfo = containerRequest.getUriInfo(); List<String> matchedUris = uriInfo.getMatchedURIs(); if (matchedUris != null && ! matchedUris.isEmpty()) { context.setMatchedRoute(matchedUris.get(0)); } FullHttpResponse httpResponse = createHttpResponse(context, response, buffer); context.setResponse(httpResponse); } Router(ApplicationMapping applicationMapping); void route(MessageContext context); }### Answer: @Test public void shouldNotSetResponseCodeIfAlreadySet() { when(response.getStatus()).thenReturn(HttpResponseStatus.NOT_FOUND); router.route(context); verify(response, never()).setStatus(any(HttpResponseStatus.class)); } @Test public void shouldPopulateContextWithApplication() { router.route(context); verify(context).setApplication(application); }
### Question: Router { protected ContainerRequest createContainerRequest(MessageContext context) { Application<ApplicationConfiguration> application = context.getApplication(); FullHttpRequest httpRequest = context.getRequest(); URI baseUri = URI.create(context.getBaseUri().resolve(application.getPath()) + "/"); URI requestUri = HttpUtil.createURI(httpRequest.getUri()); ContainerRequest containerRequest = new ContainerRequest(baseUri, requestUri, httpRequest.getMethod().name(), null, new MapPropertiesDelegate()); containerRequest.setEntityStream(new ByteBufInputStream(httpRequest.content())); for (Map.Entry<String, String> headerEntry : httpRequest.headers()) { containerRequest.getHeaders().add(headerEntry.getKey(), headerEntry.getValue()); } return containerRequest; } Router(ApplicationMapping applicationMapping); void route(MessageContext context); }### Answer: @Test public void shouldCreateContainerRequestFromHttpRequestWithBaseAndRequestUri() { ContainerRequest containerRequest = router.createContainerRequest(context); assertEquals(containerRequest.getBaseUri(), URI.create("http: assertEquals(containerRequest.getRequestUri(), URI.create("/test")); } @Test public void shouldCreateContainerRequestFromHttpRequestWithHeaders() { request.headers().add("header1", "value1"); request.headers().add("header2", Arrays.asList("value2", "value3")); ContainerRequest containerRequest = router.createContainerRequest(context); assertEquals(containerRequest.getHeaders().getFirst("header1"), "value1"); assertEquals(containerRequest.getHeaders().get("header2"), Arrays.asList("value2", "value3")); } @Test public void shouldCreateContainerRequestFromHttpRequestWithContent() { ByteBuf content = mock(ByteBuf.class); when(request.content()).thenReturn(content); ContainerRequest containerRequest = router.createContainerRequest(context); assertTrue(containerRequest.getEntityStream() instanceof ByteBufInputStream); }
### Question: Router { protected FullHttpResponse createHttpResponse(MessageContext context, ContainerResponse containerResponse, ByteBuf buffer) { FullHttpRequest httpRequest = context.getRequest(); DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.valueOf(containerResponse.getStatus()), buffer); int length = containerResponse.getLength(); if (length == -1 && containerResponse.getEntity() instanceof String) { final String entity = (String) containerResponse.getEntity(); final byte[] encodedBytes = entity.getBytes(Charset.forName("UTF-8")); length = encodedBytes.length; } if (! containerResponse.getHeaders().containsKey(HttpHeaders.Names.CONTENT_LENGTH)) { HttpHeaders.setContentLength(httpResponse, length); logger.trace("Writing response status and headers {}, length {}", containerResponse, containerResponse.getLength()); } for (Map.Entry<String, List<Object>> headerEntry : containerResponse.getHeaders().entrySet()) { HttpHeaders.addHeader(httpResponse, headerEntry.getKey(), Joiner.on(", ").join(headerEntry.getValue())); } return httpResponse; } Router(ApplicationMapping applicationMapping); void route(MessageContext context); }### Answer: @Test public void shouldCreateHttpResponseFromContainerResponseWithStatus() { MultivaluedMap<String, Object> headers = mock(MultivaluedMap.class); ContainerResponse response = mock(ContainerResponse.class); when(response.getHeaders()).thenReturn(headers); when(response.getStatus()).thenReturn(200); ByteBuf buffer = mock(ByteBuf.class); FullHttpResponse httpResponse = router.createHttpResponse(context, response, buffer); assertEquals(httpResponse.getStatus(), HttpResponseStatus.OK); } @Test public void shouldCreateHttpResponseFromContainerResponseWithContent() { MultivaluedMap<String, Object> headers = mock(MultivaluedMap.class); ContainerResponse response = mock(ContainerResponse.class); when(response.getHeaders()).thenReturn(headers); when(response.getStatus()).thenReturn(200); when(response.getLength()).thenReturn(10); when(response.getEntityStream()).thenReturn(mock(OutputStream.class)); ByteBuf buffer = mock(ByteBuf.class); FullHttpResponse httpResponse = router.createHttpResponse(context, response, buffer); assertTrue(httpResponse.content() instanceof ByteBuf); assertEquals(HttpHeaders.getContentLength(httpResponse), 10); } @Test public void shouldCreateHttpResponseFromContainerResponseWithHeaders() { MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>(); headers.add("header1", "value1"); headers.addAll("header2", Arrays.<Object>asList("value2", "value3")); ContainerResponse response = mock(ContainerResponse.class); when(response.getHeaders()).thenReturn(headers); when(response.getStatus()).thenReturn(200); ByteBuf buffer = mock(ByteBuf.class); FullHttpResponse httpResponse = router.createHttpResponse(context, response, buffer); assertEquals(HttpHeaders.getHeader(httpResponse, "header1"), "value1"); assertEquals(HttpHeaders.getHeader(httpResponse, "header2"), "value2, value3"); }
### Question: ContainerMessageObserver implements RouterListener, ConnectorListener { @Override public void onReceived(MessageContext context) { for (final MessageListener listener : messageListeners) { invoke(new ListenerInvoker(){ @Override public void invoke(MessageContext context) { listener.onReceived(context); } }, context); } } void registerListener(MessageListener listener); @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onError(MessageContext context); @Override void onComplete(MessageContext context); @Override void onApplicationResolved(MessageContext context); @Override void onError(Throwable cause); }### Answer: @Test public void shouldInvokeListenerOnReceived() { observer.onReceived(context); verify(listener).onReceived(context); }
### Question: ContainerMessageObserver implements RouterListener, ConnectorListener { @Override public void onComplete(MessageContext context) { for (final MessageListener listener : messageListeners) { invoke(new ListenerInvoker(){ @Override public void invoke(MessageContext context) { listener.onComplete(context); } }, context); } } void registerListener(MessageListener listener); @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onError(MessageContext context); @Override void onComplete(MessageContext context); @Override void onApplicationResolved(MessageContext context); @Override void onError(Throwable cause); }### Answer: @Test public void shouldInvokeListenerOnComplete() { observer.onComplete(context); verify(listener).onComplete(context); }
### Question: ContainerMessageObserver implements RouterListener, ConnectorListener { @Override public void onError(MessageContext context) { for (final MessageListener listener : messageListeners) { invoke(new ListenerInvoker(){ @Override public void invoke(MessageContext context) { listener.onError(context); } }, context); } } void registerListener(MessageListener listener); @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onError(MessageContext context); @Override void onComplete(MessageContext context); @Override void onApplicationResolved(MessageContext context); @Override void onError(Throwable cause); }### Answer: @Test public void shouldInvokeListenerOnError() { observer.onError(context); verify(listener).onError(context); }
### Question: ContainerMessageObserver implements RouterListener, ConnectorListener { @Override public void onSuccess(MessageContext context) { for (final MessageListener listener : messageListeners) { invoke(new ListenerInvoker(){ @Override public void invoke(MessageContext context) { listener.onSuccess(context); } }, context); } } void registerListener(MessageListener listener); @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onError(MessageContext context); @Override void onComplete(MessageContext context); @Override void onApplicationResolved(MessageContext context); @Override void onError(Throwable cause); }### Answer: @Test public void shouldInvokeListenerOnSuccess() { observer.onSuccess(context); verify(listener).onSuccess(context); }
### Question: ContainerMessageObserver implements RouterListener, ConnectorListener { @Override public void onApplicationResolved(MessageContext context) { ApplicationContext.instance().setApplicationConfiguration(context.getApplication().getConfiguration()); for (final MessageListener listener : messageListeners) { invoke(new ListenerInvoker(){ @Override public void invoke(MessageContext context) { listener.onApplicationResolved(context); } }, context); } } void registerListener(MessageListener listener); @Override void onReceived(MessageContext context); @Override void onSuccess(MessageContext context); @Override void onError(MessageContext context); @Override void onComplete(MessageContext context); @Override void onApplicationResolved(MessageContext context); @Override void onError(Throwable cause); }### Answer: @Test public void shouldInvokeListenerOnApplicationResolved() { observer.onApplicationResolved(context); verify(listener).onApplicationResolved(context); } @Test public void shouldSetApplicationConfigurationOnApplicationResolved() { observer.onApplicationResolved(context); assertEquals(ApplicationContext.instance().getApplicationConfiguration(), applicationConfiguration); }
### Question: Server implements Bundle<ServerBundleConfiguration> { public void init(Container container, ServerBundleConfiguration config) { logger.info("Initializing the container"); ServerConfiguration configuration = container.getConfiguration().getServerConfiguration(); AbstractHttpConnector connector = null; InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); logger.info("Loading the http connectors"); for (ConnectorConfiguration connectorConfig : configuration.getConnectorConfigurations()) { if (connectorConfig.getScheme() == Scheme.https) { connector = createHttpsConnector(connectorConfig, container.getRouter()); } else { connector = createHttpConnector(connectorConfig, container.getRouter()); } connector.registerListener(container.getMessageObserver()); connector.initialize(); connectors.add(connector); } } void init(Container container, ServerBundleConfiguration config); void start(); void stop(); @Override int getOrder(); }### Answer: @Test public void shouldInitializeServer() { server.init(container, null); verify(httpConnector).registerListener(messageObserver); verify(httpConnector).initialize(); verify(httpsConnector).registerListener(messageObserver); verify(httpsConnector).initialize(); }
### Question: Server implements Bundle<ServerBundleConfiguration> { @Override public int getOrder() { return Integer.MAX_VALUE; } void init(Container container, ServerBundleConfiguration config); void start(); void stop(); @Override int getOrder(); }### Answer: @Test public void shouldGetDefaultOrder() { assertEquals(server.getOrder(), Integer.MAX_VALUE); }
### Question: MinnalApplicationEnhancer extends ApplicationEnhancer { protected static String[] getPackagesToScan(Application<ApplicationConfiguration> application) { return application.getConfiguration().getDatabaseConfiguration().getPackagesToScan().toArray(new String[0]); } MinnalApplicationEnhancer(Application<ApplicationConfiguration> application, NamingStrategy namingStrategy); }### Answer: @Test public void shouldGetPackagesToScan() { Application<ApplicationConfiguration> application = mock(Application.class); ApplicationConfiguration configuration = mock(ApplicationConfiguration.class); DatabaseConfiguration databaseConfiguration = mock(DatabaseConfiguration.class); when(databaseConfiguration.getPackagesToScan()).thenReturn(Lists.newArrayList("com.test", "com.test.app")); when(configuration.getDatabaseConfiguration()).thenReturn(databaseConfiguration); when(application.getConfiguration()).thenReturn(configuration); assertEquals(MinnalApplicationEnhancer.getPackagesToScan(application), new String[]{"com.test", "com.test.app"}); }
### Question: MinnalApplicationEnhancer extends ApplicationEnhancer { protected void addResource(Class<?> resourceClass) { ((ResourceConfig) getApplication()).register(resourceClass); } MinnalApplicationEnhancer(Application<ApplicationConfiguration> application, NamingStrategy namingStrategy); }### Answer: @Test public void shouldAddResource() { NamingStrategy strategy = mock(NamingStrategy.class); MinnalApplicationEnhancer enhancer = new MinnalApplicationEnhancer(application, strategy); enhancer.addResource(DummyResource.class); verify(resourceConfig).register(DummyResource.class); }
### Question: InstrumentationBundle extends ContainerAdapter implements Bundle<InstrumentationBundleConfiguration> { protected ApplicationEnhancer createApplicationEnhancer(Application<ApplicationConfiguration> application) { return new MinnalApplicationEnhancer(application, namingStrategy); } void init(Container container, InstrumentationBundleConfiguration configuration); void start(); void stop(); @Override void postMount(Application<ApplicationConfiguration> application); @Override int getOrder(); }### Answer: @Test public void shouldNotEnhanceApplicationIfInstrumentationIsDisabled() { doReturn(enhancer).when(bundle).createApplicationEnhancer(application); bundle.preMount(application); verify(enhancer, never()).enhance(); }
### Question: ActionMetaData extends SecurableMetaData { public Method getMethod() { return method; } ActionMetaData(String name, String path, Method method); List<ParameterMetaData> getParameters(); void addParameter(ParameterMetaData parameter); Method getMethod(); String getPath(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer: @Test public void shouldPopulatePermissionMetaData() throws SecurityException, NoSuchMethodException { ActionMetaData data = new ActionMetaData("dummyAction", "", DummyModel.class.getMethod("dummyAction")); assertEquals(data.getPermissionMetaData().size(), 1); assertEquals(data.getPermissionMetaData().iterator().next(), new PermissionMetaData(Method.POST.getMethod(), Sets.newHashSet("permission1"))); } @Test public void shouldNotPopulatePermissionMetaData() throws SecurityException, NoSuchMethodException { ActionMetaData data = new ActionMetaData("anotherAction", "", DummyModel.class.getMethod("anotherAction")); assertEquals(data.getPermissionMetaData().size(), 0); }
### Question: ElementCollectionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return ElementCollection.class; } @Override Class<?> getAnnotationType(); @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); }### Answer: @Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), ElementCollection.class); }
### Question: ElementCollectionAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { if (ClassUtils.hasAnnotation(method, OneToMany.class)) { logger.debug("Has OneToMany annotation as well. Leaving it to OneToManyAnnotationHandler to process"); return; } Class<?> elementType = getElementType(method.getGenericReturnType()); AssociationMetaData associationMetaData = new AssociationMetaData(getGetterName(method, false), elementType, isEntity(elementType)); metaData.addAssociation(associationMetaData); } @Override Class<?> getAnnotationType(); @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); }### Answer: @Test public void shouldAddToMetadataAssociationWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getAddresses"); handler.handle(metaData, annotation, method); AssociationMetaData data = new AssociationMetaData("addresses", Address.class, false); verify(metaData).addAssociation(data); } @Test public void shouldAddToMetadataAssociationWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("addresses"); handler.handle(metaData, annotation, field); AssociationMetaData data = new AssociationMetaData("addresses", Address.class, false); verify(metaData).addAssociation(data); }
### Question: OneToManyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return OneToMany.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer: @Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), OneToMany.class); }
### Question: OneToManyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public void handle(EntityMetaData metaData, Annotation annotation, Method method) { Class<?> elementType = getElementType(method.getGenericReturnType()); CollectionMetaData collectionMetaData = new CollectionMetaData(metaData.getEntityClass(), getGetterName(method, false), elementType, method.getReturnType(), isEntity(elementType)); metaData.addCollection(collectionMetaData); } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer: @Test public void shouldAddToMetadataCollectionWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getChildren"); handler.handle(metaData, annotation, method); CollectionMetaData data = new CollectionMetaData(DummyModel.class, "children", DummyModel.class, Set.class, true); verify(metaData).addCollection(data); } @Test public void shouldAddToMetadataCollectionWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("children"); handler.handle(metaData, annotation, field); CollectionMetaData data = new CollectionMetaData(DummyModel.class, "children", DummyModel.class, Set.class, true); verify(metaData).addCollection(data); } @Test public void shouldSetRightCollectionTypeWhenOnMethod() throws Exception { Method method = DummyModel.class.getDeclaredMethod("getSiblings"); handler.handle(metaData, annotation, method); CollectionMetaData data = new CollectionMetaData(DummyModel.class, "siblings", DummyModel.class, List.class, true); verify(metaData).addCollection(data); } @Test public void shouldSetRightCollectionTypeWhenOnField() throws Exception { Field field = DummyModel.class.getDeclaredField("siblings"); handler.handle(metaData, annotation, field); CollectionMetaData data = new CollectionMetaData(DummyModel.class, "siblings", DummyModel.class, List.class, true); verify(metaData).addCollection(data); }
### Question: EntityKeyAnnotationHandler extends AbstractEntityAnnotationHandler { @Override public Class<?> getAnnotationType() { return EntityKey.class; } @Override void handle(EntityMetaData metaData, Annotation annotation, Method method); @Override void handle(EntityMetaData metaData, Annotation annotation, Field field); @Override Class<?> getAnnotationType(); }### Answer: @Test public void shouldGetAnnotationType() { assertEquals(handler.getAnnotationType(), EntityKey.class); }
### Question: PasswordEncrypt { private static String asHexStr(byte buf[]) { StringBuffer strbuf = new StringBuffer(buf.length * 2); int i; for (i = 0; i < buf.length; i++) { if (((int) buf[i] & 0xff) < 0x10) strbuf.append("0"); strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); } return strbuf.toString(); } static String encrypt(String message); }### Answer: @Test public void asHexStrTest() throws Exception { String message = "This is just an example"; String encryptedMessage = PasswordEncrypt.encrypt(message); Assert.assertEquals(encryptedMessage, "ec9634d2f7ba601f31e9b3d8c3ac03299628044355fb6e023d2c88917813fe4b"); }
### Question: AccentUtils { public static String removeAccent(String textConvert) { String temp = Normalizer.normalize(textConvert, Normalizer.Form.NFD); Pattern pattern = Pattern.compile(ConstantUtils.REMOVE_ACCENT_PATTERN); return pattern.matcher(temp).replaceAll(StringPool.BLANK) .replaceAll(ReadFilePropertiesUtils.get(ConstantUtils.MARK_UPCASE_D), ReadFilePropertiesUtils.get(ConstantUtils.UPCASE_D)) .replaceAll(ReadFilePropertiesUtils.get(ConstantUtils.MARK_LOWERCASE_D), ReadFilePropertiesUtils.get(ConstantUtils.LOWERCASE_D)) .toLowerCase(); } static String removeAccent(String textConvert); }### Answer: @Test public void asHexStrTest() throws Exception { String message = "Trần Văn A"; String removeAccentMessage = AccentUtils.removeAccent(message); Assert.assertEquals(removeAccentMessage, "Tran Van A"); }
### Question: OCPSUtils { @Deprecated public static long[] toLongArray(List<Long> ls) { long[] output = new long[ls.size()]; int i = 0; for (Long l : ls) { output[i] = l; i++; } return output; } @Deprecated static long[] toLongArray(List<Long> ls); @Deprecated static String[] toStringArray(List<String> ls); }### Answer: @Test public void toLongArrayTest() { List<Long> inputArr = new ArrayList<>(); inputArr.add(12L); inputArr.add(13L); inputArr.add(14L); long[] outputArr = OCPSUtils.toLongArray(inputArr); long[] expectedOutputArr = {12L, 13L, 14L}; Assert.assertArrayEquals(outputArr, expectedOutputArr); }
### Question: OCPSUtils { @Deprecated public static String[] toStringArray(List<String> ls) { String[] output = new String[ls.size()]; int i = 0; for (String l : ls) { output[i] = l; i++; } return output; } @Deprecated static long[] toLongArray(List<Long> ls); @Deprecated static String[] toStringArray(List<String> ls); }### Answer: @Test public void toStringArrayTest() { List<String> inputArr = new ArrayList<>(); inputArr.add("abc"); inputArr.add("bcd"); inputArr.add("def"); String[] outputArr = OCPSUtils.toStringArray(inputArr); String[] expectedOutputArr = {"abc", "bcd", "def"}; Assert.assertArrayEquals(outputArr, expectedOutputArr); }
### Question: APIDateTimeUtils { public static String timeZone2Lucene(String date) { if (GetterUtil.getLong(date) > 0) { return new SimpleDateFormat(LUCENE_DATE_FORMAT).format(new Date(GetterUtil.getLong(date))); } else { Date d = _stringToDate(date, ISO8601); return new SimpleDateFormat(LUCENE_DATE_FORMAT).format(d); } } static String _dateToString(Date date, String format); static Date _stringToDate(String dateStr, String format); static String timeZone2Lucene(String date); static String convertDateToString(Date date, String pattern); static final String _TIMESTAMP; static final String HCM_TIMEZONE; static final String LUCENE_DATE_FORMAT; static final String ISO8601; }### Answer: @Test public void timeZone2LuceneTest() { String outputDateString = APIDateTimeUtils.timeZone2Lucene("20180822142266"); Assert.assertEquals(outputDateString, "26090704075542"); }
### Question: CDICommandBus implements CommandBus { @Override public <R, C extends Command<R>> R execute(C command) { CommandHandler<R, C> commandHandler = (CommandHandler<R, C>) registry.get(command.getClass()); return commandHandler.handle(command); } @Inject CDICommandBus(Registry registry); @Override R execute(C command); }### Answer: @Test public void execute() { when(registry.get(HelloCommand.class)).thenReturn(handler); HelloCommand command = new HelloCommand("joe"); commandBus.execute(command); verify(handler).handle(command); }
### Question: SpringCommandBus implements CommandBus { @Override public <R, C extends Command<R>> R execute(C command) { CommandHandler<R, C> commandHandler = (CommandHandler<R, C>) registry.get(command.getClass()); return commandHandler.handle(command); } @Autowired SpringCommandBus(Registry registry); @Override R execute(C command); }### Answer: @Test public void execute() { when(registry.get(HelloCommand.class)).thenReturn(handler); HelloCommand command = new HelloCommand("bob"); commandBus.execute(command); verify(handler).handle(command); }
### Question: Registry { @SuppressWarnings("unchecked") <R, C extends Command<R>> CommandHandler<R,C> get(Class<C> commandClass) { return providerMap.get(commandClass).get(); } @Autowired Registry(ApplicationContext applicationContext); }### Answer: @Test public void testRegistration() { String[] commandHandlers = new String[]{"helloCommandHandler"}; when(applicationContext.getBeanNamesForType(CommandHandler.class)).thenReturn(commandHandlers); Class type = HelloCommandHandler.class; when(applicationContext.getType("helloCommandHandler")).thenReturn(type); when(applicationContext.getBean(HelloCommandHandler.class)).thenReturn(helloCommandHandler); Registry registry = new Registry(applicationContext); CommandHandler<String, HelloCommand> handler = registry.get(HelloCommand.class); assertThat(handler).isInstanceOf(HelloCommandHandler.class); }
### Question: SoundViewModel extends BaseObservable { public void onButtonClicked() { mBeatBox.play(mSound); } SoundViewModel(BeatBox beatBox); @Bindable String getTitle(); Sound getSound(); void setSound(Sound sound); void onButtonClicked(); }### Answer: @Test public void callsBeatBoxPlayOnButtonClicked() { mSubject.onButtonClicked(); verify(mBeatBox).play(mSound); }
### Question: SoundViewModel extends BaseObservable { @Bindable public String getTitle() { return mSound.getName(); } SoundViewModel(BeatBox beatBox); @Bindable String getTitle(); Sound getSound(); void setSound(Sound sound); void onButtonClicked(); }### Answer: @Test public void exposesSoundNameAsTitle() { assertThat(mSubject.getTitle(), is(mSound.getName())); }
### Question: PubService { public Beer createBeer(final String name, final int alcoholPercentage) { return beerRepository.save(new Beer(name, alcoholPercentage)); } long getBeersCount(); Beer createBeer(final String name, final int alcoholPercentage); BrewingCompany createBrewingCompany(final String name); Iterable<Beer> getAllBeers(); Beer findBeerById(final long id); Beer findBeerByName(final String name); Iterable<Beer> findBeerByAlcoholPercentage(final int alcoholPercentage); Collection<Beer> populateData(); }### Answer: @Test public void testCreateBeer() { assertEquals(0, service.getBeersCount()); Beer myBeer = service.createBeer("mine", 0); assertEquals(1, service.getBeersCount()); Iterable<Beer> founds = service.getAllBeers(); Beer mine = founds.iterator().next(); assertEquals(myBeer.getName(), mine.getName()); }
### Question: PubService { public Beer findBeerById(final long id) { return beerRepository.findOne(id); } long getBeersCount(); Beer createBeer(final String name, final int alcoholPercentage); BrewingCompany createBrewingCompany(final String name); Iterable<Beer> getAllBeers(); Beer findBeerById(final long id); Beer findBeerByName(final String name); Iterable<Beer> findBeerByAlcoholPercentage(final int alcoholPercentage); Collection<Beer> populateData(); }### Answer: @Test public void testFindBeerById() { service.populateData(); for (Beer beer : service.getAllBeers()) { Beer foundBeer = service.findBeerById(beer.getId()); assertNotNull(foundBeer); } }
### Question: PubService { public Iterable<Beer> getAllBeers() { return beerRepository.findAll(); } long getBeersCount(); Beer createBeer(final String name, final int alcoholPercentage); BrewingCompany createBrewingCompany(final String name); Iterable<Beer> getAllBeers(); Beer findBeerById(final long id); Beer findBeerByName(final String name); Iterable<Beer> findBeerByAlcoholPercentage(final int alcoholPercentage); Collection<Beer> populateData(); }### Answer: @Test public void testGetAllBeers() { Collection<Beer> madeBeers = service.populateData(); Iterable<Beer> foundBeers = service.getAllBeers(); int founds = 0; for (Beer foundBeer : foundBeers) { assertTrue(madeBeers.contains(foundBeer)); founds++; } assertEquals(madeBeers.size(), founds); }
### Question: PubService { public Iterable<Beer> findBeerByAlcoholPercentage(final int alcoholPercentage) { return beerRepository.findAllByPropertyValue("alcoholPercentage", alcoholPercentage); } long getBeersCount(); Beer createBeer(final String name, final int alcoholPercentage); BrewingCompany createBrewingCompany(final String name); Iterable<Beer> getAllBeers(); Beer findBeerById(final long id); Beer findBeerByName(final String name); Iterable<Beer> findBeerByAlcoholPercentage(final int alcoholPercentage); Collection<Beer> populateData(); }### Answer: @Test public void testFindBeerByAlcoholPercentage() { service.populateData(); for (Beer beer : service.findBeerByAlcoholPercentage(7)) { assertThat( beer.getName(), is(anyOf(containsString("Chimay Rood"), containsString("Florival Bruin")))); } }
### Question: SimpleGlobPattern { public static SimpleGlobPattern compile(String patternString) { SimpleGlobPattern pattern = EmptyGlobPattern.INSTANCE; int endIndexInclusive = patternString.length() - 1; while ( endIndexInclusive >= 0 ) { int lastWildcardIndex = patternString.lastIndexOf( WILDCARD_MANY, endIndexInclusive ); if ( lastWildcardIndex < endIndexInclusive ) { pattern = pattern.prependLiteral( patternString.substring( lastWildcardIndex + 1, endIndexInclusive + 1 ) ); } if ( 0 <= lastWildcardIndex ) { pattern = pattern.prependMany(); } endIndexInclusive = lastWildcardIndex - 1; } return pattern; } private SimpleGlobPattern(); static SimpleGlobPattern compile(String patternString); boolean matches(String candidate); SimpleGlobPattern prependLiteral(String literal); SimpleGlobPattern prependMany(); Optional<String> toLiteral(); abstract String toPatternString(); }### Answer: @Test public void testEqualsAndHashCode() { assertSoftly( softly -> { SimpleGlobPattern equalPattern = SimpleGlobPattern.compile( patternString ); softly.assertThat( pattern ) .isEqualTo( equalPattern ) .isNotEqualTo( SimpleGlobPattern.compile( patternString + "a" ) ) .isNotEqualTo( SimpleGlobPattern.compile( "a" + patternString ) ) .isNotEqualTo( SimpleGlobPattern.compile( patternString + "a*" ) ) .isNotEqualTo( SimpleGlobPattern.compile( "a*" + patternString ) ); softly.assertThat( pattern.hashCode() == equalPattern.hashCode() ) .as( "Hashcode of .compile(" + patternString + ") is always the same" ) .isTrue(); } ); }
### Question: LoggerInfoStream extends InfoStream { @Override public void close() { } @Override void message(String component, String message); @Override boolean isEnabled(String component); @Override void close(); }### Answer: @Test public void testEnableInfoStream() throws Exception { LoggerInfoStream infoStream = new LoggerInfoStream(); ByteBuffersDirectory directory = new ByteBuffersDirectory(); IndexWriterConfig indexWriterConfig = new IndexWriterConfig( new StandardAnalyzer() ); indexWriterConfig.setInfoStream( infoStream ); IndexWriter indexWriter = new IndexWriter( directory, indexWriterConfig ); Document doc = new Document(); doc.add( new StringField( "f1", "value1", Field.Store.YES ) ); indexWriter.addDocument( doc ); indexWriter.commit(); indexWriter.close(); List<LoggingEvent> loggingEvents = testAppender.searchByLoggerAndMessage( LuceneLogCategories.INFOSTREAM_LOGGER_CATEGORY.getName(), "IW:" ); assertFalse( loggingEvents.isEmpty() ); }
### Question: LuceneIndexSettings { public static String shardKey(String shardId, String radical) { return join( ".", EngineSettings.BACKEND, SHARDS, shardId, radical ); } private LuceneIndexSettings(); static String shardKey(String shardId, String radical); static String shardKey(String indexName, String shardId, String radical); static String shardKey(String backendName, String indexName, String shardId, String radical); static final String DIRECTORY_PREFIX; static final String DIRECTORY_TYPE; static final String DIRECTORY_ROOT; static final String DIRECTORY_LOCKING_STRATEGY; static final String DIRECTORY_FILESYSTEM_ACCESS_STRATEGY; static final String IO_PREFIX; static final String IO_STRATEGY; static final String IO_COMMIT_INTERVAL; static final String IO_REFRESH_INTERVAL; static final String IO_WRITER_PREFIX; static final String IO_WRITER_MAX_BUFFERED_DOCS; static final String IO_WRITER_RAM_BUFFER_SIZE; static final String IO_WRITER_INFOSTREAM; static final String IO_MERGE_PREFIX; static final String IO_MERGE_MAX_DOCS; static final String IO_MERGE_FACTOR; static final String IO_MERGE_MIN_SIZE; static final String IO_MERGE_MAX_SIZE; static final String IO_MERGE_MAX_FORCED_SIZE; static final String IO_MERGE_CALIBRATE_BY_DELETES; static final String SHARDING_PREFIX; static final String SHARDING_STRATEGY; static final String SHARDING_NUMBER_OF_SHARDS; static final String SHARDING_SHARD_IDENTIFIERS; static final String SHARDS; static final String INDEXING_PREFIX; static final String INDEXING_QUEUE_COUNT; static final String INDEXING_QUEUE_SIZE; }### Answer: @Test public void shardKey() { assertThat( LuceneIndexSettings.shardKey( "shardId", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.shards.shardId.foo.bar" ); assertThat( LuceneIndexSettings.shardKey( "indexName", "shardId", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.indexes.indexName.shards.shardId.foo.bar" ); assertThat( LuceneIndexSettings.shardKey( null, "shardId", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.shards.shardId.foo.bar" ); assertThat( LuceneIndexSettings.shardKey( "backendName", "indexName", "shardId", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.backendName.indexes.indexName.shards.shardId.foo.bar" ); assertThat( LuceneIndexSettings.shardKey( null, "indexName", "shardId", "foo.bar" ) ) .isEqualTo( "hibernate.search.backend.indexes.indexName.shards.shardId.foo.bar" ); assertThat( LuceneIndexSettings.shardKey( "backendName", null, "shardId", "foo.bar" ) ) .isEqualTo( "hibernate.search.backends.backendName.shards.shardId.foo.bar" ); }
### Question: LuceneBatchedWorkProcessor implements BatchedWorkProcessor { public void forceCommit() { try { indexAccessor.commit(); } catch (RuntimeException e) { indexAccessor.cleanUpAfterFailure( e, "Commit after a set of index works" ); throw e; } } LuceneBatchedWorkProcessor(EventContext eventContext, IndexAccessor indexAccessor); @Override void beginBatch(); @Override CompletableFuture<?> endBatch(); @Override void complete(); T submit(IndexManagementWork<T> work); T submit(IndexingWork<T> work); void forceCommit(); void forceRefresh(); }### Answer: @Test public void forceCommit() { processor.forceCommit(); verify( indexAccessorMock ).commit(); verifyNoOtherIndexInteractionsAndClear(); }