method2testcases
stringlengths 118
6.63k
|
---|
### Question:
DefaultStatus implements Status { @Override public void created() { response.setStatus(HttpServletResponse.SC_CREATED); result.use(Results.nothing()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@Test public void shouldSetCreatedStatus() throws Exception { status.created(); verify(response).setStatus(201); }
@Test public void shouldSetCreatedStatusAndLocationWithAppPath() throws Exception { when(config.getApplicationPath()).thenReturn("http: status.created("/newResource"); verify(response).setStatus(201); verify(response).addHeader("Location", "http: } |
### Question:
DefaultStatus implements Status { @Override public void ok() { response.setStatus(HttpServletResponse.SC_OK); result.use(Results.nothing()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@Test public void shouldSetOkStatus() throws Exception { status.ok(); verify(response).setStatus(200); } |
### Question:
DefaultStatus implements Status { @Override public void accepted(){ response.setStatus(HttpServletResponse.SC_ACCEPTED ); result.use(Results.nothing()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@Test public void shouldSetAcceptedStatus() throws Exception { status.accepted(); verify(response).setStatus(202); } |
### Question:
DefaultStatus implements Status { @Override public void notImplemented() { response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@Test public void shouldSetNotImplementedStatus() throws Exception { status.notImplemented(); verify(response).setStatus(501); } |
### Question:
DefaultStatus implements Status { @Override public void internalServerError() { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@Test public void shouldSetInternalServerErrorStatus() throws Exception { status.internalServerError(); verify(response).setStatus(500); } |
### Question:
DefaultStatus implements Status { @Override public void movedPermanentlyTo(String location) { this.response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); header("Location", fixLocation(location)); this.response.addIntHeader("Content-length", 0); this.response.addDateHeader("Date", System.currentTimeMillis()); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@Test public void shouldSetMovedPermanentlyStatus() throws Exception { when(config.getApplicationPath()).thenReturn("http: status.movedPermanentlyTo("/newURL"); verify(response).setStatus(301); verify(response).addHeader("Location", "http: }
@Test public void shouldMoveToExactlyURIWhenItIsNotAbsolute() throws Exception { status.movedPermanentlyTo("http: verify(response).addHeader("Location", "http: verify(response).setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); }
@Test public void shouldSetMovedPermanentlyStatusOfLogic() throws Exception { when(config.getApplicationPath()).thenReturn("http: Method method = Resource.class.getDeclaredMethod("method"); when(router.urlFor(eq(Resource.class), eq(method), Mockito.anyVararg())).thenReturn("/resource/method"); status.movedPermanentlyTo(Resource.class).method(); verify(response).setStatus(301); verify(response).addHeader("Location", "http: } |
### Question:
DefaultStatus implements Status { @Override public void badRequest(String message) { sendError(HttpServletResponse.SC_BAD_REQUEST, message); } protected DefaultStatus(); @Inject DefaultStatus(HttpServletResponse response, Result result, Configuration config,
Proxifier proxifier, Router router); @Override void notFound(); @Override void header(String key, String value); @Override void created(); @Override void created(String location); @Override void ok(); @Override void conflict(); @Override void methodNotAllowed(EnumSet<HttpMethod> allowedMethods); @Override void movedPermanentlyTo(String location); @Override T movedPermanentlyTo(final Class<T> controller); @Override void unsupportedMediaType(String message); @Override void badRequest(String message); @Override void badRequest(List<?> errors); @Override void forbidden(String message); @Override void noContent(); @Override void notAcceptable(); @Override void accepted(); @Override void notModified(); @Override void notImplemented(); @Override void internalServerError(); }### Answer:
@SuppressWarnings("deprecation") @Test public void shouldSerializeErrorMessages() throws Exception { Message normal = new SimpleMessage("category", "The message"); I18nMessage i18ned = new I18nMessage("category", "message"); i18ned.setBundle(new SingletonResourceBundle("message", "Something else")); XStreamBuilder xstreamBuilder = cleanInstance(new MessageConverter()); MockSerializationResult result = new MockSerializationResult(null, xstreamBuilder, null, null); DefaultStatus status = new DefaultStatus(response, result, config, new JavassistProxifier(), router); status.badRequest(Arrays.asList(normal, i18ned)); String serialized = result.serializedResult(); assertThat(serialized, containsString("<message>The message</message>")); assertThat(serialized, containsString("<category>category</category>")); assertThat(serialized, containsString("<message>Something else</message>")); assertThat(serialized, not(containsString("<validationMessage>"))); assertThat(serialized, not(containsString("<i18nMessage>"))); }
@SuppressWarnings("deprecation") @Test public void shouldSerializeErrorMessagesInJSON() throws Exception { Message normal = new SimpleMessage("category", "The message"); I18nMessage i18ned = new I18nMessage("category", "message"); i18ned.setBundle(new SingletonResourceBundle("message", "Something else")); List<JsonSerializer<?>> gsonSerializers = new ArrayList<>(); List<JsonDeserializer<?>> gsonDeserializers = new ArrayList<>(); gsonSerializers.add(new MessageGsonConverter()); GsonSerializerBuilder gsonBuilder = new GsonBuilderWrapper(new MockInstanceImpl<>(gsonSerializers), new MockInstanceImpl<>(gsonDeserializers), new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider()); MockSerializationResult result = new MockSerializationResult(null, null, gsonBuilder, new DefaultReflectionProvider()) { @Override public <T extends View> T use(Class<T> view) { return view.cast(new DefaultRepresentationResult(new FormatResolver() { @Override public String getAcceptFormat() { return "json"; } }, this, new MockInstanceImpl<Serialization>(super.use(JSONSerialization.class)))); } }; DefaultStatus status = new DefaultStatus(response, result, config, new JavassistProxifier(), router); status.badRequest(Arrays.asList(normal, i18ned)); String serialized = result.serializedResult(); assertThat(serialized, containsString("\"message\":\"The message\"")); assertThat(serialized, containsString("\"category\":\"category\"")); assertThat(serialized, containsString("\"message\":\"Something else\"")); assertThat(serialized, not(containsString("\"validationMessage\""))); assertThat(serialized, not(containsString("\"i18nMessage\""))); } |
### Question:
DefaultPageResult implements PageResult { @Override public void redirectTo(String url) { logger.debug("redirection to {}", url); try { if (url.startsWith("/")) { response.sendRedirect(request.getContextPath() + url); } else { response.sendRedirect(url); } } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldRedirectIncludingContext() throws Exception { when(request.getContextPath()).thenReturn("/context"); view.redirectTo("/any/url"); verify(response).sendRedirect("/context/any/url"); }
@Test public void shouldNotIncludeContextPathIfURIIsAbsolute() throws Exception { view.redirectTo("http: verify(request, never()).getContextPath(); verify(response, only()).sendRedirect("http: }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileRedirect() throws Exception { exception.expect(ResultException.class); doThrow(new IOException()).when(response).sendRedirect(anyString()); view.redirectTo("/any/url"); } |
### Question:
VRaptorRequest extends HttpServletRequestWrapper implements MutableRequest { @Override public String getParameter(String name) { if (extraParameters.containsKey(name)) { return extraParameters.get(name)[0]; } return super.getParameter(name); } VRaptorRequest(HttpServletRequest request); @Override String getParameter(String name); @Override Enumeration<String> getParameterNames(); @Override String[] getParameterValues(String name); @Override Map<String, String[]> getParameterMap(); @Override void setParameter(String key, String... value); @Override String getRequestedUri(); static String getRelativeRequestURI(HttpServletRequest request); @Override String toString(); }### Answer:
@Test public void searchesOnTheFallbackRequest() { assertThat(vraptor.getParameter("name"), is(equalTo("guilherme"))); }
@Test public void returnsNullIfNotFound() { assertThat(vraptor.getParameter("minimum"), is(nullValue())); } |
### Question:
DefaultPageResult implements PageResult { @Override public void forwardTo(String url) { logger.debug("forwarding to {}", url); try { request.getRequestDispatcher(url).forward(request, response); } catch (ServletException | IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldForwardToGivenURI() throws Exception { when(request.getRequestDispatcher("/any/url")).thenReturn(dispatcher); view.forwardTo("/any/url"); verify(dispatcher, only()).forward(request, response); }
@Test public void shouldThrowResultExceptionIfServletExceptionOccursWhileForwarding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).forward(request, response); view.forwardTo("/any/url"); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileForwarding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).forward(request, response); view.forwardTo("/any/url"); } |
### Question:
DefaultPageResult implements PageResult { @Override public void defaultView() { String to = resolver.pathFor(methodInfo.getControllerMethod()); logger.debug("forwarding to {}", to); try { request.getRequestDispatcher(to).forward(request, response); } catch (ServletException e) { throw new ApplicationLogicException(to + " raised an exception", e); } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldAllowCustomPathResolverWhileForwardingView() throws ServletException, IOException { when(request.getRequestDispatcher("fixed")).thenReturn(dispatcher); view.defaultView(); verify(dispatcher, only()).forward(request, response); }
@Test public void shouldThrowApplicationLogicExceptionIfServletExceptionOccursWhileForwardingView() throws Exception { exception.expect(ApplicationLogicException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).forward(request, response); view.defaultView(); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileForwardingView() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).forward(request, response); view.defaultView(); } |
### Question:
DefaultPageResult implements PageResult { @Override public void include() { try { String to = resolver.pathFor(methodInfo.getControllerMethod()); logger.debug("including {}", to); request.getRequestDispatcher(to).include(request, response); } catch (ServletException e) { throw new ResultException(e); } catch (IOException e) { throw new ResultException(e); } } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shouldAllowCustomPathResolverWhileIncluding() throws ServletException, IOException { when(request.getRequestDispatcher("fixed")).thenReturn(dispatcher); view.include(); verify(dispatcher, only()).include(request, response); }
@Test public void shouldThrowResultExceptionIfServletExceptionOccursWhileIncluding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new ServletException()).when(dispatcher).include(request, response); view.include(); }
@Test public void shouldThrowResultExceptionIfIOExceptionOccursWhileIncluding() throws Exception { exception.expect(ResultException.class); when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); doThrow(new IOException()).when(dispatcher).include(request, response); view.include(); } |
### Question:
DefaultPageResult implements PageResult { @Override public <T> T of(final Class<T> controllerType) { return proxifier.proxify(controllerType, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { request.getRequestDispatcher( resolver.pathFor(DefaultControllerMethod.instanceFor(controllerType, method))).forward( request, response); return null; } catch (Exception e) { throw new ProxyInvocationException(e); } } }); } protected DefaultPageResult(); @Inject DefaultPageResult(MutableRequest req, MutableResponse res, MethodInfo methodInfo,
PathResolver resolver, Proxifier proxifier); @Override void defaultView(); @Override void include(); @Override void redirectTo(String url); @Override void forwardTo(String url); @Override T of(final Class<T> controllerType); }### Answer:
@Test public void shoudNotExecuteLogicWhenUsingResultOf() { when(request.getRequestDispatcher(anyString())).thenReturn(dispatcher); try { view.of(SimpleController.class).notAllowedMethod(); } catch (UnsupportedOperationException e) { fail("Method should not be executed"); } }
@Test public void shoudThrowProxyInvocationExceptionIfAndExceptionOccursWhenUsingResultOf() { exception.expect(ProxyInvocationException.class); doThrow(new NullPointerException()).when(request).getRequestDispatcher(anyString()); view.of(SimpleController.class).notAllowedMethod(); } |
### Question:
DefaultPathResolver implements PathResolver { @Override public String pathFor(ControllerMethod method) { logger.debug("Resolving path for {}", method); String format = resolver.getAcceptFormat(); String suffix = ""; if (format != null && !format.equals("html")) { suffix = "." + format; } String name = method.getController().getType().getSimpleName(); String folderName = extractControllerFromName(name); String path = getPrefix() + folderName + "/" + method.getMethod().getName() + suffix + "." + getExtension(); logger.debug("Returning path {} for {}", path, method); return path; } protected DefaultPathResolver(); @Inject DefaultPathResolver(FormatResolver resolver); @Override String pathFor(ControllerMethod method); }### Answer:
@Test public void shouldUseResourceTypeAndMethodNameToResolveJsp(){ when(formatResolver.getAcceptFormat()).thenReturn(null); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.jsp")); }
@Test public void shouldUseTheFormatIfSupplied() throws NoSuchMethodException { when(formatResolver.getAcceptFormat()).thenReturn("json"); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.json.jsp")); }
@Test public void shouldIgnoreHtmlFormat() throws NoSuchMethodException { when(formatResolver.getAcceptFormat()).thenReturn("html"); String result = resolver.pathFor(method); assertThat(result, is("/WEB-INF/jsp/dog/bark.jsp")); } |
### Question:
DefaultHttpResult implements HttpResult { @Override public void sendError(int statusCode) { try { response.sendError(statusCode); } catch (IOException e) { throw new ResultException("Error while setting status code", e); } } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); }### Answer:
@Test public void shouldSendError() throws Exception { httpResult.sendError(SC_INTERNAL_SERVER_ERROR); verify(response).sendError(SC_INTERNAL_SERVER_ERROR); }
@Test public void shouldThrowsResultExceptionIfAnIOExceptionWhenSendError() throws Exception { doThrow(new IOException()).when(response).sendError(anyInt()); try { httpResult.sendError(SC_INTERNAL_SERVER_ERROR); fail("should throw ResultException"); } catch (ResultException e) { verify(response, only()).sendError(anyInt()); } }
@Test public void shouldSendErrorWithMessage() throws Exception { httpResult.sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); verify(response).sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenSendErrorWithMessage() throws Exception { doThrow(new IOException()).when(response).sendError(anyInt(), anyString()); try { httpResult.sendError(SC_INTERNAL_SERVER_ERROR, "A simple message"); fail("should throw ResultException"); } catch (ResultException e) { verify(response, only()).sendError(anyInt(), anyString()); } } |
### Question:
DefaultHttpResult implements HttpResult { @Override public void setStatusCode(int statusCode) { response.setStatus(statusCode); } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); }### Answer:
@Test public void shouldSetStatusCode() throws Exception { httpResult.setStatusCode(SC_INTERNAL_SERVER_ERROR); verify(response).setStatus(SC_INTERNAL_SERVER_ERROR); } |
### Question:
DefaultHttpResult implements HttpResult { @Override public HttpResult body(String body) { try { response.getWriter().print(body); } catch (IOException e) { throw new ResultException("Couldn't write to response body", e); } return this; } protected DefaultHttpResult(); @Inject DefaultHttpResult(HttpServletResponse response, Status status); @Override HttpResult addDateHeader(String name, long date); @Override HttpResult addHeader(String name, String value); @Override HttpResult addIntHeader(String name, int value); @Override void sendError(int statusCode); @Override void sendError(int statusCode, String message); @Override void setStatusCode(int statusCode); void movedPermanentlyTo(String uri); T movedPermanentlyTo(final Class<T> controller); @Override HttpResult body(String body); @Override HttpResult body(InputStream body); @Override HttpResult body(Reader body); }### Answer:
@Test public void shouldWriteStringBody() throws Exception { PrintWriter writer = mock(PrintWriter.class); when(response.getWriter()).thenReturn(writer); httpResult.body("The text"); verify(writer).print(anyString()); }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteStringBody() throws Exception { doThrow(new IOException()).when(response).getWriter(); try { httpResult.body("The text"); fail("should throw ResultException"); } catch (ResultException e) { } }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteInputStreamBody() throws Exception { doThrow(new IOException()).when(response).getOutputStream(); InputStream in = new ByteArrayInputStream("the text".getBytes()); try { httpResult.body(in); fail("should throw ResultException"); } catch (ResultException e) { } }
@Test public void shouldThrowResultExceptionIfAnIOExceptionWhenWriteReaderBody() throws Exception { doThrow(new IOException()).when(response).getWriter(); Reader reader = new StringReader("the text"); try { httpResult.body(reader); fail("should throw ResultException"); } catch (ResultException e) { } } |
### Question:
DefaultRefererResult implements RefererResult { @Override public void forward() throws IllegalStateException { String referer = getReferer(); try { ControllerMethod method = router.parse(referer, HttpMethod.GET, request); executeMethod(method, result.use(logic()).forwardTo(method.getController().getType())); } catch (ControllerNotFoundException | MethodNotAllowedException e) { logger.warn("Could not find or doesn't allowed to get controller method", e); result.use(page()).forwardTo(referer); } } protected DefaultRefererResult(); @Inject DefaultRefererResult(Result result, MutableRequest request, Router router, ParametersProvider provider,
ReflectionProvider reflectionProvider); @Override void forward(); @Override void redirect(); }### Answer:
@Test public void whenThereIsNoRefererShouldThrowExceptionOnForward() throws Exception { when(request.getHeader("Referer")).thenReturn(null); try { refererResult.forward(); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { } }
@Test public void whenRefererDontMatchAControllerShouldForwardToPage() throws Exception { PageResult page = mock(PageResult.class); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenThrow(new ControllerNotFoundException()); doReturn(page).when(result).use(page()); refererResult.forward(); verify(page).forwardTo("/no-controller"); }
@Test public void whenRefererMatchesAControllerShouldForwardToIt() throws Exception { LogicResult logic = mock(LogicResult.class); RefererController controller = mock(RefererController.class); Method index = RefererController.class.getMethod("index"); ControllerMethod method = DefaultControllerMethod.instanceFor(RefererController.class, index); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenReturn(method); doReturn(logic).when(result).use(logic()); when(logic.forwardTo(RefererController.class)).thenReturn(controller); refererResult.forward(); verify(logic).forwardTo(RefererController.class); verify(controller).index(); } |
### Question:
DefaultRefererResult implements RefererResult { @Override public void redirect() throws IllegalStateException { String referer = getReferer(); try { ControllerMethod method = router.parse(referer, HttpMethod.GET, request); executeMethod(method, result.use(logic()).redirectTo(method.getController().getType())); } catch (ControllerNotFoundException | MethodNotAllowedException e) { logger.warn("Could not find or doesn't allowed to get controller method", e); result.use(page()).redirectTo(referer); } } protected DefaultRefererResult(); @Inject DefaultRefererResult(Result result, MutableRequest request, Router router, ParametersProvider provider,
ReflectionProvider reflectionProvider); @Override void forward(); @Override void redirect(); }### Answer:
@Test public void whenThereIsNoRefererShouldThrowExceptionOnRedirect() throws Exception { when(request.getHeader("Referer")).thenReturn(null); try { refererResult.redirect(); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { } }
@Test public void whenRefererDontMatchAControllerShouldRedirectToPage() throws Exception { PageResult page = mock(PageResult.class); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenThrow(new ControllerNotFoundException()); doReturn(page).when(result).use(page()); refererResult.redirect(); verify(page).redirectTo("/no-controller"); }
@Test public void whenRefererMatchesAControllerShouldRedirectToIt() throws Exception { LogicResult logic = mock(LogicResult.class); RefererController controller = mock(RefererController.class); Method index = RefererController.class.getMethod("index"); ControllerMethod method = DefaultControllerMethod.instanceFor(RefererController.class, index); when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vraptor"); when(router.parse("/no-controller", HttpMethod.GET, request)).thenReturn(method); doReturn(logic).when(result).use(logic()); when(logic.redirectTo(RefererController.class)).thenReturn(controller); refererResult.redirect(); verify(logic).redirectTo(RefererController.class); verify(controller).index(); } |
### Question:
DefaultRefererResult implements RefererResult { protected String getReferer() { String referer = request.getHeader("Referer"); checkState(referer != null, "The Referer header was not specified"); String refererPath = null; try { refererPath = new URL(referer).getPath(); } catch(MalformedURLException e) { refererPath = referer; } String ctxPath = request.getContextPath(); return refererPath.startsWith(ctxPath+"/") || refererPath.equals(ctxPath) ? refererPath.substring(ctxPath.length()) : refererPath; } protected DefaultRefererResult(); @Inject DefaultRefererResult(Result result, MutableRequest request, Router router, ParametersProvider provider,
ReflectionProvider reflectionProvider); @Override void forward(); @Override void redirect(); }### Answer:
@Test public void whenCtxPathAppearsInItsPlaceRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/test"); assertEquals("/anything/ok", refererResult.getReferer()); }
@Test public void whenCtxPathAppearsAmongURLButNotInRightPlaceRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vrap"); assertEquals("/vrapanything/ok/vrap/ok/vrap", refererResult.getReferer()); }
@Test public void whenCtxPathEqualsURLPathRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("http: when(request.getContextPath()).thenReturn("/vrap"); assertEquals("/", refererResult.getReferer()); }
@Test public void whenRefererIsARelativePathRefererShouldBeReturnedCorrectly() throws Exception { when(request.getHeader("Referer")).thenReturn("/vrap/anything/ok/vrap"); when(request.getContextPath()).thenReturn("/vrap"); assertEquals("/anything/ok/vrap", refererResult.getReferer()); } |
### Question:
CDIBasedContainer implements Container { @Override @SuppressWarnings("unchecked") public <T> T instanceFor(Class<T> type) { type = (Class<T>) CDIProxies.extractRawTypeIfPossible(type); logger.debug("asking cdi to get instance for {}", type); Bean<?> bean = getBeanFrom(type); CreationalContext<?> ctx = beanManager.createCreationalContext(bean); return (T) beanManager.getReference(bean, type, ctx); } protected CDIBasedContainer(); @Inject CDIBasedContainer(BeanManager beanManager); @Override @SuppressWarnings("unchecked") T instanceFor(Class<T> type); @Override @SuppressWarnings("unchecked") boolean canProvide(Class<T> type); }### Answer:
@Test public void shouldCreateComponentsWithCache(){ UsingCacheComponent component = cdiBasedContainer.instanceFor(UsingCacheComponent.class); component.putWithLRU("test","test"); component.putWithDefault("test2","test2"); assertEquals(component.putWithLRU("test","test"),"test"); assertEquals(component.putWithDefault("test2","test2"),"test2"); }
@Test public void shoudRegisterResourcesInRouter() { initEvent.fire(new VRaptorInitialized(null)); Router router = instanceFor(Router.class); Matcher<Iterable<? super Route>> hasItem = hasItem(canHandle(ControllerInTheClasspath.class, ControllerInTheClasspath.class.getDeclaredMethods()[0])); assertThat(router.allRoutes(), hasItem); }
@Test public void shoudRegisterConvertersInConverters() { Converters converters = instanceFor(Converters.class); Converter<?> converter = converters.to(Void.class); assertThat(converter, is(instanceOf(ConverterInTheClasspath.class))); }
@Test public void shouldReturnAllDefaultDeserializers() { Deserializers deserializers = instanceFor(Deserializers.class); List<String> types = asList("application/json", "json", "application/xml", "xml", "text/xml", "application/x-www-form-urlencoded"); for (String type : types) { assertThat("deserializer not found: " + type, deserializers.deserializerFor(type, cdiBasedContainer), is(notNullValue())); } }
@Test public void shouldReturnAllDefaultConverters() { Converters converters = instanceFor(Converters.class); final HashMap<Class<?>, Class<?>> EXPECTED_CONVERTERS = new HashMap<Class<?>, Class<?>>() { { put(int.class, PrimitiveIntConverter.class); put(long.class, PrimitiveLongConverter.class); put(short.class, PrimitiveShortConverter.class); put(byte.class, PrimitiveByteConverter.class); put(double.class, PrimitiveDoubleConverter.class); put(float.class, PrimitiveFloatConverter.class); put(boolean.class, PrimitiveBooleanConverter.class); put(Integer.class, IntegerConverter.class); put(Long.class, LongConverter.class); put(Short.class, ShortConverter.class); put(Byte.class, ByteConverter.class); put(Double.class, DoubleConverter.class); put(Float.class, FloatConverter.class); put(Boolean.class, BooleanConverter.class); put(Calendar.class, CalendarConverter.class); put(Date.class, DateConverter.class); put(Enum.class, EnumConverter.class); } private static final long serialVersionUID = 8559316558416038474L; }; for (Entry<Class<?>, Class<?>> entry : EXPECTED_CONVERTERS.entrySet()) { Converter<?> converter = converters.to((Class<?>) entry.getKey()); assertThat(converter, is(instanceOf(entry.getValue()))); } }
@Test public void shoudRegisterInterceptorsInInterceptorRegistry() { InterceptorRegistry registry = instanceFor(InterceptorRegistry.class); assertThat(registry.all(), hasOneCopyOf(InterceptorInTheClasspath.class)); } |
### Question:
InterceptorStereotypeHandler { public void handle(@Observes @InterceptsQualifier BeanClass beanClass) { Class<?> originalType = beanClass.getType(); interceptorValidator.validate(originalType); logger.debug("Found interceptor for {}", originalType); registry.register(originalType); } protected InterceptorStereotypeHandler(); @Inject InterceptorStereotypeHandler(InterceptorRegistry registry, InterceptorValidator validator); void handle(@Observes @InterceptsQualifier BeanClass beanClass); }### Answer:
@Test public void shouldRegisterInterceptorsOnRegistry() throws Exception { handler.handle(new DefaultBeanClass(InterceptorA.class)); verify(interceptorRegistry, times(1)).register(InterceptorA.class); } |
### Question:
DefaultResult extends AbstractResult { @Override public <T extends View> T use(Class<T> view) { messages.assertAbsenceOfErrors(); responseCommitted = true; return container.instanceFor(view); } protected DefaultResult(); @Inject DefaultResult(HttpServletRequest request, Container container, ExceptionMapper exceptions, TypeNameExtractor extractor,
Messages messages); @Override T use(Class<T> view); @Override Result on(Class<? extends Exception> exception); @Override Result include(String key, Object value); @Override boolean used(); @Override Map<String, Object> included(); @Override Result include(Object value); }### Answer:
@Test public void shouldUseContainerForNewView() { final MyView expectedView = new MyView(); when(container.instanceFor(MyView.class)).thenReturn(expectedView); MyView view = result.use(MyView.class); assertThat(view, is(expectedView)); }
@Test public void shouldCallAssertAbsenceOfErrorsMethodFromMessages() throws Exception { result.use(Results.json()); verify(messages).assertAbsenceOfErrors(); } |
### Question:
DefaultResult extends AbstractResult { @Override public Result include(String key, Object value) { logger.debug("including attribute {}: {}", key, value); includedAttributes.put(key, value); request.setAttribute(key, value); return this; } protected DefaultResult(); @Inject DefaultResult(HttpServletRequest request, Container container, ExceptionMapper exceptions, TypeNameExtractor extractor,
Messages messages); @Override T use(Class<T> view); @Override Result on(Class<? extends Exception> exception); @Override Result include(String key, Object value); @Override boolean used(); @Override Map<String, Object> included(); @Override Result include(Object value); }### Answer:
@Test public void shouldSetRequestAttribute() { result.include("my_key", "my_value"); verify(request).setAttribute("my_key", "my_value"); }
@Test public void shouldIncludeExtractedNameWhenSimplyIncluding() throws Exception { Account account = new Account(); when(extractor.nameFor(Account.class)).thenReturn("account"); result.include(account); verify(request).setAttribute("account", account); }
@Test public void shouldNotIncludeTheAttributeWhenTheValueIsNull() throws Exception { result.include(null); verify(request, never()).setAttribute(anyString(), anyObject()); } |
### Question:
InterceptorStackHandlersCache { public LinkedList<InterceptorHandler> getInterceptorHandlers() { return new LinkedList<>(interceptorHandlers); } protected InterceptorStackHandlersCache(); @Inject InterceptorStackHandlersCache(InterceptorRegistry registry, InterceptorHandlerFactory handlerFactory); void init(); LinkedList<InterceptorHandler> getInterceptorHandlers(); }### Answer:
@Test public void shouldReturnHandlersListInTheSameOrderThatRegistry() { LinkedList<InterceptorHandler> handlers = cache.getInterceptorHandlers(); assertEquals(FirstInterceptor.class, extractInterceptor(handlers.get(0))); assertEquals(SecondInterceptor.class, extractInterceptor(handlers.get(1))); }
@Test public void cacheShouldBeImmutable() { cache.getInterceptorHandlers().remove(0); assertEquals(2, cache.getInterceptorHandlers().size()); } |
### Question:
JstlLocalization { @Produces public Locale getLocale() { Locale localeFromConfig = localeFor(Config.FMT_LOCALE); return firstNonNull(localeFromConfig, Locale.getDefault()); } protected JstlLocalization(); @Inject JstlLocalization(HttpServletRequest request); @Produces ResourceBundle getBundle(Locale locale); @Produces Locale getLocale(); }### Answer:
@Test public void shouldGetLocaleFromRequestFirst() { when(request.getAttribute(FMT_LOCALE + ".request")).thenReturn(PT_BR); when(session.getAttribute(FMT_LOCALE + ".session")).thenReturn(Locale.ENGLISH); when(servletContext.getAttribute(FMT_LOCALE + ".application")).thenReturn(Locale.ENGLISH); when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(Locale.ENGLISH.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromSessionWhenNotFoundInRequest() { when(session.getAttribute(FMT_LOCALE + ".session")).thenReturn(PT_BR); when(servletContext.getAttribute(FMT_LOCALE + ".application")).thenReturn(Locale.ENGLISH); when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(Locale.ENGLISH.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromServletContextWhenNotFoundInSession() { when(servletContext.getAttribute(FMT_LOCALE + ".application")).thenReturn(PT_BR); when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(Locale.ENGLISH.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromInitParameterWhenNotFoundInServletContext() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn(PT_BR.toString()); when(request.getLocale()).thenReturn(Locale.ENGLISH); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void shouldGetLocaleFromRequestLocaleWhenNotFoundUnderAnyOtherScope() { when(request.getLocale()).thenReturn(PT_BR); assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(PT_BR)); }
@Test public void findLocaleFromDefaultWhenNotFoundInAnyOtherScope() { assumeThat(Locale.getDefault(), is(Locale.ENGLISH)); assertThat(localization.getLocale(), equalTo(Locale.ENGLISH)); }
@Test public void parseLocaleWithLanguage() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn("pt"); assertThat(localization.getLocale().getLanguage(), equalTo("pt")); }
@Test public void parseLocaleWithLanguageAndCountry() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn("pt_BR"); assertThat(localization.getLocale().getLanguage(), equalTo("pt")); assertThat(localization.getLocale().getCountry(), equalTo("BR")); }
@Test public void parseLocaleWithLanguageAndCountryAndVariant() { when(servletContext.getInitParameter(Config.FMT_LOCALE)).thenReturn("pt_BR_POSIX"); assertThat(localization.getLocale().getLanguage(), equalTo("pt")); assertThat(localization.getLocale().getCountry(), equalTo("BR")); assertThat(localization.getLocale().getVariant(), equalTo("POSIX")); } |
### Question:
DefaultInterceptorStack implements InterceptorStack { @Override public void start() { ControllerMethod method = controllerMethod.get(); interceptorsReadyEvent.fire(new InterceptorsReady(method)); LinkedList<InterceptorHandler> handlers = cache.getInterceptorHandlers(); internalStack.addFirst(handlers.iterator()); this.next(method, controllerInstance.get().getController()); internalStack.poll(); } protected DefaultInterceptorStack(); @Inject DefaultInterceptorStack(InterceptorStackHandlersCache cache, Instance<ControllerMethod>
controllerMethod, Instance<ControllerInstance> controllerInstance, Event<InterceptorsExecuted> event,
Event<InterceptorsReady> stackStartingEvent); @Override void next(ControllerMethod method, Object controllerInstance); @Override void start(); }### Answer:
@Test public void firesStartEventOnStart() throws Exception { stack.start(); verify(interceptorsReadyEvent).fire(any(InterceptorsReady.class)); }
@Test public void executesTheFirstHandler() throws Exception { stack.start(); verify(handler).execute(stack, controllerMethod, controller); }
@Test public void doesntFireEndOfStackIfTheInterceptorsDontContinueTheStack() throws Exception { stack.start(); verify(interceptorsExecutedEvent, never()).fire(any(InterceptorsExecuted.class)); }
@Test public void firesEndOfStackIfAllInterceptorsWereExecuted() throws Exception { doAnswer(callNext()).when(handler).execute(stack, controllerMethod, controller); stack.start(); verify(interceptorsExecutedEvent).fire(any(InterceptorsExecuted.class)); } |
### Question:
ExceptionRecorder implements MethodInvocation<T> { public void replay(Result result) { Object current = result; for (ExceptionRecorderParameter p : parameters) { current = reflectionProvider.invoke(current, p.getMethod(), p.getArgs()); } } ExceptionRecorder(Proxifier proxifier, ReflectionProvider reflectionProvider); @Override @SuppressWarnings({ "unchecked", "rawtypes" }) Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod); void replay(Result result); }### Answer:
@Test public void withRootException() { mapper.record(Exception.class).forwardTo(DEFAULT_REDIRECT); mapper.findByException(new Exception()).replay(result); verify(result).forwardTo(DEFAULT_REDIRECT); }
@Test public void withNestedException() { mapper.record(IllegalStateException.class).forwardTo(DEFAULT_REDIRECT); mapper.findByException(new RuntimeException(new IllegalStateException())).replay(result); verify(result).forwardTo(DEFAULT_REDIRECT); } |
### Question:
ToInstantiateInterceptorHandler implements InterceptorHandler { @Override public void execute(final InterceptorStack stack, final ControllerMethod method, final Object controllerInstance) throws InterceptionException { final Interceptor interceptor = (Interceptor) container.instanceFor(type); if (interceptor == null) { throw new InterceptionException("Unable to instantiate interceptor for " + type.getName() + ": the container returned null."); } if (interceptor.accepts(method)) { logger.debug("Invoking interceptor {}", interceptor.getClass().getSimpleName()); executeSafely(stack, method, controllerInstance, interceptor); } else { stack.next(method, controllerInstance); } } ToInstantiateInterceptorHandler(Container container, Class<?> type, ExecuteMethodExceptionHandler executeMethodExceptionHandler); @Override void execute(final InterceptorStack stack, final ControllerMethod method, final Object controllerInstance); @Override String toString(); }### Answer:
@Test public void shouldComplainWhenUnableToInstantiateAnInterceptor() throws InterceptionException, IOException { exception.expect(InterceptionException.class); exception.expectMessage(containsString("Unable to instantiate interceptor for")); when(container.instanceFor(MyWeirdInterceptor.class)).thenReturn(null); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, MyWeirdInterceptor.class, new ExecuteMethodExceptionHandler()); handler.execute(null, null, null); }
@Test public void shouldInvokeInterceptorsMethodIfAbleToInstantiateIt() throws InterceptionException, IOException { final Object instance = new Object(); when(container.instanceFor(Interceptor.class)).thenReturn(interceptor); when(interceptor.accepts(method)).thenReturn(true); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, Interceptor.class, new ExecuteMethodExceptionHandler()); handler.execute(stack, method, instance); verify(interceptor).intercept(stack, method, instance); }
@Test public void shouldNotInvokeInterceptorsMethodIfInterceptorDoesntAcceptsResource() throws InterceptionException, IOException { final Object instance = new Object(); when(container.instanceFor(Interceptor.class)).thenReturn(interceptor); when(interceptor.accepts(method)).thenReturn(false); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, Interceptor.class, new ExecuteMethodExceptionHandler()); handler.execute(stack, method, instance); verify(interceptor, never()).intercept(stack, method, instance); verify(stack).next(method, instance); }
@Test public void shouldCatchValidationExceptionOfValidatedInterceptor() { MyValidatedInterceptor validatedInterceptor = new MyValidatedInterceptor(); when(container.instanceFor(MyValidatedInterceptor.class)).thenReturn(validatedInterceptor); ExecuteMethodExceptionHandler exceptionHandler = Mockito.spy(new ExecuteMethodExceptionHandler()); ToInstantiateInterceptorHandler handler = new ToInstantiateInterceptorHandler(container, MyValidatedInterceptor.class, exceptionHandler); handler.execute(stack, method, new Object()); verify(exceptionHandler).handle(Mockito.any(ValidationException.class)); } |
### Question:
DefaultConverters implements Converters { @SuppressWarnings("unchecked") @Override public <T> Converter<T> to(Class<T> clazz) { Class<? extends Converter<?>> converterType = findConverterTypeFromCache(clazz); checkState(!converterType.equals(NullConverter.class), "Unable to find converter for %s", clazz.getName()); logger.debug("found converter {} to {}", converterType.getName(), clazz.getName()); return (Converter<T>) container.instanceFor(converterType); } protected DefaultConverters(); @Inject DefaultConverters(Container container, @LRU CacheStore<Class<?>, Class<? extends Converter<?>>> cache); @Override void register(Class<? extends Converter<?>> converterClass); @SuppressWarnings("unchecked") @Override Converter<T> to(Class<T> clazz); @Override boolean existsFor(Class<?> type); @Override boolean existsTwoWayFor(Class<?> type); @Override TwoWayConverter<?> twoWayConverterFor(Class<?> type); }### Answer:
@Test public void complainsIfNoConverterFound() { exception.expect(IllegalStateException.class); exception.expectMessage("Unable to find converter for " + getClass().getName()); converters.to(DefaultConvertersTest.class); } |
### Question:
DefaultConverters implements Converters { @Override public void register(Class<? extends Converter<?>> converterClass) { Convert type = converterClass.getAnnotation(Convert.class); checkState(type != null, "The converter type %s should have the Convert annotation", converterClass.getName()); Class<? extends Converter<?>> currentConverter = findConverterType(type.value()); if (!currentConverter.equals(NullConverter.class)) { int priority = getConverterPriority(converterClass); int priorityCurrent = getConverterPriority(currentConverter); Convert currentType = currentConverter.getAnnotation(Convert.class); checkState(priority != priorityCurrent || !type.value().equals(currentType.value()), "Converter %s have same priority than %s", converterClass, currentConverter); if (priority > priorityCurrent) { logger.debug("Overriding converter {} with {} because have more priority", currentConverter, converterClass); classes.remove(currentConverter); classes.add(converterClass); } else { logger.debug("Converter {} not registered because have less priority than {}", converterClass, currentConverter); } } logger.debug("adding converter {} to {}", converterClass, type.value()); classes.add(converterClass); } protected DefaultConverters(); @Inject DefaultConverters(Container container, @LRU CacheStore<Class<?>, Class<? extends Converter<?>>> cache); @Override void register(Class<? extends Converter<?>> converterClass); @SuppressWarnings("unchecked") @Override Converter<T> to(Class<T> clazz); @Override boolean existsFor(Class<?> type); @Override boolean existsTwoWayFor(Class<?> type); @Override TwoWayConverter<?> twoWayConverterFor(Class<?> type); }### Answer:
@Test public void convertingANonAnnotatedConverterEndsUpComplaining() { exception.expect(IllegalStateException.class); exception.expectMessage("The converter type " + WrongConverter.class.getName() + " should have the Convert annotation"); converters.register(WrongConverter.class); }
@Test public void shouldForbidConverterWithSamePriority() { exception.expect(IllegalStateException.class); exception.expectMessage(String.format("Converter %s have same priority than %s", MyThirdConverter.class, MySecondConverter.class)); converters.register(MySecondConverter.class); converters.register(MyThirdConverter.class); } |
### Question:
DefaultStaticContentHandler implements StaticContentHandler { @Override public boolean requestingStaticFile(HttpServletRequest request) throws MalformedURLException { URL resourceUrl = context.getResource(uriRelativeToContextRoot(request)); return resourceUrl != null && isAFile(resourceUrl); } protected DefaultStaticContentHandler(); @Inject DefaultStaticContentHandler(ServletContext context); @Override boolean requestingStaticFile(HttpServletRequest request); @Override void deferProcessingToContainer(FilterChain filterChain, HttpServletRequest request,
HttpServletResponse response); }### Answer:
@Test public void returnsTrueForRealStaticResources() throws Exception { String key = file.getAbsolutePath(); when(request.getRequestURI()).thenReturn("/contextName/" +key); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(file.toURI().toURL()); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(true))); }
@Test public void returnsTrueForRealStaticResourcesWithQueryString() throws Exception { String key = file.getAbsolutePath(); when(request.getRequestURI()).thenReturn("/contextName/" + key + "?jsesssionid=12lkjahfsd12414"); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(file.toURI().toURL()); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(true))); }
@Test public void returnsTrueForRealStaticResourcesWithJSessionId() throws Exception { String key = file.getAbsolutePath(); when(request.getRequestURI()).thenReturn("/contextName/" + key + ";jsesssionid=12lkjahfsd12414"); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(file.toURI().toURL()); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(true))); }
@Test public void returnsFalseForNonStaticResources() throws Exception { String key = "thefile.xml"; when(request.getRequestURI()).thenReturn("/contextName/" + key); when(request.getContextPath()).thenReturn("/contextName/"); when(context.getResource(key)).thenReturn(null); boolean result = new DefaultStaticContentHandler(context).requestingStaticFile(request); assertThat(result, is(equalTo(false))); } |
### Question:
DefaultInterceptorHandlerFactory implements InterceptorHandlerFactory { @Override public InterceptorHandler handlerFor(final Class<?> type) { return cachedHandlers.fetch(type, new Supplier<InterceptorHandler>() { @Override public InterceptorHandler get() { if(type.isAnnotationPresent(Intercepts.class) && !Interceptor.class.isAssignableFrom(type)){ return new AspectStyleInterceptorHandler(type, stepInvoker, container, customAcceptsExecutor, acceptsExecutor, interceptorExecutor); } return new ToInstantiateInterceptorHandler(container, type, executeMethodExceptionHandler); } }); } protected DefaultInterceptorHandlerFactory(); @Inject DefaultInterceptorHandlerFactory(Container container, StepInvoker stepInvoker,
CacheStore<Class<?>, InterceptorHandler> cachedHandlers, InterceptorAcceptsExecutor acceptsExecutor,
CustomAcceptsExecutor customAcceptsExecutor, InterceptorExecutor interceptorExecutor,
ExecuteMethodExceptionHandler executeMethodExceptionHandler); @Override InterceptorHandler handlerFor(final Class<?> type); }### Answer:
@Test public void handlerForRegularInterceptorsShouldBeDynamic() throws Exception { assertThat(factory.handlerFor(RegularInterceptor.class), is(instanceOf(ToInstantiateInterceptorHandler.class))); }
@Test public void handlerForAspectStyleInterceptorsShouldBeDynamic() throws Exception { assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(instanceOf(AspectStyleInterceptorHandler.class))); }
@Test public void aspectStyleHandlersShouldBeCached() throws Exception { InterceptorHandler handler = factory.handlerFor(AspectStyleInterceptor.class); assertThat(factory.handlerFor(AspectStyleInterceptor.class), is(sameInstance(handler))); } |
### Question:
ReplicatorOutjector implements Outjector { @Override public void outjectRequestMap() { for (ValuedParameter vparameter : methodInfo.getValuedParameters()) { result.include(vparameter.getName(), vparameter.getValue()); } } protected ReplicatorOutjector(); @Inject ReplicatorOutjector(Result result, MethodInfo method); @Override void outjectRequestMap(); }### Answer:
@Test public void shouldReplicateMethodParametersToNextRequest() throws Exception { methodInfo.setParameter(0, 1); methodInfo.setParameter(1, 2.0); methodInfo.setParameter(2, 3l); outjector.outjectRequestMap(); verify(result).include("first", 1); verify(result).include("second", 2.0); verify(result).include("third", 3l); } |
### Question:
DefaultValidator extends AbstractValidator { @Override public Validator add(Message message) { message.setBundle(bundle); messages.add(message); return this; } protected DefaultValidator(); @Inject DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier,
ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale,
Messages messages); @Override Validator check(boolean condition, Message message); @Override Validator ensure(boolean expression, Message message); @Override Validator addIf(boolean expression, Message message); @Override Validator validate(Object object, Class<?>... groups); @Override Validator validate(String alias, Object object, Class<?>... groups); @Override Validator add(Message message); @Override Validator addAll(Collection<? extends Message> messages); @Override Validator addAll(Set<ConstraintViolation<T>> errors); @Override Validator addAll(String alias, Set<ConstraintViolation<T>> errors); @Override T onErrorUse(Class<T> view); @Override boolean hasErrors(); @Override List<Message> getErrors(); }### Answer:
@Test public void outjectsTheRequestParameters() { try { validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); } catch (ValidationException e) { } verify(outjector).outjectRequestMap(); }
@Test public void addsTheErrorsOnTheResult() { try { validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); } catch (ValidationException e) { } verify(result).include(eq("errors"), argThat(is(not(empty())))); }
@Test public void forwardToCustomOnErrorPage() { try { when(logicResult.forwardTo(MyComponent.class)).thenReturn(instance); validator.add(A_MESSAGE); validator.onErrorForwardTo(MyComponent.class).logic(); fail("should stop flow"); } catch (ValidationException e) { verify(instance).logic(); } } |
### Question:
DefaultValidator extends AbstractValidator { @Override public List<Message> getErrors() { return messages.getErrors(); } protected DefaultValidator(); @Inject DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier,
ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale,
Messages messages); @Override Validator check(boolean condition, Message message); @Override Validator ensure(boolean expression, Message message); @Override Validator addIf(boolean expression, Message message); @Override Validator validate(Object object, Class<?>... groups); @Override Validator validate(String alias, Object object, Class<?>... groups); @Override Validator add(Message message); @Override Validator addAll(Collection<? extends Message> messages); @Override Validator addAll(Set<ConstraintViolation<T>> errors); @Override Validator addAll(String alias, Set<ConstraintViolation<T>> errors); @Override T onErrorUse(Class<T> view); @Override boolean hasErrors(); @Override List<Message> getErrors(); }### Answer:
@Test public void shouldNotRedirectIfHasNotErrors() { try { validator.onErrorRedirectTo(MyComponent.class).logic(); assertThat(validator.getErrors(), hasSize(0)); verify(outjector, never()).outjectRequestMap(); } catch (ValidationException e) { fail("no error occurs"); } } |
### Question:
DefaultValidator extends AbstractValidator { @Override public Validator addAll(Collection<? extends Message> messages) { for (Message message : messages) { add(message); } return this; } protected DefaultValidator(); @Inject DefaultValidator(Result result, ValidationViewsFactory factory, Outjector outjector, Proxifier proxifier,
ResourceBundle bundle, javax.validation.Validator bvalidator, MessageInterpolator interpolator, Locale locale,
Messages messages); @Override Validator check(boolean condition, Message message); @Override Validator ensure(boolean expression, Message message); @Override Validator addIf(boolean expression, Message message); @Override Validator validate(Object object, Class<?>... groups); @Override Validator validate(String alias, Object object, Class<?>... groups); @Override Validator add(Message message); @Override Validator addAll(Collection<? extends Message> messages); @Override Validator addAll(Set<ConstraintViolation<T>> errors); @Override Validator addAll(String alias, Set<ConstraintViolation<T>> errors); @Override T onErrorUse(Class<T> view); @Override boolean hasErrors(); @Override List<Message> getErrors(); }### Answer:
@Test public void testThatValidatorGoToRedirectsToTheErrorPageImmediatellyAndNotBeforeThis() { try { validator.addAll(Arrays.asList(new SimpleMessage("test", "test"))); when(pageResult.of(MyComponent.class)).thenReturn(instance); validator.onErrorUsePageOf(MyComponent.class).logic(); fail("should stop flow"); } catch (ValidationException e) { verify(instance).logic(); } } |
### Question:
Messages implements Serializable { public void assertAbsenceOfErrors() { if (hasUnhandledErrors()) { log.debug("Some validation errors occured: {}", getErrors()); throw new ValidationFailedException( "There are validation errors and you forgot to specify where to go. Please add in your method " + "something like:\n" + "validator.onErrorUse(page()).of(AnyController.class).anyMethod();\n" + "or any view that you like.\n" + "If you didn't add any validation error, it is possible that a conversion error had happened."); } } Messages add(Message message); List<Message> getErrors(); List<Message> getInfo(); List<Message> getWarnings(); List<Message> getSuccess(); List<Message> getAll(); List<Message> handleErrors(); boolean hasUnhandledErrors(); void assertAbsenceOfErrors(); }### Answer:
@Test public void shouldNotThrowExceptionIfMessagesHasNoErrors() { messages.assertAbsenceOfErrors(); } |
### Question:
Messages implements Serializable { public Messages add(Message message) { get(message.getSeverity()).add(message); if(Severity.ERROR.equals(message.getSeverity())) { unhandledErrors = true; } return this; } Messages add(Message message); List<Message> getErrors(); List<Message> getInfo(); List<Message> getWarnings(); List<Message> getSuccess(); List<Message> getAll(); List<Message> handleErrors(); boolean hasUnhandledErrors(); void assertAbsenceOfErrors(); }### Answer:
@Test public void testElExpressionGettingMessagesByCaegory() { messages.add(new SimpleMessage("client.id", "will generated", Severity.INFO)); messages.add(new SimpleMessage("client.name", "not null")); messages.add(new SimpleMessage("client.name", "not empty")); ELProcessor el = new ELProcessor(); el.defineBean("messages", messages); String result = el.eval("messages.errors.from('client.name')").toString(); assertThat(result, is("not null, not empty")); result = el.eval("messages.errors.from('client.name').join(' - ')").toString(); assertThat(result, is("not null - not empty")); result = el.eval("messages.errors.from('client.id')").toString(); assertThat(result, isEmptyString()); result = el.eval("messages.info.from('client.id')").toString(); assertThat(result, is("will generated")); } |
### Question:
DateConverter implements Converter<Date> { @Override public Date convert(String value, Class<? extends Date> type) { if (isNullOrEmpty(value)) { return null; } try { return getDateFormat().parse(value); } catch (ParseException pe) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected DateConverter(); @Inject DateConverter(Locale locale); @Override Date convert(String value, Class<? extends Date> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvert() throws ParseException { assertThat(converter.convert("10/06/2008", Date.class), is(equalTo(new SimpleDateFormat("dd/MM/yyyy") .parse("10/06/2008")))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Date.class), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Date.class), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("a,10/06/2008/a/b/c is not a valid date.")); converter.convert("a,10/06/2008/a/b/c", Date.class); } |
### Question:
PrimitiveLongConverter implements Converter<Long> { @Override public Long convert(String value, Class<? extends Long> type) { if (isNullOrEmpty(value)) { return 0L; } try { return Long.parseLong(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Long convert(String value, Class<? extends Long> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", long.class), is(equalTo(2L))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", long.class); }
@Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, long.class), is(equalTo(0L))); }
@Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", long.class), is(equalTo(0L))); } |
### Question:
PrimitiveBooleanConverter implements Converter<Boolean> { @Override public Boolean convert(String value, Class<? extends Boolean> type) { if (isNullOrEmpty(value)) { return false; } return booleanConverter.convert(value, type); } protected PrimitiveBooleanConverter(); @Inject PrimitiveBooleanConverter(BooleanConverter converter); @Override Boolean convert(String value, Class<? extends Boolean> type); }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("", boolean.class), is(equalTo(false))); assertThat(converter.convert("false", boolean.class), is(equalTo(false))); assertThat(converter.convert("true", boolean.class), is(equalTo(true))); assertThat(converter.convert("True", boolean.class), is(equalTo(true))); }
@Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, boolean.class), is(equalTo(false))); }
@Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", boolean.class), is(equalTo(false))); }
@Test public void shouldConvertYesNo() { assertThat(converter.convert("yes", boolean.class), is(equalTo(true))); assertThat(converter.convert("no", boolean.class), is(equalTo(false))); }
@Test public void shouldConvertYN() { assertThat(converter.convert("y", boolean.class), is(equalTo(true))); assertThat(converter.convert("n", boolean.class), is(equalTo(false))); }
@Test public void shouldConvertOnOff() { assertThat(converter.convert("on", boolean.class), is(equalTo(true))); assertThat(converter.convert("off", boolean.class), is(equalTo(false))); }
@Test public void shouldConvertIgnoringCase() { assertThat(converter.convert("truE", boolean.class), is(equalTo(true))); assertThat(converter.convert("FALSE", boolean.class), is(equalTo(false))); assertThat(converter.convert("On", boolean.class), is(equalTo(true))); assertThat(converter.convert("oFf", boolean.class), is(equalTo(false))); }
@Test public void shouldThrowExceptionForInvalidString() { exception.expect(hasConversionException("NOT A BOOLEAN! is not a valid boolean. Please use true/false, yes/no, y/n or on/off")); converter.convert("not a boolean!", boolean.class); } |
### Question:
CalendarConverter implements Converter<Calendar> { @Override public Calendar convert(String value, Class<? extends Calendar> type) { if (isNullOrEmpty(value)) { return null; } try { Date date = getDateFormat().parse(value); Calendar calendar = Calendar.getInstance(locale); calendar.setTime(date); return calendar; } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected CalendarConverter(); @Inject CalendarConverter(Locale locale); @Override Calendar convert(String value, Class<? extends Calendar> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvert() { Calendar expected = Calendar.getInstance(new Locale("pt", "BR")); expected.set(2008, 5, 10, 0, 0, 0); expected.set(Calendar.MILLISECOND, 0); assertThat(converter.convert("10/06/2008", Calendar.class), is(equalTo(expected))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Calendar.class), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Calendar.class), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("a,10/06/2008/a/b/c is not a valid date.")); converter.convert("a,10/06/2008/a/b/c", Calendar.class); } |
### Question:
PrimitiveByteConverter implements Converter<Byte> { @Override public Byte convert(String value, Class<? extends Byte> type) { if (isNullOrEmpty(value)) { return (byte) 0; } try { return Byte.parseByte(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Byte convert(String value, Class<? extends Byte> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("7", byte.class), is(equalTo((byte) 7))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", byte.class); }
@Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, byte.class), is(equalTo((byte) 0))); }
@Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", byte.class), is(equalTo((byte) 0))); } |
### Question:
LongConverter implements Converter<Long> { @Override public Long convert(String value, Class<? extends Long> type) { if (isNullOrEmpty(value)) { return null; } try { return Long.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Long convert(String value, Class<? extends Long> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers(){ assertThat(converter.convert("2", long.class), is(equalTo(2L))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", long.class); }
@Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, long.class), is(nullValue())); }
@Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", long.class), is(nullValue())); } |
### Question:
PrimitiveFloatConverter implements Converter<Float> { @Override public Float convert(String value, Class<? extends Float> type) { if (isNullOrEmpty(value)) { return 0f; } try { return getNumberFormat().parse(value).floatValue(); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected PrimitiveFloatConverter(); @Inject PrimitiveFloatConverter(Locale locale); @Override Float convert(String value, Class<? extends Float> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", float.class), is(equalTo(Float.parseFloat("10.00")))); assertThat(converter.convert("10,01", float.class), is(equalTo(Float.parseFloat("10.01")))); }
@Test public void shouldBeAbleToConvertWithENUS() { converter = new PrimitiveFloatConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", float.class), is(equalTo(Float.parseFloat("10.00")))); assertThat(converter.convert("10.01", float.class), is(equalTo(Float.parseFloat("10.01")))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", float.class), is(equalTo(0f))); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, float.class), is(equalTo(0f))); }
@Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", float.class); } |
### Question:
CharacterConverter implements Converter<Character> { @Override public Character convert(String value, Class<? extends Character> type) { if (isNullOrEmpty(value)) { return null; } if (value.length() != 1) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } return value.charAt(0); } @Override Character convert(String value, Class<? extends Character> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertCharacters() { assertThat(converter.convert("Z", Character.class), is(equalTo('Z'))); }
@Test public void shouldComplainAboutStringTooBig() { exception.expect(hasConversionException("--- is not a valid character.")); converter.convert("---", Character.class); }
@Test public void shouldNotComplainAboutNullAndEmpty() { assertThat(converter.convert(null, Character.class), is(nullValue())); assertThat(converter.convert("", Character.class), is(nullValue())); } |
### Question:
PrimitiveShortConverter implements Converter<Short> { @Override public Short convert(String value, Class<? extends Short> type) { if (isNullOrEmpty(value)) { return (short) 0; } try { return Short.parseShort(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Short convert(String value, Class<? extends Short> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers(){ assertThat(converter.convert("5", short.class), is(equalTo((short) 5))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", short.class); }
@Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, short.class), is(equalTo((short) 0))); }
@Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", short.class), is(equalTo((short) 0))); } |
### Question:
PrimitiveIntConverter implements Converter<Integer> { @Override public Integer convert(String value, Class<? extends Integer> type) { if (isNullOrEmpty(value)) { return 0; } try { return Integer.parseInt(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Integer convert(String value, Class<? extends Integer> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", int.class), is(equalTo(2))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", int.class); }
@Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, int.class), is(equalTo(0))); }
@Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", int.class), is(equalTo(0))); } |
### Question:
ByteConverter implements Converter<Byte> { @Override public Byte convert(String value, Class<? extends Byte> type) { if (isNullOrEmpty(value)) { return null; } try { return Byte.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Byte convert(String value, Class<? extends Byte> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", Byte.class), is(equalTo((byte) 2))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", Byte.class); }
@Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, Byte.class), is(nullValue())); }
@Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", Byte.class), is(nullValue())); } |
### Question:
PrimitiveCharConverter implements Converter<Character> { @Override public Character convert(String value, Class<? extends Character> type) { if (isNullOrEmpty(value)) { return '\u0000'; } if (value.length() != 1) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } return value.charAt(0); } @Override Character convert(String value, Class<? extends Character> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("r", char.class), is(equalTo('r'))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid character.")); converter.convert("---", char.class); }
@Test public void shouldConvertToZeroWhenNull() { assertThat(converter.convert(null, char.class), is(equalTo('\u0000'))); }
@Test public void shouldConvertToZeroWhenEmpty() { assertThat(converter.convert("", char.class), is(equalTo('\u0000'))); } |
### Question:
BigDecimalConverter implements Converter<BigDecimal> { @Override public BigDecimal convert(String value, Class<? extends BigDecimal> type) { if (isNullOrEmpty(value)) { return null; } try { return (BigDecimal) getNumberFormat().parse(value); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected BigDecimalConverter(); @Inject BigDecimalConverter(Locale locale); @Override BigDecimal convert(String value, Class<? extends BigDecimal> type); }### Answer:
@Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", BigDecimal.class), is(equalTo(new BigDecimal("10.00")))); assertThat(converter.convert("10,01", BigDecimal.class), is(equalTo(new BigDecimal("10.01")))); }
@Test public void shouldBeAbleToConvertWithENUS() { converter = new BigDecimalConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", BigDecimal.class), is(equalTo(new BigDecimal("10.00")))); assertThat(converter.convert("10.01", BigDecimal.class), is(equalTo(new BigDecimal("10.01")))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", BigDecimal.class), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, BigDecimal.class), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", BigDecimal.class); } |
### Question:
IntegerConverter implements Converter<Integer> { @Override public Integer convert(String value, Class<? extends Integer> type) { if (isNullOrEmpty(value)) { return null; } try { return Integer.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Integer convert(String value, Class<? extends Integer> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", Integer.class), is(equalTo(2))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", Integer.class); }
@Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, Integer.class), is(nullValue())); }
@Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", Integer.class), is(nullValue())); } |
### Question:
BigIntegerConverter implements Converter<BigInteger> { @Override public BigInteger convert(String value, Class<? extends BigInteger> type) { if (isNullOrEmpty(value)) { return null; } try { return new BigInteger(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override BigInteger convert(String value, Class<? extends BigInteger> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertIntegerNumbers() { assertThat(converter.convert("3", BigInteger.class), is(equalTo(new BigInteger("3")))); }
@Test public void shouldComplainAboutNonIntegerNumbers() { exception.expect(hasConversionException("2.3 is not a valid number.")); converter.convert("2.3", BigInteger.class); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", BigInteger.class); }
@Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, BigInteger.class), is(nullValue())); }
@Test public void shouldNotComplainAboutEmpty() { assertThat(converter.convert("", BigInteger.class), is(nullValue())); } |
### Question:
DoubleConverter implements Converter<Double> { @Override public Double convert(String value, Class<? extends Double> type) { if (isNullOrEmpty(value)) { return null; } try { return getNumberFormat().parse(value).doubleValue(); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected DoubleConverter(); @Inject DoubleConverter(Locale locale); @Override Double convert(String value, Class<? extends Double> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", Double.class), is(equalTo(new Double("10.00")))); assertThat(converter.convert("10,01", Double.class), is(equalTo(new Double("10.01")))); }
@Test public void shouldBeAbleToConvertWithENUS() { converter = new DoubleConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", Double.class), is(equalTo(new Double("10.00")))); assertThat(converter.convert("10.01", Double.class), is(equalTo(new Double("10.01")))); }
@Test public void shouldBeAbleToConvertWithGroupingAndPTBR() { assertThat(converter.convert("1.000.000,00", Double.class), is(equalTo(new Double("1000000.00")))); assertThat(converter.convert("1.001.000,01", Double.class), is(equalTo(new Double("1001000.01")))); }
@Test public void shouldBeAbleToConvertWithGroupingAndENUS() { converter = new DoubleConverter(new Locale("en", "US")); assertThat(converter.convert("1,000,000.00", Double.class), is(equalTo(new Double("1000000.00")))); assertThat(converter.convert("1,001,000.01", Double.class), is(equalTo(new Double("1001000.01")))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Double.class), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Double.class), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", Double.class); } |
### Question:
BooleanConverter implements Converter<Boolean> { @Override public Boolean convert(String value, Class<? extends Boolean> type) { if (isNullOrEmpty(value)) { return null; } value = value.toUpperCase(); if (matches(IS_TRUE, value)) { return true; } else if (matches(IS_FALSE, value)) { return false; } throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } @Override Boolean convert(String value, Class<? extends Boolean> type); }### Answer:
@Test public void shouldBeAbleToConvertTrueAndFalse(){ assertThat(converter.convert("true", Boolean.class), is(equalTo(true))); assertThat(converter.convert("false", Boolean.class), is(equalTo(false))); }
@Test public void shouldConvertEmptyToNull() { assertThat(converter.convert("", Boolean.class), is(nullValue())); }
@Test public void shouldNotComplainAboutNull() { assertThat(converter.convert(null, Boolean.class), is(nullValue())); }
@Test public void shouldConvertYesNo() { assertThat(converter.convert("yes", Boolean.class), is(equalTo(true))); assertThat(converter.convert("no", Boolean.class), is(equalTo(false))); }
@Test public void shouldConvertYN() { assertThat(converter.convert("y", Boolean.class), is(equalTo(true))); assertThat(converter.convert("n", Boolean.class), is(equalTo(false))); }
@Test public void shouldConvertOnOff() { assertThat(converter.convert("on", Boolean.class), is(equalTo(true))); assertThat(converter.convert("off", Boolean.class), is(equalTo(false))); }
@Test public void shouldConvertIgnoringCase() { assertThat(converter.convert("truE", Boolean.class), is(equalTo(true))); assertThat(converter.convert("FALSE", Boolean.class), is(equalTo(false))); assertThat(converter.convert("On", Boolean.class), is(equalTo(true))); assertThat(converter.convert("oFf", Boolean.class), is(equalTo(false))); }
@Test public void shouldThrowExceptionForInvalidString() { exception.expect(hasConversionException("NOT A BOOLEAN! is not a valid boolean. Please use true/false, yes/no, y/n or on/off")); converter.convert("not a boolean!", Boolean.class); } |
### Question:
FloatConverter implements Converter<Float> { @Override public Float convert(String value, Class<? extends Float> type) { if (isNullOrEmpty(value)) { return null; } try { return getNumberFormat().parse(value).floatValue(); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } protected FloatConverter(); @Inject FloatConverter(Locale locale); @Override Float convert(String value, Class<? extends Float> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", Float.class), is(equalTo(new Float("10.00")))); assertThat(converter.convert("10,01", Float.class), is(equalTo(new Float("10.01")))); }
@Test public void shouldBeAbleToConvertWithENUS() { converter = new FloatConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", Float.class), is(equalTo(new Float("10.00")))); assertThat(converter.convert("10.01", Float.class), is(equalTo(new Float("10.01")))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", Float.class), is(nullValue())); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, Float.class), is(nullValue())); }
@Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", Float.class); } |
### Question:
ShortConverter implements Converter<Short> { @Override public Short convert(String value, Class<? extends Short> type) { if (isNullOrEmpty(value)) { return null; } try { return Short.valueOf(value); } catch (NumberFormatException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } @Override Short convert(String value, Class<? extends Short> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertNumbers() { assertThat(converter.convert("2", Short.class), is(equalTo((short) 2))); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("--- is not a valid number.")); converter.convert("---", Short.class); }
@Test public void shouldComplainAboutNull() { assertThat(converter.convert(null, Short.class), is(nullValue())); }
@Test public void shouldComplainAboutEmpty() { assertThat(converter.convert("", Short.class), is(nullValue())); } |
### Question:
EnumConverter implements Converter { @Override public Object convert(String value, Class type) { if (isNullOrEmpty(value)) { return null; } if (Character.isDigit(value.charAt(0))) { return resolveByOrdinal(value, type); } else { return resolveByName(value, type); } } @Override Object convert(String value, Class type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertByOrdinal() { Enum value = converter.convert("1", MyCustomEnum.class); MyCustomEnum second = MyCustomEnum.SECOND; assertEquals(value, second); }
@Test public void shouldBeAbleToConvertByName() { Enum value = converter.convert("FIRST", MyCustomEnum.class); MyCustomEnum first = MyCustomEnum.FIRST; assertEquals(value, first); }
@Test public void shouldConvertEmptyToNull() { assertThat(converter.convert("", MyCustomEnum.class), is(nullValue())); }
@Test public void shouldComplainAboutInvalidIndex() { exception.expect(hasConversionException("3200 is not a valid option.")); converter.convert("3200", MyCustomEnum.class); }
@Test public void shouldComplainAboutInvalidNumber() { exception.expect(hasConversionException("32a00 is not a valid option.")); converter.convert("32a00", MyCustomEnum.class); }
@Test public void shouldComplainAboutInvalidOrdinal() { exception.expect(hasConversionException("THIRD is not a valid option.")); converter.convert("THIRD", MyCustomEnum.class); }
@Test public void shouldAcceptNull() { assertThat(converter.convert(null, MyCustomEnum.class), is(nullValue())); } |
### Question:
PrimitiveDoubleConverter implements Converter<Double> { @Override public Double convert(String value, Class<? extends Double> type) { if (isNullOrEmpty(value)) { return 0d; } try { return getNumberFormat().parse(value).doubleValue(); } catch (ParseException e) { throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value)); } } PrimitiveDoubleConverter(); @Inject PrimitiveDoubleConverter(Locale locale); @Override Double convert(String value, Class<? extends Double> type); static final String INVALID_MESSAGE_KEY; }### Answer:
@Test public void shouldBeAbleToConvertWithPTBR() { assertThat(converter.convert("10,00", double.class), is(equalTo(Double.parseDouble("10.00")))); assertThat(converter.convert("10,01", double.class), is(equalTo(Double.parseDouble("10.01")))); }
@Test public void shouldBeAbleToConvertWithENUS() { converter = new PrimitiveDoubleConverter(new Locale("en", "US")); assertThat(converter.convert("10.00", double.class), is(equalTo(Double.parseDouble("10.00")))); assertThat(converter.convert("10.01", double.class), is(equalTo(Double.parseDouble("10.01")))); }
@Test public void shouldBeAbleToConvertWithGroupingAndPTBR() { assertThat(converter.convert("1.000.000,00", double.class), is(equalTo(Double.parseDouble("1000000.00")))); assertThat(converter.convert("1.001.000,01", double.class), is(equalTo(Double.parseDouble("1001000.01")))); }
@Test public void shouldBeAbleToConvertWithGroupingAndENUS() { converter = new PrimitiveDoubleConverter(new Locale("en", "US")); assertThat(converter.convert("1,000,000.00", double.class), is(equalTo(Double.parseDouble("1000000.00")))); assertThat(converter.convert("1,001,000.01", double.class), is(equalTo(Double.parseDouble("1001000.01")))); }
@Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", double.class), is(equalTo(0d))); }
@Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, double.class), is(equalTo(0d))); }
@Test public void shouldThrowExceptionWhenUnableToParse() { exception.expect(hasConversionException("vr3.9 is not a valid number.")); converter.convert("vr3.9", double.class); } |
### Question:
HomeController { @Post @Public public void login(String login, String password) { final User currentUser = dao.find(login, password); validator.check(currentUser != null, new SimpleMessage("login", "invalid_login_or_password")); validator.onErrorUsePageOf(this).login(); userInfo.login(currentUser); result.redirectTo(UsersController.class).home(); } protected HomeController(); @Inject HomeController(UserDao dao, UserInfo userInfo, Result result, Validator validator); @Post @Public void login(String login, String password); void logout(); @Public @Get void login(); @Public @Get void about(); }### Answer:
@Test public void shouldLoginWhenUserExists() { when(dao.find(user.getLogin(), user.getPassword())).thenReturn(user); controller.login(user.getLogin(), user.getPassword()); assertThat(validator.getErrors(), empty()); }
@Test(expected=ValidationException.class) public void shouldNotLoginWhenUserDoesNotExists() { when(dao.find(user.getLogin(), user.getPassword())).thenReturn(null); controller.login(user.getLogin(), user.getPassword()); }
@Test public void shouldNotLoginWhenUserDoesNotExistsAndHasOneError() { when(dao.find(user.getLogin(), user.getPassword())).thenReturn(null); try { controller.login(user.getLogin(), user.getPassword()); fail("Should throw an exception."); } catch (ValidationException e) { List<Message> errors = e.getErrors(); assertThat(errors, hasSize(1)); assertTrue(errors.contains(new SimpleMessage("login", "invalid_login_or_password"))); } } |
### Question:
HomeController { public void logout() { userInfo.logout(); result.redirectTo(this).login(); } protected HomeController(); @Inject HomeController(UserDao dao, UserInfo userInfo, Result result, Validator validator); @Post @Public void login(String login, String password); void logout(); @Public @Get void login(); @Public @Get void about(); }### Answer:
@Test public void shouldLogoutUser() { controller.logout(); verify(userInfo).logout(); } |
### Question:
UsersController { @Get("/") public void home() { result.include("musicTypes", MusicType.values()); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator,
UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer:
@Test public void shouldOpenHomeWithMusicTypes() { controller.home(); MusicType[] musicsType = (MusicType[]) result.included().get("musicTypes"); assertThat(Arrays.asList(musicsType), hasSize(MusicType.values().length)); } |
### Question:
UsersController { @Get("/users") public void list() { result.include("users", userDao.listAll()); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator,
UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer:
@SuppressWarnings("unchecked") @Test public void shouldListAllUsers() { when(userDao.listAll()).thenReturn(Arrays.asList(user, anotherUser)); controller.list(); assertThat((List<User>)result.included().get("users"), contains(user, anotherUser)); } |
### Question:
UsersController { @Path("/users") @Post @Public public void add(@Valid @LoginAvailable User user) { validator.onErrorUsePageOf(HomeController.class).login(); userDao.add(user); result.include("notice", "User " + user.getName() + " successfully added"); result.redirectTo(HomeController.class).login(); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator,
UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer:
@Test public void shouldAddUser() { controller.add(user); verify(userDao).add(user); assertThat(result.included().get("notice").toString(), is("User " + user.getName() + " successfully added")); } |
### Question:
UsersController { @Path("/users/{user.login}") @Get public void show(User user) { result.include("user", userDao.find(user.getLogin())); result.forwardTo("/WEB-INF/jsp/users/view.jsp"); } protected UsersController(); @Inject UsersController(UserDao dao, Result result, Validator validator,
UserInfo userInfo, MusicDao musicDao); @Get("/") void home(); @Get("/users") void list(); @Path("/users") @Post @Public void add(@Valid @LoginAvailable User user); @Path("/users/{user.login}") @Get void show(User user); @Path("/users/{user.login}/musics/{music.id}") @Put void addToMyList(User user, Music music); }### Answer:
@Test public void shouldShowUser() { when(userDao.find(user.getLogin())).thenReturn(user); controller.show(user); assertThat((User) result.included().get("user"), is(user)); } |
### Question:
MusicController { @Path("/musics") @Post public void add(final @NotNull @Valid Music music, UploadedFile file) { validator.onErrorForwardTo(UsersController.class).home(); musicDao.add(music); User currentUser = userInfo.getUser(); userDao.refresh(currentUser); currentUser.add(music); if (file != null) { musics.save(file, music); logger.info("Uploaded file: {}", file.getFileName()); } result.include("notice", music.getTitle() + " music added"); result.redirectTo(UsersController.class).home(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@Test public void shouldAddMusic() { when(userInfo.getUser()).thenReturn(user); controller.add(music, uploadFile); verify(dao).add(music); verify(musics).save(uploadFile, music); assertThat(result.included().get("notice").toString(), is(music.getTitle() + " music added")); } |
### Question:
MusicController { @Path("/musics/{music.id}") @Get public void show(Music music) { result.include("music", musicDao.load(music)); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@Test public void shouldShowMusicWhenExists() { when(dao.load(music)).thenReturn(music); controller.show(music); assertNotNull(result.included().get("music")); assertThat((Music) result.included().get("music"), is(music)); }
@Test public void shouldNotShowMusicWhenDoesNotExists() { when(dao.load(music)).thenReturn(null); controller.show(music); assertNull(result.included().get("music")); } |
### Question:
VRaptorRequest extends HttpServletRequestWrapper implements MutableRequest { @Override public String getRequestedUri() { if (getAttribute(INCLUDE_REQUEST_URI) != null) { return (String) getAttribute(INCLUDE_REQUEST_URI); } String uri = getRelativeRequestURI(this); return uri.replaceFirst("(?i);jsessionid=.*$", ""); } VRaptorRequest(HttpServletRequest request); @Override String getParameter(String name); @Override Enumeration<String> getParameterNames(); @Override String[] getParameterValues(String name); @Override Map<String, String[]> getParameterMap(); @Override void setParameter(String key, String... value); @Override String getRequestedUri(); static String getRelativeRequestURI(HttpServletRequest request); @Override String toString(); }### Answer:
@Test public void strippsContextPath() { when(request.getContextPath()).thenReturn("/myapp"); when(request.getRequestURI()).thenReturn("/myapp/somepage"); assertThat(vraptor.getRequestedUri(), is(equalTo("/somepage"))); }
@Test public void strippsRootContextPath() { when(request.getContextPath()).thenReturn("/"); when(request.getRequestURI()).thenReturn("/somepage"); assertThat(vraptor.getRequestedUri(), is(equalTo("/somepage"))); } |
### Question:
MusicController { @Get("/musics/search") public void search(Music music) { String title = MoreObjects.firstNonNull(music.getTitle(), ""); result.include("musics", this.musicDao.searchSimilarTitle(title)); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@SuppressWarnings("unchecked") @Test public void shouldReturnMusicList() { when(dao.searchSimilarTitle(music.getTitle())).thenReturn(Arrays.asList(music)); controller.search(music); assertThat((List<Music>) result.included().get("musics"), contains(music)); }
@SuppressWarnings("unchecked") @Test public void shouldReturnEmptyList() { when(dao.searchSimilarTitle(music.getTitle())).thenReturn(new ArrayList<Music>()); controller.search(music); List<Music> musics = (List<Music>) result.included().get("musics"); assertThat(musics, empty()); } |
### Question:
MusicController { @Path("/musics/download/{m.id}") @Get public Download download(Music m) throws FileNotFoundException { Music music = musicDao.load(m); File file = musics.getFile(music); String contentType = "audio/mpeg"; String filename = music.getTitle() + ".mp3"; return new FileDownload(file, contentType, filename); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@Test public void shouldNotDownloadMusicWhenDoesNotExist() { when(dao.load(music)).thenReturn(music); when(musics.getFile(music)).thenReturn(new File("/tmp/uploads/Music_" + music.getId() + ".mp3")); try { controller.download(music); fail("Should throw an exception."); } catch (FileNotFoundException e) { verify(musics).getFile(music); } } |
### Question:
MusicController { @Public @Path("/musics/list/json") public void showAllMusicsAsJSON() { result.use(json()).from(musicDao.listAll()).serialize(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@Test public void shouldShowAllMusicsAsJSON() throws Exception { when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsJSON(); assertThat(result.serializedResult(), is("{\"list\":[{\"id\":1,\"title\":\"Some Music\"," + "\"description\":\"Some description\",\"type\":\"ROCK\"}]}")); } |
### Question:
MusicController { @Public @Path("/musics/list/xml") public void showAllMusicsAsXML() { result.use(xml()).from(musicDao.listAll()).serialize(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@Test public void shouldShowAllMusicsAsXML() throws Exception { when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsXML(); assertThat(result.serializedResult(), is("<list><music><id>1</id><title>Some Music</title><description>Some description</description><type>ROCK</type></music></list>")); } |
### Question:
MusicController { @Public @Path("/musics/list/http") public void showAllMusicsAsHTTP() { result.use(http()).body("<p class=\"content\">"+ musicDao.listAll().toString()+"</p>"); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@Test public void shouldShowAllMusicsAsHTTP() { MockHttpResult mockHttpResult = new MockHttpResult(); controller = new MusicController(dao, userInfo, mockHttpResult, validator, musics, userDao); when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.showAllMusicsAsHTTP(); assertThat(mockHttpResult.getBody(), is("<p class=\"content\">"+ Arrays.asList(music).toString()+"</p>")); } |
### Question:
MusicController { @Public @Path("musics/listAs") public void listAs() { result.use(representation()) .from(musicDao.listAll()).serialize(); } protected MusicController(); @Inject MusicController(MusicDao musicDao, UserInfo userInfo,
Result result, Validator validator, Musics musics, UserDao userDao); @Path("/musics") @Post void add(final @NotNull @Valid Music music, UploadedFile file); @Path("/musics/{music.id}") @Get void show(Music music); @Get("/musics/search") void search(Music music); @Path("/musics/download/{m.id}") @Get Download download(Music m); @Public @Path("/musics/list/json") void showAllMusicsAsJSON(); @Public @Path("/musics/list/xml") void showAllMusicsAsXML(); @Public @Path("/musics/list/http") void showAllMusicsAsHTTP(); @Public @Path("/musics/list/form") void listForm(); @Public @Path("musics/listAs") void listAs(); }### Answer:
@Test public void shouldListAs() throws Exception { when(dao.listAll()).thenReturn(Arrays.asList(music)); controller.listAs(); assertThat(result.serializedResult(), is("<list><music><id>1</id><title>Some Music</title><description>Some description</description><type>ROCK</type></music></list>")); } |
### Question:
Rules { protected final RouteBuilder routeFor(String uri) { RouteBuilder rule = router.builderFor(uri); rule.withPriority(Integer.MIN_VALUE); this.routesToBuild.add(rule); return rule; } Rules(Router router); abstract void routes(); }### Answer:
@Test public void allowsAdditionOfRouteBuildersByDefaultWithNoStrategy() { exception.expect(IllegalRouteException.class); new Rules(router) { @Override public void routes() { routeFor(""); } }; } |
### Question:
JavaEvaluator implements Evaluator { @Override public Object get(Object root, String path) { if (root == null) { return null; } String[] paths = path.split("[\\]\\.]"); Object current = root; for (int i = 1; i < paths.length; i++) { try { current = navigate(current, paths[i]); } catch (Exception e) { throw new VRaptorException("Unable to evaluate expression " + path, e); } if (current == null) { return ""; } } return current; } protected JavaEvaluator(); @Inject JavaEvaluator(ReflectionProvider reflectionProvider); @Override Object get(Object root, String path); }### Answer:
@Test public void shouldInvokeAGetter() { assertThat((Long) evaluator.get(client(1L), "client.id"), is(equalTo(1L))); }
@Test public void shouldInvokeAIs() { Client c = client(1L); c.ugly=true; assertThat((Boolean) evaluator.get(c, "client.ugly"), is(equalTo(true))); }
@Test public void shouldAccessArray() { Client c = client(1L); c.favoriteColors = new String[] {"blue", "red"}; assertThat((String) evaluator.get(c, "client.favoriteColors[1]"), is(equalTo("red"))); }
@Test public void shouldAccessList() { Client c = client(1L); c.emails = Arrays.asList("blue", "red"); assertThat((String) evaluator.get(c, "client.emails[1]"), is(equalTo("red"))); }
@Test public void shouldAccessCollection() { Client c = client(1L); c.favoriteNumbers = new TreeSet<>(Arrays.asList(10, 5)); assertThat((Integer) evaluator.get(c, "client.favoriteNumbers[1]"), is(equalTo(10))); }
@Test public void shouldReturnEmptyStringIfNullWasFoundOnTheWay() { Client c = client(1L); assertThat((String) evaluator.get(c, "client.child.id"), is(equalTo(""))); }
@Test public void shouldReturnEmptyStringIfTheResultIsNull() { Client c = client(null); assertThat((String) evaluator.get(c, "client.id"), is(equalTo(""))); }
@Test public void shouldInvokeAGetterDeclaredOnSuperClass() { Client c = vipClient(1L); assertThat((Long) evaluator.get(c, "client.id"), is(equalTo(1L))); }
@Test public void shouldInvokeAIsDeclaredOnSuperClass() { Client c = vipClient(1L); c.ugly = true; assertThat((Boolean) evaluator.get(c, "client.ugly"), is(equalTo(true))); } |
### Question:
DefaultRouter implements Router { @Override public <T> String urlFor(final Class<T> type, final Method method, Object... params) { final Class<?> rawtype = proxifier.isProxyType(type) ? type.getSuperclass() : type; final Invocation invocation = new Invocation(rawtype, method); Route route = cache.fetch(invocation, new Supplier<Route>() { @Override public Route get() { return FluentIterable.from(routes).filter(canHandle(rawtype, method)) .first().or(NULL); } }); logger.debug("Selected route for {} is {}", method, route); String url = route.urlFor(type, method, params); logger.debug("Returning URL {} for {}", url, route); return url; } protected DefaultRouter(); @Inject DefaultRouter(Proxifier proxifier, TypeFinder finder, Converters converters,
ParameterNameProvider nameProvider, Evaluator evaluator, EncodingHandler encodingHandler,
CacheStore<Invocation, Route> cache); @Override RouteBuilder builderFor(String uri); @Override void add(Route r); @Override ControllerMethod parse(String uri, HttpMethod method, MutableRequest request); @Override EnumSet<HttpMethod> allowedMethodsFor(String uri); @Override String urlFor(final Class<T> type, final Method method, Object... params); @Override List<Route> allRoutes(); }### Answer:
@Test public void shouldReturnTheFirstRouteFound() throws Exception { Method method = MyController.class.getDeclaredMethod("listDogs", Integer.class); registerRulesFor(MyController.class); assertEquals("/dogs/1", router.urlFor(MyController.class, method, new Object[] { "1" })); }
@Test public void canFindUrlForProxyClasses() throws Exception { registerRulesFor(MyController.class); MyController proxy = proxifier.proxify(MyController.class, null); Class<? extends MyController> type = proxy.getClass(); Method method = type.getMethod("notAnnotated"); assertEquals("/my/notAnnotated", router.urlFor(type, method)); } |
### Question:
ParanamerNameProvider implements ParameterNameProvider { @Override public Parameter[] parametersFor(final AccessibleObject executable) { try { String[] names = info.lookupParameterNames(executable); Parameter[] params = new Parameter[names.length]; logger.debug("Found parameter names with paranamer for {} as {}", executable, (Object) names); for (int i = 0; i < names.length; i++) { params[i] = new Parameter(i, names[i], executable); } return defensiveCopy(params); } catch (ParameterNamesNotFoundException e) { throw new IllegalStateException("Paranamer were not able to find your parameter names for " + executable + "You must compile your code with debug information (javac -g), or using @Named on " + "each method parameter.", e); } } @Override Parameter[] parametersFor(final AccessibleObject executable); }### Answer:
@Test public void shouldNameObjectTypeAsItsSimpleName() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Horse.class.getMethod("runThrough", Field.class)); assertThat(toNames(namesFor), contains("f")); }
@Test public void shouldNamePrimitiveTypeAsItsSimpleName() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Horse.class.getMethod("rest", int.class)); assertThat(toNames(namesFor), contains("hours")); }
@Test public void shouldNameArrayAsItsSimpleTypeName() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Horse.class.getMethod("setLeg", int[].class)); assertThat(toNames(namesFor), contains("length")); }
@Test public void shouldNameGenericCollectionUsingOf() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Cat.class.getDeclaredMethod("fightWith", List.class)); assertThat(toNames(namesFor), contains("cats")); }
@Test public void shouldIgnoreChangesToTheReturnedArrayInSubsequentCalls() throws Exception { Parameter[] firstCall = provider.parametersFor(Horse.class.getMethod("setLeg", int[].class)); firstCall[0] = null; Parameter[] secondCall = provider.parametersFor(Horse.class.getMethod("setLeg", int[].class)); assertThat(secondCall[0], notNullValue()); }
@Test public void shouldNameFieldsAnnotatedWithNamed() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Horse.class.getMethod("runThroughWithAnnotation", Field.class)); assertThat(toNames(namesFor), contains("one")); }
@Test public void shouldNotNameFieldsByTheFieldNameWhenUsingAnnotation() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Horse.class.getMethod("runThroughWithAnnotation", Field.class)); assertThat(toNames(namesFor), not(contains("field"))); }
@Test public void shouldNameMethodsFieldsWhenAnnotatedOrNot() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Horse.class.getMethod("runThroughWithAnnotation2", Field.class, Field.class)); assertThat(toNames(namesFor), contains("one", "two")); }
@Test public void shouldNameMethodsFieldsWhenAnnotatedOrNot2() throws SecurityException, NoSuchMethodException { Parameter[] namesFor = provider.parametersFor(Horse.class.getMethod("runThroughWithAnnotation3", Field.class, Field.class)); assertThat(toNames(namesFor), contains("one", "size")); } |
### Question:
AVSessionCacheHelper { static synchronized SessionTagCache getTagCacheInstance() { if (null == tagCacheInstance) { tagCacheInstance = new SessionTagCache(); } return tagCacheInstance; } }### Answer:
@Test public void testRemoveNotExistTag() { AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); AVSessionCacheHelper.getTagCacheInstance().removeSession("test11"); Map<String, String> map = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(map.size() == 1); Assert.assertTrue(testClientTag.equals(map.get(testClientId))); }
@Test public void testRemoveExistTag() { AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); AVSessionCacheHelper.getTagCacheInstance().removeSession(testClientId); Map<String, String> map = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(map.size() == 0); }
@Test public void testTagCacheAdd() { AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); Map<String, String> clientMap = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(clientMap.size() == 1); Assert.assertTrue(testClientTag.equals(clientMap.get(testClientId))); }
@Test public void testUpdateTag() { String updateTag = "updateTag"; AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, testClientTag); AVSessionCacheHelper.getTagCacheInstance().addSession(testClientId, updateTag); Map<String, String> clientMap = AVSessionCacheHelper.getTagCacheInstance().getAllSession(); Assert.assertTrue(clientMap.size() == 1); Assert.assertTrue(updateTag.equals(clientMap.get(testClientId))); } |
### Question:
AVFile { public Object removeMetaData(String key) { return metaData.remove(key); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testRemoveMetaData() { String key = "key"; String value = "value"; AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); Assert.assertTrue(!file.getMetaData().containsKey(key)); file.addMetaData(key, value); Assert.assertEquals(file.getMetaData().get(key), value); file.removeMetaData(key); Assert.assertTrue(!file.getMetaData().containsKey(key)); } |
### Question:
AVFile { public void clearMetaData() { this.metaData.clear(); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testClearMetaData() { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); Assert.assertTrue(!file.getMetaData().isEmpty()); file.clearMetaData(); Assert.assertTrue(file.getMetaData().isEmpty()); } |
### Question:
AVFile { public String getOwnerObjectId() { return (String) getMetaData("owner"); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testGetOwnerObjectId() { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); Assert.assertTrue(AVUtils.isBlankContent(file.getOwnerObjectId())); } |
### Question:
AVFile { public synchronized void saveInBackground(final SaveCallback saveCallback, final ProgressCallback progressCallback) { if (AVUtils.isBlankString(objectId)) { cancelUploadIfNeed(); uploader = getUploader(saveCallback, progressCallback); uploader.execute(); } else { if (null != saveCallback) { saveCallback.internalDone(null); } if (null != progressCallback) { progressCallback.internalDone(100, null); } } } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testSaveInBackground() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); file.saveInBackground(new SaveCallback() { @Override protected boolean mustRunOnUIThread() { return false; } @Override public void done(AVException e) { System.out.println("file saved. objectId=" + file.getObjectId()); System.out.println("url=" + file.getUrl()); Assert.assertNull(e); Assert.assertTrue(file.getObjectId().length() > 0); Assert.assertTrue(file.getUrl().length() > 0); latch.countDown(); } }); latch.await(60, TimeUnit.SECONDS); file.delete(); } |
### Question:
AVFile { @Deprecated static public AVFile parseFileWithObjectId(String objectId) throws AVException, FileNotFoundException { return withObjectId(objectId); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testParseFileWithObjectId() throws Exception { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); file.save(); AVFile newFile = AVFile.parseFileWithObjectId(file.getObjectId()); Assert.assertNotNull(newFile); Assert.assertNotNull(newFile.getObjectId()); Assert.assertNotNull(newFile.getOriginalName()); Assert.assertNotNull(newFile.getBucket()); Assert.assertNotNull(newFile.getMetaData()); file.delete(); } |
### Question:
AVFile { public static AVFile withObjectId(String objectId) throws AVException, FileNotFoundException { AVQuery<AVObject> query = new AVQuery<AVObject>("_File"); AVObject object = query.get(objectId); if (object != null && !AVUtils.isBlankString(object.getObjectId())) { AVFile file = createFileFromAVObject(object); return file; } else { throw new FileNotFoundException("Could not find file object by id:" + objectId); } } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testWithObjectId() throws Exception { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); file.save(); AVFile newFile = AVFile.withObjectId(file.getObjectId()); Assert.assertNotNull(newFile); Assert.assertNotNull(newFile.getObjectId()); Assert.assertNotNull(newFile.getOriginalName()); Assert.assertNotNull(newFile.getBucket()); Assert.assertNotNull(newFile.getMetaData()); file.delete(); } |
### Question:
AVFile { public static AVFile withAVObject(AVObject obj) { if (obj != null && !AVUtils.isBlankString(obj.getObjectId())) { AVFile file = createFileFromAVObject(obj); return file; } else { throw new IllegalArgumentException("Invalid AVObject."); } } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testWithAVObject() throws Exception { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); file.save(); AVQuery<AVObject> query = new AVQuery<AVObject>("_File"); AVObject object = query.get(file.getObjectId()); AVFile newFile = AVFile.withAVObject(object); Assert.assertEquals(file.getOriginalName(), newFile.getOriginalName()); Assert.assertEquals(file.getObjectId(), newFile.getObjectId()); Assert.assertEquals(file.getUrl(), newFile.getUrl()); Assert.assertNotNull(newFile.getBucket()); Assert.assertEquals(file.getMetaData(), newFile.getMetaData()); file.delete(); } |
### Question:
AVFile { public static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath) throws FileNotFoundException { return withFile(name, new File(absoluteLocalFilePath)); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testWithAbsoluteLocalPath() throws Exception { File file = new File(getAVFileCachePath(), "test"); AVPersistenceUtils.saveContentToFile(TEST_FILE_CONTENT, file); AVFile newFile = AVFile.withAbsoluteLocalPath("name", file.getAbsolutePath()); Assert.assertNotNull(newFile); Assert.assertNotNull(newFile.getOriginalName()); Assert.assertNotNull(newFile.getMetaData()); Assert.assertArrayEquals(TEST_FILE_CONTENT.getBytes(), newFile.getData()); } |
### Question:
AVFile { public void delete() throws AVException { if (getFileObject() != null) getFileObject().delete(); else throw AVErrorUtils.createException(AVException.FILE_DELETE_ERROR, "File object is not exists."); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testDelete() throws Exception { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); file.save(); AVFile cloudFile = AVFile.withObjectId(file.getObjectId()); Assert.assertNotNull(cloudFile); Assert.assertEquals(file.getUrl(), cloudFile.getUrl()); file.delete(); AVException exception = null; AVFile deletedFile = null; try { deletedFile = AVFile.withObjectId(file.getObjectId()); } catch (AVException e) { exception = e; } Assert.assertEquals(exception.code, AVException.OBJECT_NOT_FOUND); Assert.assertNull(deletedFile); } |
### Question:
AVFile { public void deleteInBackground() { if (getFileObject() != null) getFileObject().deleteInBackground(); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testDeleteInBackground() throws Exception { AVFile file = new AVFile("name", TEST_FILE_CONTENT.getBytes()); file.save(); AVFile cloudFile = AVFile.withObjectId(file.getObjectId()); Assert.assertNotNull(cloudFile); Assert.assertEquals(file.getUrl(), cloudFile.getUrl()); final CountDownLatch latch = new CountDownLatch(1); file.deleteInBackground(new DeleteCallback() { @Override public void done(AVException e) { Assert.assertNull(e); latch.countDown(); } }); latch.await(1, TimeUnit.MINUTES); AVException exception = null; AVFile deletedFile = null; try { deletedFile = AVFile.withObjectId(file.getObjectId()); } catch (AVException e) { exception = e; } Assert.assertEquals(exception.code, AVException.OBJECT_NOT_FOUND); Assert.assertNull(deletedFile); } |
### Question:
AVFile { public static void clearCacheMoreThanDays(int days) { long curTime = System.currentTimeMillis(); if ( days > 0) { curTime -= days * 86400000; } String cacheDir = AVFileDownloader.getAVFileCachePath(); clearDir(new File(cacheDir), curTime); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testClearCachedFileBeforeDays() throws Exception { AVFile.clearCacheMoreThanDays(6); } |
### Question:
AVFile { public static void clearAllCachedFiles() { clearCacheMoreThanDays(0); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testClearAllCachedFile() throws Exception { AVFile.clearAllCachedFiles(); } |
### Question:
AVSMS { public static void requestSMSCode(String phone, AVSMSOption smsOption) throws AVException { requestSMSCodeInBackground(phone, smsOption, true, new RequestMobileCodeCallback() { @Override public void done(AVException e) { if (e != null) { AVExceptionHolder.add(e); } } @Override public boolean mustRunOnUIThread() { return false; } }); if (AVExceptionHolder.exists()) { throw AVExceptionHolder.remove(); } } static void requestSMSCode(String phone, AVSMSOption smsOption); static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback); static void verifySMSCode(String code, String mobilePhoneNumber); static void verifySMSCodeInBackground(String code, String phoneNumber,
AVMobilePhoneVerifyCallback callback); }### Answer:
@Test public void testRequestSMSCode() throws AVException { AVOSCloud.requestSMSCode(PHONE); }
@Test public void testRequestSMSCode1() throws AVException { AVOSCloud.requestSMSCode(PHONE, APPLICATION_NAME, OPERATION, TTL); }
@Test public void testRequestSMSCode2() throws AVException { AVOSCloud.requestSMSCode(PHONE, TEMPLATE_NAME, ENV_MAP); }
@Test public void testRequestSMSCode3() throws AVException { AVOSCloud.requestSMSCode(PHONE, TEMPLATE_NAME, SIGNATURE_NAME, ENV_MAP); } |
### Question:
AVSMS { public static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback) { requestSMSCodeInBackground(phone, option, false, callback); } static void requestSMSCode(String phone, AVSMSOption smsOption); static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback); static void verifySMSCode(String code, String mobilePhoneNumber); static void verifySMSCodeInBackground(String code, String phoneNumber,
AVMobilePhoneVerifyCallback callback); }### Answer:
@Test public void testRequestSMSCodeInBackground() throws AVException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); AVOSCloud.requestSMSCodeInBackground(PHONE, APPLICATION_NAME, OPERATION, TTL, new RequestMobileCodeCallback() { @Override public void done(AVException e) { latch.countDown(); } }); latch.await(); }
@Test public void testRequestSMSCodeInBackground1() throws AVException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); AVOSCloud.requestSMSCodeInBackground(PHONE, TEMPLATE_NAME, ENV_MAP, new RequestMobileCodeCallback() { @Override public void done(AVException e) { latch.countDown(); } }); latch.await(); }
@Test public void testRequestSMSCodeInBackground2() throws AVException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); AVOSCloud.requestSMSCodeInBackground(PHONE, TEMPLATE_NAME, SIGNATURE_NAME, ENV_MAP, new RequestMobileCodeCallback() { @Override public void done(AVException e) { latch.countDown(); } }); latch.await(); }
@Test public void testRequestSMSCodeInBackground3() throws AVException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); AVOSCloud.requestSMSCodeInBackground(PHONE, new RequestMobileCodeCallback() { @Override public void done(AVException e) { latch.countDown(); } }); latch.await(); } |
### Question:
AVSMS { public static void verifySMSCode(String code, String mobilePhoneNumber) throws AVException { verifySMSCodeInBackground(code, mobilePhoneNumber, true, new AVMobilePhoneVerifyCallback() { @Override public void done(AVException e) { if (e != null) { AVExceptionHolder.add(e); } } @Override public boolean mustRunOnUIThread() { return false; } }); if (AVExceptionHolder.exists()) { throw AVExceptionHolder.remove(); } } static void requestSMSCode(String phone, AVSMSOption smsOption); static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback); static void verifySMSCode(String code, String mobilePhoneNumber); static void verifySMSCodeInBackground(String code, String phoneNumber,
AVMobilePhoneVerifyCallback callback); }### Answer:
@Test public void testVerifySMSCode() throws AVException { AVOSCloud.verifySMSCode(CODE, PHONE); } |
### Question:
AVSMS { public static void verifySMSCodeInBackground(String code, String phoneNumber, AVMobilePhoneVerifyCallback callback) { verifySMSCodeInBackground(code, phoneNumber, false, callback); } static void requestSMSCode(String phone, AVSMSOption smsOption); static void requestSMSCodeInBackground(String phone, AVSMSOption option, RequestMobileCodeCallback callback); static void verifySMSCode(String code, String mobilePhoneNumber); static void verifySMSCodeInBackground(String code, String phoneNumber,
AVMobilePhoneVerifyCallback callback); }### Answer:
@Test public void testVerifySMSCodeInBackground() throws AVException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); AVOSCloud.verifySMSCodeInBackground(CODE, PHONE, new AVMobilePhoneVerifyCallback() { @Override public void done(AVException e) { latch.countDown(); } }); latch.await(); } |
### Question:
AVPowerfulUtils { public static String getEndpoint(String className) { String endpoint = get(className, ENDPOINT); if (AVUtils.isBlankString(endpoint)) { if (!AVUtils.isBlankString(className)) { endpoint = String.format("classes/%s", className); } else { throw new AVRuntimeException("Blank class name"); } } return endpoint; } static String getEndpoint(String className); static String getEndpoint(Object object); static String getEndpoint(Object object, boolean isPost); static String getBatchEndpoint(String version, AVObject object, boolean isPost); static String getEndpointByAVClassName(String className, String objectId); static String getAVClassName(String className); static String getFollowEndPoint(String followee, String follower); static String getFollowersEndPoint(String userId); static String getFolloweesEndPoint(String userId); static String getFollowersAndFollowees(String userId); static String getInternalIdFromRequestBody(Map request); }### Answer:
@Test public void testGetEndpoint() { final String objectId = "objectId"; AVUser user = new AVUser(); Assert.assertEquals(AVUser.AVUSER_ENDPOINT, AVPowerfulUtils.getEndpoint(user)); user.setObjectId(objectId); Assert.assertEquals(String.format("%s/%s", AVUser.AVUSER_ENDPOINT, objectId), AVPowerfulUtils.getEndpoint(user)); AVStatus status = new AVStatus(); Assert.assertEquals(AVStatus.STATUS_ENDPOINT, AVPowerfulUtils.getEndpoint(status)); status.setObjectId(objectId); Assert.assertEquals(String.format("%s/%s", AVStatus.STATUS_ENDPOINT, objectId), AVPowerfulUtils.getEndpoint(status)); AVRole role = new AVRole(); Assert.assertEquals(AVRole.AVROLE_ENDPOINT, AVPowerfulUtils.getEndpoint(role)); role.setObjectId(objectId); Assert.assertEquals(String.format("%s/%s", AVRole.AVROLE_ENDPOINT, objectId), AVPowerfulUtils.getEndpoint(role)); AVFile file = new AVFile(); Assert.assertEquals(AVFile.AVFILE_ENDPOINT, AVPowerfulUtils.getEndpoint(file)); final String NORMAL_OBJECT_NAME = "normalObject"; AVObject normalObject = new AVObject("normalObject"); Assert.assertEquals("classes/" + NORMAL_OBJECT_NAME, AVPowerfulUtils.getEndpoint(normalObject)); normalObject.setObjectId(objectId); Assert.assertEquals(String.format("classes/%s/%s", NORMAL_OBJECT_NAME, objectId), AVPowerfulUtils.getEndpoint(normalObject)); } |
### Question:
AVCloud { public static Object convertCloudResponse(String response) { Object newResultValue = null; try { Map<String, ?> resultMap = AVUtils.getFromJSON(response, Map.class); Object resultValue = resultMap.get("result"); if (resultValue instanceof Collection) { newResultValue = AVUtils.getObjectFrom((Collection) resultValue); } else if (resultValue instanceof Map) { newResultValue = AVUtils.getObjectFrom((Map<String, Object>) resultValue); } else { newResultValue = resultValue; } } catch (Exception e) { LogUtil.log.e("Error during response parse", e); } return newResultValue; } static void setProductionMode(boolean productionMode); static boolean isProductionMode(); static T callFunction(String name, Map<String, ?> params); static void callFunctionInBackground(String name, Map<String, ?> params,
final FunctionCallback<T> callback); static Object convertCloudResponse(String response); static void rpcFunctionInBackground(String name, Object params,
final FunctionCallback<T> callback); static T rpcFunction(String name, Object params); }### Answer:
@Test public void testConvertCloudResponse() { String content = "{\"result\":{\"content\":\"2222我若是写代码。\",\"ACL\":{\"*\":{\"read\":true},\"59229e282f301e006b1b637e\":{\"read\":true}},\"number\":123,\"userName\":{\"__type\":\"Pointer\",\"className\":\"_User\",\"objectId\":\"59631dab128fe1507271d9b7\"},\"asdfds\":{\"__type\":\"Pointer\",\"className\":\"_File\",\"objectId\":\"5875e04a61ff4b005c5c28ba\"},\"objectId\":\"56de3e5aefa631005ec03f67\",\"createdAt\":\"2016-03-08T02:52:10.733Z\",\"updatedAt\":\"2017-08-02T10:58:05.630Z\",\"__type\":\"Object\",\"className\":\"Comment\"}}"; AVObject object = (AVObject) AVCloud.convertCloudResponse(content); Assert.assertEquals(object.getClassName(), "Comment"); Assert.assertEquals(object.get("content"), "2222我若是写代码。"); Assert.assertEquals(object.getInt("number"), 123); Assert.assertEquals(object.getObjectId(), "56de3e5aefa631005ec03f67"); Assert.assertNotNull(object.getCreatedAt()); Assert.assertNotNull(object.getUpdatedAt()); Assert.assertNotNull(object.getACL()); Assert.assertNotNull(object.get("asdfds")); } |
### Question:
AVFile { protected org.json.JSONObject toJSONObject() { Map<String, Object> data = AVUtils.mapFromFile(this); if (!AVUtils.isBlankString(url)) { data.put("url", url); } return new JSONObject(data); } AVFile(); @Deprecated AVFile(byte[] data); AVFile(String name, String url, Map<String, Object> metaData); protected AVFile(String name, String url, Map<String, Object> metaData, boolean external); AVFile(String name, byte[] data); protected AVFile(String name, String url); static void setUploadHeader(String key, String value); String getObjectId(); void setObjectId(String objectId); @Deprecated static void parseFileWithObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); static void withObjectIdInBackground(final String objectId,
final GetFileCallback<AVFile> cb); @Deprecated static AVFile parseFileWithObjectId(String objectId); static AVFile withObjectId(String objectId); @Deprecated static AVFile parseFileWithAVObject(AVObject obj); static AVFile withAVObject(AVObject obj); @Deprecated static AVFile parseFileWithAbsoluteLocalPath(String name, String absoluteLocalFilePath); static AVFile withAbsoluteLocalPath(String name, String absoluteLocalFilePath); @Deprecated static AVFile parseFileWithFile(String name, File file); static AVFile withFile(String name, File file); HashMap<String, Object> getMetaData(); Object addMetaData(String key, Object val); Object getMetaData(String key); int getSize(); String getOwnerObjectId(); Object removeMetaData(String key); void clearMetaData(); String getName(); String getOriginalName(); void setName(String name); static String getMimeType(String url); boolean isDirty(); @Deprecated boolean isDataAvailable(); String getUrl(); String getThumbnailUrl(boolean scaleToFit, int width, int height); String getThumbnailUrl(boolean scaleToFit, int width, int height, int quality, String fmt); void setUrl(String url); void save(); synchronized void saveInBackground(final SaveCallback saveCallback,
final ProgressCallback progressCallback); void saveInBackground(SaveCallback callback); void saveInBackground(); @Deprecated @JSONField(serialize = false) byte[] getData(); @JSONField(serialize = false) InputStream getDataStream(); void getDataInBackground(final GetDataCallback dataCallback,
final ProgressCallback progressCallback); void getDataInBackground(GetDataCallback dataCallback); void getDataStreamInBackground(GetDataStreamCallback callback); void getDataStreamInBackground(final GetDataStreamCallback callback, final ProgressCallback progressCallback); void cancel(); void delete(); void deleteEventually(); void deleteEventually(DeleteCallback callback); void deleteInBackground(); void deleteInBackground(DeleteCallback callback); static String className(); Uploader getUploader(SaveCallback saveCallback, ProgressCallback progressCallback); String getBucket(); void setBucket(String bucket); AVACL getACL(); void setACL(AVACL acl); void clearCachedFile(); static void clearAllCachedFiles(); static void clearCacheMoreThanDays(int days); static String DEFAULTMIMETYPE; static final String AVFILE_ENDPOINT; }### Answer:
@Test public void testToJSONObject() throws Exception { String fileName = "FileUnitTestFiles"; AVFile avFile = new AVFile(fileName, TEST_FILE_CONTENT.getBytes()); JSONObject jsonObject = avFile.toJSONObject(); Assert.assertNotNull(jsonObject); Assert.assertEquals(jsonObject.getString("__type"), AVFile.className()); Assert.assertFalse(jsonObject.has("url")); Assert.assertEquals(jsonObject.getString("id"), fileName); } |
### Question:
AVCaptcha { public static void requestCaptchaInBackground(AVCaptchaOption option, final AVCallback<AVCaptchaDigest> callback) { if (null == callback) { return; } PaasClient.storageInstance().getObject("requestCaptcha", getOptionParams(option), false, null, new GenericObjectCallback() { @Override public void onSuccess(String content, AVException e) { AVCaptchaDigest digest = new AVCaptchaDigest(); if (!AVUtils.isBlankString(content)) { Map<String, String> map = JSON.parseObject(content, HashMap.class); if (null != map) { if (map.containsKey(CAPTCHA_TOKEN)) { digest.setNonce(map.get(CAPTCHA_TOKEN)); } if (map.containsKey(CAPTCHA_URL)) { digest.setUrl(map.get(CAPTCHA_URL)); } } } callback.internalDone(digest, null); } @Override public void onFailure(Throwable error, String content) { callback.internalDone(null, AVErrorUtils.createException(error, content)); } }); } static void requestCaptchaInBackground(AVCaptchaOption option, final AVCallback<AVCaptchaDigest> callback); static void verifyCaptchaCodeInBackground(String captchaCode, AVCaptchaDigest digest, final AVCallback<String> callback); }### Answer:
@Test public void testRequestCaptchaInBackground() throws AVException { final CountDownLatch latch = new CountDownLatch(1); AVCaptchaOption option = new AVCaptchaOption(); option.setWidth(200); option.setHeight(100); AVCaptcha.requestCaptchaInBackground(option, new AVCallback<AVCaptchaDigest>() { @Override protected void internalDone0(AVCaptchaDigest avCaptchaDigest, AVException exception) { Assert.assertNull(exception); Assert.assertNotNull(avCaptchaDigest); Assert.assertNotNull(avCaptchaDigest.getNonce()); Assert.assertNotNull(avCaptchaDigest.getUrl()); latch.countDown(); } @Override protected boolean mustRunOnUIThread() { return false; } }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); Assert.fail(); } } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.