src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
MatrixController { @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody public String find(@PathVariable String petId, @MatrixVariable int q) { logger.info("petId:{},q:{}",petId,q); return petId + q; } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); } | @Test public void find() throws Exception { this.mockMvc.perform(get("/matrix/find/42;q=11;r=22")) .andExpect(status().isOk()) .andExpect(content().string("4211")); } |
MatrixController { @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody public String find1( @MatrixVariable(name="q", pathVar="ownerId") int q1, @MatrixVariable(name="q", pathVar="petId") int q2) { return String.valueOf(q1+q2); } @RequestMapping(path = "/find/{petId}", method = RequestMethod.GET) @ResponseBody String find(@PathVariable String petId, @MatrixVariable int q); @RequestMapping(path = "/owners/{ownerId}/pets/{petId}", method = RequestMethod.GET) @ResponseBody String find1(
@MatrixVariable(name="q", pathVar="ownerId") int q1,
@MatrixVariable(name="q", pathVar="petId") int q2); } | @Test public void find1() throws Exception { this.mockMvc.perform(get("/matrix/owners/42;q=11/pets/11;q=22")) .andExpect(status().isOk()) .andExpect(content().string("33")); } |
JsonController { @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User get(){ return new User(20,"李四","F"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); } | @Test public void getUser() throws Exception { logger.info("JsonControllerTest getUser is running"); this.mockMvc.perform(get("/json/get").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("李四")); } |
JsonController { @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); } @RequestMapping(path = "/get",method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@PathVariable String name, Model model); } | @Test public void postUser() throws Exception { logger.info("JsonControllerTest postUser is running"); this.mockMvc.perform(post("/json/post/haha").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()).andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.name").value("haha")); } |
XmlController { @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User get(){ return new User(21,"张三","男"); } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); } | @Test public void getUser() throws Exception { logger.info("XmlControllerTest getUser is running"); this.mockMvc.perform(get("/xml/get")).andExpect(status().isOk()).andExpect(content().contentType ("application/xml")).andExpect(xpath("/user/name", new HashMap<String, String>()).string("张三")); } |
XmlController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public User post(@RequestBody User user){ logger.info(user.toString()); return user; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); } | @Test public void postUser() throws Exception { logger.info("XmlControllerTest postUser is running"); User user = new User(10, "王五", "男"); String content = JaxbUtils.toXml(user); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/post").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/user/sex", new HashMap<String, String>()).string("男")); } |
XmlController { @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody public House postHouse(@RequestBody House house){ logger.info(house.toString()); return house; } @RequestMapping(path = "/get",method = RequestMethod.GET,produces = MediaType.APPLICATION_XML_VALUE) @ResponseBody User get(); @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post(@RequestBody User user); @RequestMapping(path = "/post1",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody User post1(@RequestBody User user); @RequestMapping(path = "/postHouse",method = RequestMethod.POST,produces = MediaType.APPLICATION_XML_VALUE,consumes = MediaType.APPLICATION_XML_VALUE) @ResponseBody House postHouse(@RequestBody House house); } | @Test public void postHouse() throws Exception { logger.info("XmlControllerTest postHouse is running"); User user = new User(30, "王五", "男"); House house = new House(user,"南京"); String content = JaxbUtils.toXml(house); logger.info("content:{}", content); this.mockMvc.perform(post("/xml/postHouse").contentType(MediaType.APPLICATION_XML_VALUE).content(content)) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE)).andExpect(xpath ("/house/user/sex", new HashMap<String, String>()).string("男")); } |
ValidController { @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@RequestBody @Valid User user){ return user; } @RequestMapping(path = "/post",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User post(@RequestBody @Valid User user); } | @Test public void postTest() throws Exception { User user = new User(50, "王五", "男"); String content = JSON.toJSONString(user); logger.info("content:{}", content); this.mockMvc.perform(post("/valid/post").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(content)) .andExpect(content().string("4211")); } |
ModelRef { static public boolean validateId(String id){ return (id != null) && (id).matches(REGEX_ID); } ModelRef(ModelRef modelRef); ModelRef(Principal owner, String id); @Override int hashCode(); @Override boolean equals(Object object); Principal getOwner(); String getId(); static boolean validateId(String id); static final String PATH_VALUE_ID; } | @Test public void validateId(){ assertTrue(ModelRef.validateId("com.mycompany.Test")); assertTrue(ModelRef.validateId("Test_v1")); assertTrue(ModelRef.validateId("Test_v1.0")); assertFalse(ModelRef.validateId(".")); assertFalse(ModelRef.validateId("-Test")); } |
CsvUtil { static public CsvPreference getFormat(String delimiterChar, String quoteChar){ char delimiter = ','; char quote = '\"'; if(delimiterChar != null){ delimiterChar = decodeDelimiter(delimiterChar); if(delimiterChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV delimiter character: \"" + delimiterChar + "\""); } delimiter = delimiterChar.charAt(0); } if(quoteChar != null){ quoteChar = decodeQuote(quoteChar); if(quoteChar.length() != 1){ throw new IllegalArgumentException("Invalid CSV quote character: \"" + quoteChar + "\""); } quote = quoteChar.charAt(0); } CsvPreference format = createFormat(delimiter, quote); return format; } private CsvUtil(); static CsvPreference getFormat(String delimiterChar, String quoteChar); static CsvPreference getFormat(BufferedReader reader); static CsvPreference createFormat(char delimiterChar, char quoteChar); static TableEvaluationRequest readTable(BufferedReader reader, CsvPreference format); static void writeTable(TableEvaluationResponse tableResponse, BufferedWriter writer, CsvPreference format); } | @Test public void getFormat() throws IOException { CsvPreference first; CsvPreference second; String csv = "1\tone\n" + "2\ttwo\n" + "3\tthree"; try(BufferedReader reader = new BufferedReader(new StringReader(csv))){ first = CsvUtil.getFormat(reader); second = CsvUtil.getFormat(reader); } assertNotSame(first.getEncoder(), second.getEncoder()); } |
WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Override public Response toResponse(WebApplicationException exception){ Response response = exception.getResponse(); Throwable throwable = exception; Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>(); while(true){ Throwable cause = throwable.getCause(); throwableMap.put(throwable, cause); if((cause == null) || throwableMap.containsKey(cause)){ break; } throwable = cause; } String message = throwable.getMessage(); if((message == null) || ("").equals(message)){ Response.Status status = (Response.Status)response.getStatusInfo(); message = status.getReasonPhrase(); } if(message.startsWith("HTTP ")){ message = message.replaceFirst("^HTTP (\\d)+ ", ""); } SimpleResponse entity = new SimpleResponse(); entity.setMessage(message); return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build(); } @Override Response toResponse(WebApplicationException exception); } | @Test public void toResponse(){ assertEquals("Not Found", getMessage(new NotFoundException())); assertEquals("Resource \"id\" not found", getMessage(new NotFoundException("Resource \"id\" not found"))); assertEquals("Bad Request", getMessage(new BadRequestException(new IllegalArgumentException()))); assertEquals("Bad \"id\" value", getMessage(new BadRequestException(new IllegalArgumentException("Bad \"id\" value")))); assertEquals("Bad Request", getMessage(new BadRequestException(new UnmarshalException(new IOException())))); assertEquals("Resource \"id\" is incomplete", getMessage(new BadRequestException(new UnmarshalException(new EOFException("Resource \"id\" is incomplete"))))); UnmarshalException selfRefException = new UnmarshalException((Throwable)null); selfRefException.setLinkedException(new UnmarshalException(selfRefException)); assertEquals("Bad Request", getMessage(new BadRequestException(selfRefException))); } |
Decorating { public static <T> DecoratingWith<T> proxy(final Class<T> type) { return new DecoratingWith<T>(new Decorating<T, T>((T)null, type)); } private Decorating(final U delegate, final Class<T>primaryType, final Class<?>... types); static DecoratingWith<T> proxy(final Class<T> type); static DecoratingWith<T> proxy(final Class<T> primaryType, final Class<?> ... types); static DecoratingVisitor<U, U> proxy(final U delegate); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> type); static DecoratingVisitor<U, T> proxy(final U delegate, final Class<T> primaryType, final Class<?> ... types); } | @Test(expected = MyException.class) public void shouldInterceptInvocationException() throws Exception { final Throwable[] thrown = new Throwable[1]; final MyException decoratedException = new MyException(); foo = Decorating.proxy(new MethodMissingImpl(), Foo.class).visiting(new Decorator<Foo>() { private static final long serialVersionUID = 1L; @Override public Exception decorateInvocationException(Foo proxy, Method method, Object[] args, Exception cause) { thrown[0] = cause; return decoratedException; } }).build(); foo.getSomething("value"); fail("Mock should have thrown exception"); }
@Test public void serializeWithJDK() throws IOException, ClassNotFoundException { useSerializedProxy(serializeWithJDK( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
@Test public void serializeWithXStream() { useSerializedProxy(serializeWithXStream( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
@Test public void serializeWithXStreamInPureReflectionMode() { useSerializedProxy(serializeWithXStreamAndPureReflection( Decorating.proxy(CharSequence.class).with("Test").visiting(new AssertingDecorator()).build(getFactory()))); }
@Test public void canDeferDecorationUntilAfterProxyInstantiation() throws Exception { final Decorator<WithCallsInConstructor> nullDecorator = new Decorator<WithCallsInConstructor>() {}; final WithCallsInConstructor obj = new WithCallsInConstructor(); obj.setS("custom"); assertEquals("sanity check", "custom", obj.getS()); final WithCallsInConstructor withCallsInConstructor = Decorating.proxy(WithCallsInConstructor.class).with(obj).visiting(nullDecorator).build(new CglibProxyFactory(true)); assertEquals("This won't be expected by most users, but it is \"correct\" nonetheless", "default", withCallsInConstructor.getS()); assertEquals("And this was passed on to the underlying object too", "default", obj.getS()); final WithCallsInConstructor obj2 = new WithCallsInConstructor(); obj2.setS("custom"); assertEquals("sanity check", "custom", obj2.getS()); final WithCallsInConstructor withoutCallsInConstructor = Decorating.proxy(WithCallsInConstructor.class).with(obj2).visiting(nullDecorator).build(new CglibProxyFactory(false)); assertEquals("And this is what most users would expect - setting interceptDuringConstruction to false", "custom", withoutCallsInConstructor.getS()); assertEquals("And this was not passed on to the underlying object either", "custom", obj2.getS()); } |
Privileging { public static <T> PrivilegingWith<T> proxy(Class<T> type) { return new PrivilegingWith<T>(new Privileging<T>(type)); } private Privileging(Class<T> type); static PrivilegingWith<T> proxy(Class<T> type); static PrivilegingExecutedByOrBuild<T> proxy(T target); } | @Test public void callWithArgumentsIsDelegated() throws Exception { Foo fooMock = mock(Foo.class); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call(42, "Arthur"); verify(fooMock).call(42, "Arthur"); }
@Test public void callWillReturnValue() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenReturn(42); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); assertEquals(42, foo.call("Arthur")); verify(fooMock).call("Arthur"); }
@Test(expected=NoSuchElementException.class) public void callWillThrowCheckedException() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenThrow(new NoSuchElementException("JUnit")); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call("Arthur"); }
@Test(expected=ArithmeticException.class) public void callWillThrowRuntimeException() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.call("Arthur")).thenThrow(new ArithmeticException("JUnit")); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call("Arthur"); }
@Test public void callWillCallToString() throws Exception { Foo fooMock = mock(Foo.class); when(fooMock.toString()).thenReturn("Arthur"); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); assertEquals("Arthur", foo.toString()); }
@Test public void callIsDelegated() throws Exception { Foo fooMock = mock(Foo.class); Foo foo = Privileging.proxy(Foo.class).with(fooMock).executedBy(new DirectExecutor()).build(getFactory()); foo.call(); verify(fooMock).call(); } |
Failover { public static <T> FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type) { return new FailoverWithOrExceptingOrBuild<T>(new Failover<T>(type)); } private Failover(Class<T> primaryType, Class<?>... types); static FailoverWithOrExceptingOrBuild<T> proxy(Class<T> type); static FailoverWithOrExceptingOrBuild<T> proxy(final Class<T> primaryType, final Class<?> ... types); static FailoverExceptingOrBuild<T> proxy(final T... delegates); } | @Test public void shouldFailoverToNextOnSpecialException() { FailsOnNthCall first = new FailsOnNthCallImpl(1); FailsOnNthCall second = new FailsOnNthCallImpl(1); FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(first, second) .excepting(RuntimeException.class) .build(getFactory()); assertEquals(0, first.dunIt()); assertEquals(0, second.dunIt()); failover.doIt(); assertEquals(1, first.dunIt()); assertEquals(0, second.dunIt()); failover.doIt(); assertEquals(1, first.dunIt()); assertEquals(1, second.dunIt()); }
@Test public void serializeWithJDK() throws IOException, ClassNotFoundException { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithJDK(failover)); }
@Test public void serializeWithXStream() { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithXStream(failover)); }
@Test public void serializeWithXStreamInPureReflectionMode() { final FailsOnNthCall failover = Failover.proxy(FailsOnNthCall.class) .with(new FailsOnNthCallImpl(1), new FailsOnNthCallImpl(1)) .excepting(RuntimeException.class) .build(getFactory()); failover.doIt(); useSerializedProxy(serializeWithXStreamAndPureReflection(failover)); } |
Delegating { public static <T> DelegatingWith<T> proxy(Class<T> type) { return new DelegatingWith<T>(new Delegating<T>(type)); } private Delegating(Class<T> type); static DelegatingWith<T> proxy(Class<T> type); } | @Test public void shouldSupportIndirectRecursion() { Faculty fac = new Faculty() { public int calc(int i, Faculty fac) { return i == 1 ? 1 : i * fac.calc(i - 1, fac); } }; Faculty proxy = Delegating.proxy(Faculty.class).with(fac).build(getFactory()); assertEquals(120, fac.calc(5, fac)); assertEquals(120, proxy.calc(5, proxy)); } |
Echoing { public static <T> EchoingWithOrTo<T> proxy(final Class<T> type) { return new EchoingWithOrTo<T>(new Echoing<T>(type)); } private Echoing(final Class<T> type); static EchoingWithOrTo<T> proxy(final Class<T> type); } | @Test public void shouldEchoMethodNameAndArgs() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); assertContains("Simple.doSomething()", out); }
@Test public void shouldDelegateCalls() throws Exception { Writer out = new StringWriter(); Simple foo = Echoing.proxy(Simple.class).with(simpleMock).to(new PrintWriter(out)).build(getFactory()); foo.doSomething(); verify(simpleMock).doSomething(); }
@Test public void shouldRecursivelyReturnEchoProxiesForInterfaces() throws Exception { Inner innerMock = mock(Inner.class); Outer outerMock = mock(Outer.class); StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).with(outerMock).to(new PrintWriter(out)).build(getFactory()); when(outerMock.getInner()).thenReturn(innerMock); when(innerMock.getName()).thenReturn("inner"); String result = outer.getInner().getName(); assertEquals("inner", result); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); verify(outerMock).getInner(); verify(innerMock).getName(); }
@Test public void shouldRecursivelyReturnEchoProxiesEvenForMissingImplementations() throws Exception { StringWriter out = new StringWriter(); Outer outer = Echoing.proxy(Outer.class).to(new PrintWriter(out)).build(getFactory()); outer.getInner().getName(); assertContains("Outer.getInner()", out); assertContains("Inner.getName()", out); } |
CglibProxyFactory extends AbstractProxyFactory { public boolean canProxy(final Class<?> type) { return !Modifier.isFinal(type.getModifiers()); } CglibProxyFactory(); CglibProxyFactory(boolean interceptDuringConstruction); T createProxy(final Invoker invoker, final Class<?>... types); boolean canProxy(final Class<?> type); boolean isProxyClass(final Class<?> type); } | @Test public void shouldDenyProxyGenerationForFinalClasses() throws Exception { ProxyFactory factory = new CglibProxyFactory(); assertFalse(factory.canProxy(String.class)); } |
ReflectionUtils { public static Class<?> getMostCommonSuperclass(Object... objects) { Class<?> type = null; boolean found = false; if (objects != null && objects.length > 0) { while (!found) { for (Object object : objects) { found = true; if (object != null) { final Class<?> currenttype = object.getClass(); if (type == null) { type = currenttype; } if (!type.isAssignableFrom(currenttype)) { if (currenttype.isAssignableFrom(type)) { type = currenttype; } else { type = type.getSuperclass(); found = false; break; } } } } } } if (type == null) { type = Object.class; } return type; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; } | @Test public void mostCommonSuperclassForClassesWithACommonBaseClass() { assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new StringWriter())); }
@Test public void mostCommonSuperclassForClassesAreInSameHierarchy() { assertEquals(OutputStreamWriter.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out))); assertEquals(OutputStreamWriter.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out))); }
@Test public void mostCommonSuperclassForClassesInSameOrDifferentHierarchy() { assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new StringWriter(), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out), new StringWriter())); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new FileWriter(FileDescriptor.out), new OutputStreamWriter(System.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out), new StringWriter())); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new StringWriter(), new OutputStreamWriter(System.out), new FileWriter(FileDescriptor.out))); assertEquals(Writer.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), new StringWriter(), new FileWriter(FileDescriptor.out))); }
@Test public void mostCommonSuperclassForUnmatchingObjects() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(1, new OutputStreamWriter(System.out))); assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(new OutputStreamWriter(System.out), 1)); }
@Test public void mostCommonSuperclassForEmptyArray() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass()); }
@Test public void mostCommonSuperclassForNullElements() { assertEquals(Object.class, ReflectionUtils.getMostCommonSuperclass(null, null)); }
@Test public void mostCommonSuperclassForCollections() { assertEquals(AbstractList.class, ReflectionUtils.getMostCommonSuperclass(new LinkedList<Object>(), new Vector<Object>())); } |
ReflectionUtils { public static Set<Class<?>> getAllInterfaces(Object... objects) { final Set<Class<?>> interfaces = new HashSet<Class<?>>(); for (Object object : objects) { if (object != null) { getInterfaces(object.getClass(), interfaces); } } interfaces.remove(InvokerReference.class); return interfaces; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; } | @Test public void allInterfacesOfListShouldBeFound() { Set<Class<?>> interfaces = ReflectionUtils.getAllInterfaces(BeanContextServices.class); assertTrue(interfaces.contains(BeanContextServices.class)); assertTrue(interfaces.contains(BeanContext.class)); assertTrue(interfaces.contains(Collection.class)); assertTrue(interfaces.contains(BeanContextServicesListener.class)); assertTrue(interfaces.contains(EventListener.class)); } |
ReflectionUtils { public static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args) throws NoSuchMethodException { final Object[] newArgs = args == null ? new Object[0] : args; final Method[] methods = type.getMethods(); final Set<Method> possibleMethods = new HashSet<Method>(); Method method = null; for (int i = 0; method == null && i < methods.length; i++) { if (methodName.equals(methods[i].getName())) { final Class<?>[] argTypes = methods[i].getParameterTypes(); if (argTypes.length == newArgs.length) { boolean exact = true; Method possibleMethod = methods[i]; for (int j = 0; possibleMethod != null && j < argTypes.length; j++) { final Class<?> newArgType = newArgs[j] != null ? newArgs[j].getClass() : Object.class; if ((argTypes[j].equals(byte.class) && newArgType.equals(Byte.class)) || (argTypes[j].equals(char.class) && newArgType.equals(Character.class)) || (argTypes[j].equals(short.class) && newArgType.equals(Short.class)) || (argTypes[j].equals(int.class) && newArgType.equals(Integer.class)) || (argTypes[j].equals(long.class) && newArgType.equals(Long.class)) || (argTypes[j].equals(float.class) && newArgType.equals(Float.class)) || (argTypes[j].equals(double.class) && newArgType.equals(Double.class)) || (argTypes[j].equals(boolean.class) && newArgType.equals(Boolean.class))) { exact = true; } else if (!argTypes[j].isAssignableFrom(newArgType)) { possibleMethod = null; exact = false; } else if (!argTypes[j].isPrimitive()) { if (!argTypes[j].equals(newArgType)) { exact = false; } } } if (exact) { method = possibleMethod; } else if (possibleMethod != null) { possibleMethods.add(possibleMethod); } } } } if (method == null && possibleMethods.size() > 0) { method = possibleMethods.iterator().next(); } if (method == null) { final StringBuilder name = new StringBuilder(type.getName()); name.append('.'); name.append(methodName); name.append('('); for (int i = 0; i < newArgs.length; i++) { if (i != 0) { name.append(", "); } name.append(newArgs[i].getClass().getName()); } name.append(')'); throw new NoSuchMethodException(name.toString()); } return method; } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; } | @Test public void matchingMethodIsFound() throws Exception { Method appendChar = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{'c'}); Method appendCharArray = ReflectionUtils.getMatchingMethod( StringBuffer.class, "append", new Object[]{new char[]{'c'}}); Method appendShort = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{(short) 0}); Method appendObject = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{this}); Method appendObject2 = ReflectionUtils.getMatchingMethod( StringBuffer.class, "append", new Object[]{new Exception()}); assertNotNull(appendChar); assertNotNull(appendCharArray); assertNotNull(appendShort); assertNotNull(appendObject); assertNotNull(appendObject2); assertNotSame(appendChar, appendCharArray); assertNotSame(appendObject, appendChar); assertNotSame(appendObject, appendCharArray); assertNotSame(appendObject, appendShort); assertTrue(appendObject.equals(appendObject2)); }
@Test public void matchingMethodArgumentCanBeNull() throws Exception { Method appendObject = ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{null}); assertNotNull(appendObject); }
@Test public void matchingMethodArgumentsCanBeNull() throws Exception { Method method = ReflectionUtils.getMatchingMethod(StringBuffer.class, "toString", null); assertNotNull(method); }
@Test public void noSuchMethodExceptionIsThrownIfNoMatchingMethodCouldBeFound() throws Exception { try { ReflectionUtils.getMatchingMethod(StringBuffer.class, "append", new Object[]{this, StringBuffer.class}); fail("Thrown " + NoSuchMethodException.class.getName() + " expected"); } catch (final NoSuchMethodException e) { assertTrue(e.getMessage().indexOf( StringBuffer.class.getName() + ".append(" + this.getClass().getName() + ", " + Class.class.getName() + ")") >= 0); } } |
ReflectionUtils { public static void writeMethod(final ObjectOutputStream out, final Method method) throws IOException { out.writeObject(method.getDeclaringClass()); out.writeObject(method.getName()); out.writeObject(method.getParameterTypes()); } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; } | @Test public void methodCanBeSerialized() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); ReflectionUtils.writeMethod(outStream, ReflectionUtils.equals); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); assertSame(Object.class, inStream.readObject()); assertEquals("equals", inStream.readObject()); assertTrue(Arrays.equals(new Class[]{Object.class}, (Object[]) inStream.readObject())); inStream.close(); } |
ReflectionUtils { public static Method readMethod(final ObjectInputStream in) throws IOException, ClassNotFoundException { final Class<?> type = Class.class.cast(in.readObject()); final String name = String.class.cast(in.readObject()); final Class<?>[] parameters = Class[].class.cast(in.readObject()); try { return type.getMethod(name, parameters); } catch (final NoSuchMethodException e) { throw new InvalidObjectException(e.getMessage()); } } private ReflectionUtils(); static Set<Class<?>> getAllInterfaces(Object... objects); static Set<Class<?>> getAllInterfaces(final Class<?> type); static Class<?> getMostCommonSuperclass(Object... objects); static void addIfClassProxyingSupportedAndNotObject(
final Class<?> type, final Set<Class<?>> interfaces, final ProxyFactory proxyFactory); static Method getMatchingMethod(final Class<?> type, final String methodName, final Object[] args); static void writeMethod(final ObjectOutputStream out, final Method method); static Method readMethod(final ObjectInputStream in); static Class<?>[] makeTypesArray(Class<?> primaryType, Class<?>[] types); static final Method equals; static final Method hashCode; static final Method toString; } | @Test public void methodCanBeDeserialized() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); outStream.writeObject(Object.class); outStream.writeObject("equals"); outStream.writeObject(new Class[]{Object.class}); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); assertEquals(ReflectionUtils.equals, ReflectionUtils.readMethod(inStream)); }
@Test public void unknownDeserializedMethodThrowsInvalidObjectException() throws IOException, ClassNotFoundException { ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); ObjectOutputStream outStream = new ObjectOutputStream(outBuffer); outStream.writeObject(Object.class); outStream.writeObject("equals"); outStream.writeObject(new Class[0]); outStream.close(); ByteArrayInputStream inBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(inBuffer); try { ReflectionUtils.readMethod(inStream); fail("Thrown " + InvalidObjectException.class.getName() + " expected"); } catch (final InvalidObjectException e) { } } |
Future { public static <T> FutureWith<T> proxy(Class<T> primaryType) { Future<T> future = new Future<T>(new Class<?>[]{primaryType}); return new FutureWith<T>(future); } private Future(Class<?>[] types); static FutureWith<T> proxy(Class<T> primaryType); static FutureWith<T> proxy(Class<T> primaryType, Class<?>... types); static FutureBuild<T> proxy(T target); } | @Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithCast() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); }
@Test public void shouldReturnNullObjectAsIntermediateResultAndSwapWhenMethodCompletesWithGenerics() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); List<String> stuff = fastService.getList(); assertTrue(stuff.isEmpty()); latch.countDown(); Thread.sleep(100); assertEquals(1, stuff.size()); assertEquals("yo", stuff.get(0)); }
@Test public void shouldHandleVoidMethodsWithCast() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(slowService).build(getFactory()); fastService.methodReturnsVoid(); }
@Test public void shouldHandleVoidMethodsWithGenerics() { CountDownLatch latch = new CountDownLatch(1); Service slowService = new SlowService(latch); Service fastService = Future.proxy(Service.class).with(slowService).build(getFactory()); fastService.methodReturnsVoid(); } |
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected RRestoreBlobData createRestoreData(final RestoreBlobData restoreBlobData) { checkState(!isEmpty(restoreBlobData.getBlobName()), "Blob name cannot be empty"); return new RRestoreBlobData(restoreBlobData); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); } | @Test public void testBlobDataIsCreated() { assertThat(restoreBlobStrategy.createRestoreData(restoreBlobData).getBlobData(), is(restoreBlobData)); }
@Test(expected = IllegalStateException.class) public void testIfBlobDataNameIsEmptyExceptionIsThrown() { when(rRestoreBlobData.getBlobData().getBlobName()).thenReturn(""); restoreBlobStrategy.createRestoreData(restoreBlobData); } |
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Nonnull @Override protected List<HashAlgorithm> getHashAlgorithms() { return ImmutableList.of(SHA1); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); } | @Test public void testCorrectHashAlgorithmsAreSupported() { assertThat(restoreBlobStrategy.getHashAlgorithms(), containsInAnyOrder(SHA1)); } |
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected String getAssetPath(@Nonnull final RRestoreBlobData rRestoreBlobData) { return rRestoreBlobData.getBlobData().getBlobName(); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); } | @Test public void testAppropriatePathIsReturned() { assertThat(restoreBlobStrategy.getAssetPath(rRestoreBlobData), is(ARCHIVE_PATH)); } |
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean assetExists(@Nonnull final RRestoreBlobData rRestoreBlobData) { RRestoreFacet facet = getRestoreFacet(rRestoreBlobData); return facet.assetExists(getAssetPath(rRestoreBlobData)); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); } | @Test public void testPackageIsRestored() throws Exception { restoreBlobStrategy.restore(properties, blob, TEST_BLOB_STORE_NAME, false); verify(rRestoreFacet).assetExists(ARCHIVE_PATH); verify(rRestoreFacet).restore(any(AssetBlob.class), eq(ARCHIVE_PATH)); verifyNoMoreInteractions(rRestoreFacet); } |
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected boolean componentRequired(final RRestoreBlobData data) { RRestoreFacet facet = getRestoreFacet(data); final String path = data.getBlobData().getBlobName(); return facet.componentRequired(path); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); } | @Test public void testComponentIsRequiredForGz() { boolean expected = true; when(rRestoreFacet.componentRequired(ARCHIVE_PATH)).thenReturn(expected); assertThat(restoreBlobStrategy.componentRequired(rRestoreBlobData), is(expected)); verify(rRestoreFacet).componentRequired(ARCHIVE_PATH); verifyNoMoreInteractions(rRestoreFacet); } |
RRestoreBlobStrategy extends BaseRestoreBlobStrategy<RRestoreBlobData> { @Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.extractComponentAttributesFromArchive(blobData.getBlobName(), inputStream); } return facet.getComponentQuery(attributes); } @Inject RRestoreBlobStrategy(final NodeAccess nodeAccess,
final RepositoryManager repositoryManager,
final BlobStoreManager blobStoreManager,
final DryRunPrefix dryRunPrefix); } | @Test public void testComponentQuery() throws IOException { restoreBlobStrategy.getComponentQuery(rRestoreBlobData); verify(rRestoreFacet, times(1)).getComponentQuery(anyMapOf(String.class, String.class)); } |
XssSanitizerService { public String sanitize(String html) { return policyFactory.sanitize( html, xssHtmlChangeListener, "ip='"+ getIpAddressFromRequestContext()+"'" ); } String sanitize(String html); } | @Test public void test() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто</a> используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); }
@Test public void testNoClosed() throws Exception { String unsafe = "<a href='javascript:alert('XSS')'>часто используемый в печати и вэб-дизайне"; String safe = xssSanitizerService.sanitize(unsafe); Assertions.assertEquals("часто используемый в печати и вэб-дизайне", safe); } |
SettingsController { @GetMapping(API+CONFIG) public SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount){ Iterable<RuntimeSettings> runtimeSettings = runtimeSettingsRepository.findAll(); SettingsDTO settingsDTOPartial = StreamSupport.stream(runtimeSettings.spliterator(), false) .reduce( new SettingsDTO(), (settingsDTO, runtimeSettings1) -> { if (runtimeSettings1.getKey() == null) { throw new RuntimeException("Null key is not supported"); } switch (runtimeSettings1.getKey()) { case IMAGE_BACKGROUND: settingsDTO.setImageBackground(runtimeSettings1.getValue()); break; case HEADER: settingsDTO.setHeader(runtimeSettings1.getValue()); break; case SUB_HEADER: settingsDTO.setSubHeader(runtimeSettings1.getValue()); break; case TITLE_TEMPLATE: settingsDTO.setTitleTemplate(runtimeSettings1.getValue()); break; case BACKGROUND_COLOR: settingsDTO.setBackgroundColor(runtimeSettings1.getValue()); break; default: LOGGER.warn("Unknown key " + runtimeSettings1.getKey()); } return settingsDTO; }, (settingsDTO, settingsDTO2) -> { throw new UnsupportedOperationException("Parallel is not supported");} ); boolean canShowSettings = blogSecurityService.hasSettingsPermission(userAccount); settingsDTOPartial.setCanShowSettings(canShowSettings); settingsDTOPartial.setCanShowApplications(applicationConfig.isEnableApplications()); settingsDTOPartial.setAvailableRoles(Arrays.asList(UserRole.ROLE_ADMIN, UserRole.ROLE_USER)); return settingsDTOPartial; } @GetMapping(API+CONFIG) SettingsDTO getConfig(@AuthenticationPrincipal UserAccountDetailsDTO userAccount); @Transactional @PostMapping(value = API+CONFIG, consumes = {"multipart/form-data"}) @PreAuthorize("@blogSecurityService.hasSettingsPermission(#userAccount)") SettingsDTO putConfig(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestPart(value = DTO_PART) SettingsDTO dto,
@RequestPart(value = IMAGE_PART, required = false) MultipartFile imagePart
); static final String IMAGE_PART; static final String DTO_PART; static final String IMAGE_BACKGROUND; } | @Test public void getConfig() throws Exception { mockMvc.perform( get(Constants.Urls.API+ Constants.Urls.CONFIG) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) ) .andExpect(status().isOk()) .andExpect(jsonPath("$.titleTemplate").value("%s | nkonev's blog")) .andExpect(jsonPath("$.header").value("Блог Конева Никиты")) .andExpect(jsonPath("$.canShowSettings").value(false)) .andExpect(jsonPath("$.removeImageBackground").doesNotExist()) .andReturn(); } |
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization updatePost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.updatePost(userAccount, postDTO); } @GetMapping(Constants.Urls.API + Constants.Urls.POST) Wrapper<PostDTO> getPosts(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) PostDTOExtended getPost(
@PathVariable(Constants.PathVariables.POST_ID) long id,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).READ_MY)") @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.MY) List<PostDTO> getMyPosts(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString // TODO implement
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization addPost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization updatePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postId, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).DELETE)") @DeleteMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) void deletePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@PathVariable(Constants.PathVariables.POST_ID) long postId
); } | @WithUserDetails(TestConstants.USER_ADMIN) @Test public void testFulltextSearchHostPort() throws Exception { final String newPostRendered = "<body>Post Rendered</body>"; mockServer.expect(requestTo(new StringStartsWith(true, "http: .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(newPostRendered, MediaType.TEXT_HTML)); final String newIndexRendered = "<body>Index Rendered</body>"; mockServer.expect(requestTo("http: .andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(newIndexRendered, MediaType.TEXT_HTML)); UserAccountDetailsDTO userAccountDetailsDTO = (UserAccountDetailsDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); postController.updatePost(userAccountDetailsDTO, new PostDTO(50L, "edited for search host port", "A new host for test www.google.com:80 with port too", "", null, null, null, false, null)); MvcResult getPostsRequest = mockMvc.perform( get(Constants.Urls.API+ Constants.Urls.POST+"?searchString=www.google.com:80") .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) ) .andDo( mvcResult -> { LOGGER.info(mvcResult.getResponse().getContentAsString()); } ) .andExpect(status().isOk()) .andExpect(jsonPath("$.data.size()").value(1)) .andExpect(jsonPath("$.data[0].title").value("edited for search host port")) .andExpect(jsonPath("$.data[0].text").value("A new host for test <b>www.google.com:80</b> with port too")) .andReturn(); } |
PostController { @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization addPost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, @RequestBody @NotNull PostDTO postDTO ) { return postService.addPost(userAccount, postDTO); } @GetMapping(Constants.Urls.API + Constants.Urls.POST) Wrapper<PostDTO> getPosts(
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) PostDTOExtended getPost(
@PathVariable(Constants.PathVariables.POST_ID) long id,
@AuthenticationPrincipal UserAccountDetailsDTO userAccount // null if not authenticated
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).READ_MY)") @GetMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.MY) List<PostDTO> getMyPosts(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount,
@RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "0") int size,
@RequestParam(value = "searchString", required = false, defaultValue = "") String searchString // TODO implement
); @PreAuthorize("@blogSecurityService.hasPostPermission(#userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).CREATE)") @PostMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization addPost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) PostDTOWithAuthorization updatePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@RequestBody @NotNull PostDTO postDTO
); @PreAuthorize("@blogSecurityService.hasPostPermission(#postId, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).DELETE)") @DeleteMapping(Constants.Urls.API + Constants.Urls.POST + Constants.Urls.POST_ID) void deletePost(
@AuthenticationPrincipal UserAccountDetailsDTO userAccount, // null if not authenticated
@PathVariable(Constants.PathVariables.POST_ID) long postId
); } | @Test public void testAnonymousCannotAddPostUnit() throws Exception { Assertions.assertThrows(AuthenticationCredentialsNotFoundException.class, () -> { postController.addPost(null, PostDtoBuilder.startBuilding().build()); }); } |
PostConverter { public static String getYouTubeVideoId(String iframeSrcUrl) { UriComponents build = UriComponentsBuilder.fromHttpUrl(iframeSrcUrl).build(); List<String> pathSegments = build.getPathSegments(); return pathSegments.get(pathSegments.size() - 1); } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); } | @Test public void testGetYouTubeId() { String youtubeVideoId = PostConverter.getYouTubeVideoId("https: Assertions.assertEquals("eoDsxos6xhM", youtubeVideoId); } |
PostConverter { String getTitleImg(PostDTO postDTO) { String titleImg = postDTO.getTitleImg(); if (setFirstImageAsTitle && StringUtils.isEmpty(titleImg)) { try { Document document = Jsoup.parse(postDTO.getText()); Elements images = document.getElementsByTag("img"); if (!images.isEmpty()) { Element element = images.get(0); return element.attr("src"); } Elements iframes = document.getElementsByTag("iframe"); if (!iframes.isEmpty()) { Element element = iframes.get(0); String iframeSrcUrl = element.attr("src"); if (iframeSrcUrl.contains("youtube.com")) { String youtubeVideoId = getYouTubeVideoId(iframeSrcUrl); String youtubeThumbnailUrl = youtubeThumbnailUrlTemplate.replace("__VIDEO_ID__", youtubeVideoId); return imageDownloader.downloadImageAndSave(youtubeThumbnailUrl, imagePostTitleUploadController); } } } catch (RuntimeException e) { if (LOGGER.isDebugEnabled()){ LOGGER.warn("Error during parse image from content: {}", e.getMessage(), e); } else { LOGGER.warn("Error during parse image from content: {}", e.getMessage()); } return null; } } return titleImg; } PostDTOWithAuthorization convertToDto(Post saved, UserAccountDetailsDTO userAccount); Post convertToPost(PostDTO postDTO, Post forUpdate); static String getYouTubeVideoId(String iframeSrcUrl); IndexPost toElasticsearchPost(com.github.nkonev.blog.entity.jdbc.Post jpaPost); static void cleanTags(PostDTO postDTO); static String cleanHtmlTags(String html); PostDTO convertToPostDTO(Post post); } | @Test public void shouldSetFirstImgWhenTitleImgEmpty() { PostDTO postDTO = new PostDTO(); postDTO.setText("Hello, I contains images. This is first. <img src=\"http: postDTO.setTitle("Title"); String titleImg = postConverter.getTitleImg(postDTO); Assertions.assertEquals("http: }
@Test public void shouldDownloadYoutubePreviewWhenTitleImgEmptyAndContentHasNotImages() { PostDTO postDTO = new PostDTO(); postDTO.setText("Hello, I contains youtube videos. " + " This is first. <iframe allowfullscreen=\"true\" src=\"https: " This is second. <iframe allowfullscreen=\"true\" src=\"https: postDTO.setTitle("Title"); String titleImg = postConverter.getTitleImg(postDTO); Assertions.assertNotNull(titleImg); String imageId = titleImg .replace("/api/image/post/title/", "") .replace(".png", ""); Assertions.assertFalse(StringUtils.isEmpty(imageId)); Integer integer = jdbcTemplate.queryForObject("select count(*) from images.post_title_image where id = :id\\:\\:uuid", Map.of("id", imageId), Integer.class); Assertions.assertEquals(1, integer); } |
JettyServerWrapper extends Server { HttpServiceContext getOrCreateContext(final Model model) { return getOrCreateContext(model.getContextModel()); } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); } | @SuppressWarnings("unchecked") @Test public void getOrCreateContextDoesNotRegisterMultipleServletContextsForSameContextModelSingleThreaded() throws Exception { final JettyServerWrapper jettyServerWrapperUnderTest = new JettyServerWrapper( serverModelMock, new QueuedThreadPool()); try { jettyServerWrapperUnderTest.start(); HttpServiceContext context = jettyServerWrapperUnderTest.getOrCreateContext(contextModelMock); context.start(); context = jettyServerWrapperUnderTest.getOrCreateContext(contextModelMock); context.start(); verify(bundleContextMock, times(1)).registerService( same(ServletContext.class), any(ServletContext.class), any(Dictionary.class)); } finally { jettyServerWrapperUnderTest.stop(); } }
@SuppressWarnings("unchecked") @Test public void getOrCreateContextDoesNotRegisterMultipleServletContextsForSameContextModelMultiThreaded() throws Exception { final JettyServerWrapper jettyServerWrapperUnderTest = new JettyServerWrapper( serverModelMock, new QueuedThreadPool()); try { jettyServerWrapperUnderTest.start(); final CountDownLatch countDownLatch = new CountDownLatch(1); final Runnable getOrCreateContextRunnable = new Runnable() { @Override public void run() { try { countDownLatch.await(); HttpServiceContext context = jettyServerWrapperUnderTest .getOrCreateContext(contextModelMock); context.start(); } catch (final InterruptedException ex) { } catch (final Exception ex) { exceptionInRunnable = ex; } } }; final ExecutorService executor = Executors .newFixedThreadPool(NUMBER_OF_CONCURRENT_EXECUTIONS); for (int i = 0; i < NUMBER_OF_CONCURRENT_EXECUTIONS; i++) { executor.execute(getOrCreateContextRunnable); } countDownLatch.countDown(); executor.shutdown(); final boolean terminated = executor.awaitTermination(10, TimeUnit.SECONDS); if (exceptionInRunnable != null) { try { throw exceptionInRunnable; } finally { exceptionInRunnable = null; } } assertTrue("could not shutdown the executor within the timeout", terminated); verify(bundleContextMock, times(1)).registerService( same(ServletContext.class), any(ServletContext.class), any(Dictionary.class)); } finally { jettyServerWrapperUnderTest.stop(); } } |
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); } | @Test public void replaceSlashes07() { assertEquals("Replaced", "/foo/bar/car/", Path.replaceSlashes("/foo }
@Test public void replaceSlashesWithNull() { assertEquals("Replaced", null, Path.replaceSlashes(null)); }
@Test public void replaceSlashes01() { assertEquals("Replaced", "/foo/bar/", Path.replaceSlashes("/foo/bar/")); }
@Test public void replaceSlashes02() { assertEquals("Replaced", "/", Path.replaceSlashes("/")); }
@Test public void replaceSlashes03() { assertEquals("Replaced", "/", Path.replaceSlashes(" }
@Test public void replaceSlashes04() { assertEquals("Replaced", "/foo/bar", Path.replaceSlashes(" }
@Test public void replaceSlashes05() { assertEquals("Replaced", "foo/bar/", Path.replaceSlashes("foo/bar }
@Test public void replaceSlashes06() { assertEquals("Replaced", "foo/bar", Path.replaceSlashes("foo } |
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String getDirectParent(URL entry); } | @Test public void normalizeResourcePathSlash01() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/")); }
@Test public void normalizeResourcePathSlash02() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" /")); }
@Test public void normalizeResourcePathSlash03() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" / ")); }
@Test public void normalizeResourcePathSlash04() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/ ")); } |
WebAppParser { protected WebAppType parseWebXml(URL url) { try { XMLReader reader = XMLReaderFactory.createXMLReader(); NamespaceFilter inFilter = new NamespaceFilter("http: inFilter.setParent(reader); JAXBContext context = JAXBContext.newInstance(WebAppType.class); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXSource source = new SAXSource(inFilter, new InputSource(url.openStream())); return unmarshaller.unmarshal(source, WebAppType.class).getValue(); } catch (JAXBException | IOException | SAXException exc) { LOG.error("error parsing web.xml", exc); } return null; } WebAppParser(ServiceTracker<PackageAdmin, PackageAdmin> packageAdmin); void parse(final Bundle bundle, WebApp webApp); static Boolean canSeeClass(Bundle bundle, Class<?> clazz); } | @SuppressWarnings("deprecation") @Test public void testParseWebXml() throws Exception { WebAppParser parser = new WebAppParser(null); File file = new File("src/test/resources/web.xml"); assertTrue(file.exists()); WebAppType parseWebXml = parser.parseWebXml(file.toURL()); assertNotNull(parseWebXml); List<JAXBElement<?>> list = parseWebXml.getModuleNameOrDescriptionAndDisplayName(); for (JAXBElement<?> jaxbElement : list) { Object value = jaxbElement.getValue(); if (value instanceof SessionConfigType) { SessionConfigType sessionConfig = (SessionConfigType) value; BigInteger value2 = sessionConfig.getSessionTimeout().getValue(); assertThat(value2.intValue(), is(30)); } } } |
DeployerUtils { public static String[] extractNameVersionType(String url) { Matcher m = ARTIFACT_MATCHER.matcher(url); if (!m.matches()) { return new String[]{url.split("\\.")[0], DEFAULT_VERSION}; } else { StringBuilder v = new StringBuilder(); String d1 = m.group(1); String d2 = m.group(2); String d3 = m.group(3); String d4 = m.group(4); String d5 = m.group(5); String d6 = m.group(6); if (d2 != null) { v.append(d2); if (d3 != null) { v.append('.'); v.append(d3); if (d4 != null) { v.append('.'); v.append(d4); if (d5 != null) { v.append("."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0."); cleanupModifier(v, d5); } } else if (d5 != null) { v.append(".0.0."); cleanupModifier(v, d5); } } return new String[]{d1, v.toString(), d6}; } } private DeployerUtils(); static String[] extractNameVersionType(String url); } | @Test public void testExtractNameVersionType() { String[] nameVersion; nameVersion = DeployerUtils.extractNameVersionType("test-1.0.0.war"); assertEquals("test", nameVersion[0]); assertEquals("1.0.0", nameVersion[1]); nameVersion = DeployerUtils.extractNameVersionType("test.war"); assertEquals("test", nameVersion[0]); assertEquals("0.0.0", nameVersion[1]); } |
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public HttpService getService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration) { LOG.info("Binding bundle: [" + bundle + "] to http service"); return createService(bundle); } @Override HttpService getService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration,
final HttpService httpService); } | @Test public void checkGetServiceFlow() { replay(bundle, serviceRegistration, httpService); Object result = underTest.getService(bundle, serviceRegistration); assertNotNull("expect not null", result); verify(bundle, serviceRegistration, httpService); } |
HttpServiceFactoryImpl implements
ServiceFactory<HttpService> { @Override public void ungetService(final Bundle bundle, final ServiceRegistration<HttpService> serviceRegistration, final HttpService httpService) { LOG.info("Unbinding bundle: [" + bundle + "]"); ((StoppableHttpService) httpService).stop(); } @Override HttpService getService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration); @Override void ungetService(final Bundle bundle,
final ServiceRegistration<HttpService> serviceRegistration,
final HttpService httpService); } | @Test public void checkUngetServiceFlow() { httpService.stop(); replay(bundle, serviceRegistration, httpService); underTest.ungetService(bundle, serviceRegistration, httpService); verify(bundle, serviceRegistration, httpService); } |
DefaultHttpContext implements WebContainerContext { @Override public boolean handleSecurity(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { return true; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void handleSecurity() throws IOException { assertTrue(contextUnderTest.handleSecurity(null, null)); } |
DefaultHttpContext implements WebContainerContext { @Override public String getMimeType(String name) { return null; } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void getMimeType() { assertEquals(null, contextUnderTest.getMimeType(null)); } |
DefaultHttpContext implements WebContainerContext { @Override public URL getResource(final String name) { final String normalizedname = Path.normalizeResourcePath(name); LOG.debug("Searching bundle [" + bundle + "] for resource [" + normalizedname + "]"); return bundle.getResource(normalizedname); } DefaultHttpContext(final Bundle bundle, String contextID); @Override boolean handleSecurity(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse); @Override URL getResource(final String name); @Override String getMimeType(String name); @Override Set<String> getResourcePaths(final String name); @Override String getContextId(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); } | @Test public void getResource() throws MalformedURLException { URL url = new URL("file: expect(bundle.getResource("test")).andReturn(url); replay(bundle); contextUnderTest.getResource("test"); verify(bundle); } |
Path { static String replaceSlashes(final String target) { String replaced = target; if (replaced != null) { replaced = replaced.replaceAll("/+", "/"); } return replaced; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); } | @Test public void replaceSlashesWithNull() { assertEquals("Replaced", null, Path.replaceSlashes(null)); }
@Test public void replaceSlashes01() { assertEquals("Replaced", "/foo/bar/", Path.replaceSlashes("/foo/bar/")); }
@Test public void replaceSlashes02() { assertEquals("Replaced", "/", Path.replaceSlashes("/")); }
@Test public void replaceSlashes03() { assertEquals("Replaced", "/", Path.replaceSlashes(" }
@Test public void replaceSlashes04() { assertEquals("Replaced", "/foo/bar", Path.replaceSlashes(" }
@Test public void replaceSlashes05() { assertEquals("Replaced", "foo/bar/", Path.replaceSlashes("foo/bar }
@Test public void replaceSlashes06() { assertEquals("Replaced", "foo/bar", Path.replaceSlashes("foo }
@Test public void replaceSlashes07() { assertEquals("Replaced", "/foo/bar/car/", Path.replaceSlashes("/foo } |
JettyServerWrapper extends Server { HttpServiceContext getContext(final HttpContext httpContext) { readLock.lock(); try { ServletContextInfo servletContextInfo = contexts.get(httpContext); if (servletContextInfo != null) { return servletContextInfo.getHandler(); } return null; } finally { readLock.unlock(); } } JettyServerWrapper(ServerModel serverModel, ThreadPool threadPool); HandlerCollection getRootHandlerCollection(); void configureContext(final Map<String, Object> attributes, final Integer timeout, final String cookie,
final String domain, final String path, final String url, final Boolean cookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName, final Boolean lazy, final String directory,
Integer maxAge, final Boolean showStacks); void setServerConfigDir(File serverConfigDir); File getServerConfigDir(); URL getServerConfigURL(); void setServerConfigURL(URL serverConfigURL); String getDefaultAuthMethod(); void setDefaultAuthMethod(String defaultAuthMethod); String getDefaultRealmName(); void setDefaultRealmName(String defaultRealmName); } | @Test public void registrationAndUnregistrationOfTwoServletsThereShouldBeNoContexts() throws Exception { JettyServerImpl server = new JettyServerImpl(serverModelMock, null); server.start(); try { Bundle testBundle = mock(Bundle.class); ContextModel contextModel = new ContextModel(httpContextMock, testBundle, getClass().getClassLoader(), null); ServletModel servletModel1 = new ServletModel(contextModel, new DefaultServlet(), "/s1", null, null, null); ServletModel servletModel2 = new ServletModel(contextModel, new DefaultServlet(), "/s2", null, null, null); assertNull(server.getServer().getContext(httpContextMock)); server.addServlet(servletModel1); assertNotNull(server.getServer().getContext(httpContextMock)); server.addServlet(servletModel2); assertNotNull(server.getServer().getContext(httpContextMock)); server.removeServlet(servletModel1); assertNotNull(server.getServer().getContext(httpContextMock)); server.removeServlet(servletModel2); assertNull(server.getServer().getContext(httpContextMock)); } finally { server.stop(); } } |
Path { public static String normalizeResourcePath(final String path) { if (path == null) { return null; } String normalizedPath = replaceSlashes(path.trim()); if (normalizedPath.startsWith("/") && normalizedPath.length() > 1) { normalizedPath = normalizedPath.substring(1); } return normalizedPath; } private Path(); static String normalizeResourcePath(final String path); static String[] normalizePatterns(final String[] urlPatterns); static String normalizePattern(final String pattern); } | @Test public void normalizeResourcePathSlash01() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/")); }
@Test public void normalizeResourcePathSlash02() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" /")); }
@Test public void normalizeResourcePathSlash03() { assertEquals("Normalized", "/", Path.normalizeResourcePath(" / ")); }
@Test public void normalizeResourcePathSlash04() { assertEquals("Normalized", "/", Path.normalizeResourcePath("/ ")); } |
FilterModel extends Model { public String[] getDispatcher() { return dispatcher.toArray(new String[dispatcher.size()]); } FilterModel(final ContextModel contextModel, final Filter filter,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter, final boolean asyncSupported); FilterModel(final ContextModel contextModel, final Filter filter,
final Class<? extends Filter> filterClass,
final String[] urlPatterns, final String[] servletNames,
final Dictionary<String, ?> initParameter,
final boolean asyncSupported); Filter getFilter(); Class<? extends Filter> getFilterClass(); String getName(); String[] getUrlPatterns(); String[] getServletNames(); Map<String, String> getInitParams(); String[] getDispatcher(); boolean isAsyncSupported(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | @Test public void registerWithNoDispatcherInitParams() { FilterModel fm = new FilterModel(new ContextModel( createMock(WebContainerContext.class), null, getClass() .getClassLoader(), null), createMock(Filter.class), new String[]{"/*"}, null, new Hashtable<>(), false); System.out.println(Arrays.asList(fm.getDispatcher())); }
@Test public void registerWithCorrectSubsetOfDispatcherInitParams() { FilterModel fm = new FilterModel(new ContextModel( createMock(WebContainerContext.class), null, getClass() .getClassLoader(), null), createMock(Filter.class), new String[]{" private static final long serialVersionUID = 6291128067491953259L; { put(WebContainerConstants.FILTER_MAPPING_DISPATCHER, "REQUEST, FORWARD"); } }, false); System.out.println(Arrays.asList(fm.getDispatcher())); }
@Test public void registerWithFullComplimentOfDispatcherInitParams() { FilterModel fm = new FilterModel(new ContextModel( createMock(WebContainerContext.class), null, getClass() .getClassLoader(), null), createMock(Filter.class), new String[]{" private static final long serialVersionUID = 4025173284250768044L; { put(WebContainerConstants.FILTER_MAPPING_DISPATCHER, "REQUEST, FORWARD, ERROR , include"); } }, false); System.out.println(Arrays.asList(fm.getDispatcher())); } |
FileTools { public static boolean createBlankProject(String path, String projectName) { boolean result = true; result &= createDirectory(path + File.separator + projectName); result &= createAssetDirectories(path + File.separator + projectName); return result; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); } | @Test public void testCreateDirectoryStructure() { System.out.println("createDirectoryStructure"); String path = System.getProperty("user.home"); String project = "Test"; boolean expResult = true; boolean result = FileTools.createBlankProject(path, project); assertEquals(expResult, result); } |
FileTools { public static File doChoosePath() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getCurrentDirectory(); } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); } | @Test @Ignore public void testDoChoosePath() { System.out.println("doChoosePath"); File expResult = null; File result = FileTools.doChoosePath(); assertEquals(expResult, result); fail("The test case is a prototype."); } |
FileTools { public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChooser = new JFileChooser(new SingleRootFileSystemView(projectPath)); fileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter(type, extension); fileChooser.setFileFilter(filter); if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) { return fileChooser.getSelectedFile(); } } } return null; } static String getJreDirectory(); static String getBuildsDirectory(); static String getProjectsDirectory(); static String getExecutionPath(Class clazz); static boolean createBlankProject(String path, String projectName); static Project createProjectFromTemplate(String path, String projectName, String template); static boolean createAssetDirectories(String path); static File doChoosePath(); static File doChooseFile(String extension, String directory, String type); static void saveAsset(AbstractAsset asset); } | @Test @Ignore public void testDoChooseFile() { System.out.println("doChooseFile"); String extension = ""; String directory = ""; String type = ""; File expResult = null; File result = FileTools.doChooseFile(extension, directory, type); assertEquals(expResult, result); fail("The test case is a prototype."); } |
WXBizMsgCrypt { String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSET); byteCollector.addBytes(randomStrBytes); byteCollector.addBytes(networkBytesOrder); byteCollector.addBytes(textBytes); byteCollector.addBytes(appidBytes); byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); byteCollector.addBytes(padBytes); byte[] unencrypted = byteCollector.toBytes(); try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); byte[] encrypted = cipher.doFinal(unencrypted); System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation()); String base64Encrypted = base64.encodeToString(encrypted); return base64Encrypted; } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.EncryptAESError); } } WXBizMsgCrypt(String token, String encodingAesKey, String appId); String encryptMsg(String replyMsg, String timeStamp, String nonce); String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData); String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr); } | @Test public void testAesEncrypt() { try { WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); assertEquals(afterAesEncrypt, pc.encrypt(randomStr, replyMsg)); } catch (AesException e) { e.printStackTrace(); fail("no异常"); } }
@Test public void testAesEncrypt2() { try { WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); assertEquals(afterAesEncrypt2, pc.encrypt(randomStr, replyMsg2)); } catch (AesException e) { e.printStackTrace(); fail("no异常"); } } |
JSONCPARepository implements CPARepository { public boolean isValidPartnerAgreement(final Map<String, Object> fields) { PartnerAgreement agreement = (PartnerAgreement) fields.get(EbmsConstants.CPA); return agreement != null; } void init(); @Override List<PartnerAgreement> getPartnerAgreements(); @Override List<PartnerAgreement> getActivePartnerAgreements(); @Override PartnerAgreement findByCPAId(String cpaId); @Override PartnerAgreement findByServiceAndAction(final String service, final String action); @Override PartnerAgreement findByMessage(Document message, String ebmsVersion); boolean isValidPartnerAgreement(final Map<String, Object> fields); File getCpaJsonFile(); void setCpaJsonFile(File cpaJsonFile); } | @Test public void testIsValidPartnerAgreement() throws IOException { JSONCPARepository repository = new JSONCPARepository(); repository.setCpaJsonFile(fileFromClasspath("agreementWithServices.json")); repository.init(); Map<String,Object> fields = new ImmutableMap.Builder<String, Object>() .put(EbmsConstants.CPA, repository.getActivePartnerAgreements().get(0)) .build(); assertThat(repository.isValidPartnerAgreement(fields),is(true)); Map<String,Object> fields2 = new ImmutableMap.Builder<String, Object>() .put(EbmsConstants.MESSAGE_SERVICE, "service2") .put(EbmsConstants.MESSAGE_ACTION,"action1") .build(); assertThat(repository.isValidPartnerAgreement(fields2),is(false)); } |
FileMessageStore implements MessageStore { @Override public Message findByMessageId(final String messageId, String messageDirection) { return new DefaultMessage(messageId); } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); } | @Test public void testFileMessageStore() throws IOException { Exchange request = new DefaultExchange(context()); request.getIn().setHeader(EbmsConstants.EBMS_VERSION,EbmsConstants.EBMS_V3); request.getIn().setHeader(EbmsConstants.MESSAGE_ID,"testMessageID"); request.getIn().setBody(new ByteArrayInputStream("test".getBytes())); Exchange response = context().createProducerTemplate().send(MessageStore.DEFAULT_MESSAGE_STORE_ENDPOINT,request); String msgId = response.getIn().getHeader(MessageStore.JENTRATA_MESSAGE_ID, String.class); assertThat(msgId,equalTo("testMessageID")); assertThat(messageStore.findByMessageId(msgId,EbmsConstants.MESSAGE_DIRECTION_INBOUND).getMessageId(),equalTo(msgId)); } |
FileMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { try { return new FileInputStream(getFilename(messageId)); } catch (FileNotFoundException e) { return null; } } @Override void store(@Body InputStream input, Exchange exchange); @Override void storeMessage(Exchange exchange); @Override Message findByMessageId(final String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection,String status); @Override void updateMessage(final String messageId, String messageDirection, MessageStatusType status, String statusDescription); String getBaseDir(); void setBaseDir(String baseDir); String getFileNameExpression(); void setFileNameExpression(String fileNameExpression); @Override String toString(); } | @Test public void testFindPayloadById() throws Exception { testFileMessageStore(); InputStream stream = messageStore.findPayloadById("testMessageID"); assertThat(IOUtils.toString(stream),equalTo("test")); } |
EbmsUtils { public static List<Map<String, Object>> extractPartProperties(String partProperties) { List<Map<String,Object>> properites = new ArrayList<>(); if(partProperties != null && partProperties.length() > 0) { String [] propertyArray = partProperties.split(";"); for (String property : propertyArray) { String [] value = property.split("="); Map<String,Object> propertyMap = new HashMap<>(); propertyMap.put("name",value[0]); if(value.length == 2) { propertyMap.put("value",value[1]); } else { propertyMap.put("value",null); } properites.add(propertyMap); } } return properites; } private EbmsUtils(); static final SOAPMessage createSOAP11MessageFromClasspath(String filename); static final SOAPMessage createSOAP12MessageFromClasspath(String filename); static final SOAPMessage createSOAP12Message(String ebmsMessage); static final SOAPMessage createSOAP11Message(String ebmsMessage); static final SOAPMessage createSOAPMessage(String soapProtocol, String ebmsMessage); static final SOAPMessage parse(String soapProtocol, String contentType, InputStream stream); static final SOAPMessage parse(Exchange exchange); static void addAttachment(SOAPMessage soapMessage,String contentId,String contentType,InputStream content); static void addAttachment(SOAPMessage soapMessage, String payloadId, String contentType, byte[] content); static void addAttachment(SOAPMessage soapMessage, String payloadId, String contentType, byte[] content, Map<String, String> mimeHeaders); static void addGZippedAttachment(SOAPMessage soapMessage, String payloadId, byte[] content); static void addAttachment(SOAPMessage soapMessage,String contentId,String contentType,InputStream content,Map<String,String> headers); static String encodeContentId(String contentId); static String decodeContentID(String contentId); static InputStream compressStream(String compressionType, byte [] content); static byte [] compress(String compressionType, byte [] content); static byte [] decompress(String compressionType, byte [] content); static String toString(SOAPMessage soapMessage); static String toString(Document doc); static byte[] toByteArray(SOAPMessage soapMessage); static void elementToStream(Element element, OutputStream out); static final Document toXML(String xmlString); static String toStringFromClasspath(String filename); static File fileFromClasspath(String filename); static final String ebmsXpathValue(Element element,String xpath); static final Node ebmsXpathNode(String xml,String xpath); static final Node ebmsXpathNode(Node xml,String xpath); static final NodeList ebmsXpathNodeList(String xml,String xpath); static final NodeList ebmsXpathNodeList(Node xml,String xpath); static boolean hasEbmsXpath(Document element, String query); static List<Map<String, Object>> extractPartProperties(String partProperties); } | @Test public void testExtractPartProperties() { assertThat(EbmsUtils.extractPartProperties(null), hasSize(0)); assertThat(EbmsUtils.extractPartProperties(""), hasSize(0)); assertThat(EbmsUtils.extractPartProperties(";"), hasSize(0)); assertThat(EbmsUtils.extractPartProperties(";;"), hasSize(0)); List<Map<String,Object>> actual = EbmsUtils.extractPartProperties("test;"); assertThat(actual, hasSize(1)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",null)); actual = EbmsUtils.extractPartProperties("test=test1;"); assertThat(actual, hasSize(1)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",(Object)"test1")); actual = EbmsUtils.extractPartProperties("test=test1;test2="); assertThat(actual, hasSize(2)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",(Object)"test1")); assertThat(actual.get(1), hasEntry("name",(Object)"test2")); assertThat(actual.get(1), hasEntry("value",null)); actual = EbmsUtils.extractPartProperties("test=;test2=test3"); assertThat(actual, hasSize(2)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",null)); assertThat(actual.get(1), hasEntry("name",(Object)"test2")); assertThat(actual.get(1), hasEntry("value",(Object)"test3")); actual = EbmsUtils.extractPartProperties("test=;test2=test3;"); assertThat(actual, hasSize(2)); assertThat(actual.get(0), hasEntry("name",(Object)"test")); assertThat(actual.get(0), hasEntry("value",null)); assertThat(actual.get(1), hasEntry("name",(Object)"test2")); assertThat(actual.get(1), hasEntry("value",(Object)"test3")); } |
MessageDetector { public void parse(@Body InputStream input, @Headers Map<String, Object> headers) throws IOException { try { byte [] msgData = new byte[20480]; int count = input.read(msgData); if(count > 0) { String msg = new String(msgData); String soapVersion = msg.contains(EbmsConstants.SOAP_1_2_NAMESPACE) ? SOAPConstants.SOAP_1_2_PROTOCOL : SOAPConstants.SOAP_1_1_PROTOCOL; headers.put(EbmsConstants.SOAP_VERSION,soapVersion); String ebmsVersion = msg.contains(EbmsConstants.EBXML_V3_NAMESPACE) ? EbmsConstants.EBMS_V3 : EbmsConstants.EBMS_V2; headers.put(EbmsConstants.EBMS_VERSION,ebmsVersion); headers.put(EbmsConstants.MESSAGE_ID, getMessageId(msg)); headers.put(EbmsConstants.REF_TO_MESSAGE_ID, getRefMessageId(msg)); headers.put(EbmsConstants.MESSAGE_TYPE, getMessageType(msg).name()); } } finally { input.reset(); } } void parse(@Body InputStream input, @Headers Map<String, Object> headers); } | @Test public void testSoap12SignMessage() throws Exception { MessageDetector messageDetector = new MessageDetector(); Map<String,Object> headers = new HashMap<>(); InputStream stream = new ByteArrayInputStream(EbmsUtils.toStringFromClasspath("signal-message.xml").getBytes()); messageDetector.parse(stream,headers); assertThat((String) headers.get(EbmsConstants.SOAP_VERSION),equalTo(SOAPConstants.SOAP_1_2_PROTOCOL)); assertThat((String) headers.get(EbmsConstants.EBMS_VERSION),equalTo(EbmsConstants.EBMS_V3)); assertThat((String) headers.get(EbmsConstants.MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.REF_TO_MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.MESSAGE_TYPE),equalTo(MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE.name())); }
@Test public void testSoap12SignReceipt() throws Exception { MessageDetector messageDetector = new MessageDetector(); Map<String,Object> headers = new HashMap<>(); InputStream stream = new ByteArrayInputStream(EbmsUtils.toStringFromClasspath("signed-receipt.xml").getBytes()); messageDetector.parse(stream,headers); assertThat((String) headers.get(EbmsConstants.SOAP_VERSION),equalTo(SOAPConstants.SOAP_1_2_PROTOCOL)); assertThat((String) headers.get(EbmsConstants.EBMS_VERSION),equalTo(EbmsConstants.EBMS_V3)); assertThat((String) headers.get(EbmsConstants.MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.REF_TO_MESSAGE_ID),equalTo("[email protected]")); assertThat((String) headers.get(EbmsConstants.MESSAGE_TYPE),equalTo(MessageType.SIGNAL_MESSAGE.name())); } |
JDBCMessageStore implements MessageStore { @Override public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) { repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription); } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); } | @Test public void testUpdateStoreMimeMessage() throws Exception { File body = fileFromClasspath("simple-as4-receipt.xml"); String contentType = "Multipart/Related; boundary=\"----=_Part_7_10584188.1123489648993\"; type=\"application/soap+xml\"; start=\"<[email protected]>\""; String messageId = "testMimeMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); try(Connection conn = dataSource.getConnection()) { try (PreparedStatement st = conn.prepareStatement("select * from message where message_id = ?")) { st.setString(1,messageId); ResultSet resultSet = st.executeQuery(); assertThat(resultSet.next(),is(true)); assertThat(resultSet.getString("status"),equalTo("RECEIVED")); assertThat(resultSet.getString("status_description"),equalTo("Message Received")); } } } |
JDBCMessageStore implements MessageStore { @Override public Message findByMessageId(String messageId, String messageDirection) { Map<String,Object> fields = new HashMap<>(); fields.put("message_id",messageId); fields.put("message_box",messageDirection); List<Message> messages = repositoryManager.selectMessageBy(fields); if(messages.size() > 0) { return messages.get(0); } return null; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); } | @Test public void testFindByMessageId() throws Exception { String contentType = "application/soap+xml"; File body = fileFromClasspath("simple-as4-receipt.xml"); String messageId = "testSoapMessage1"; assertStoredMessage(messageId, contentType, body, MessageType.SIGNAL_MESSAGE_WITH_USER_MESSAGE); messageStore.updateMessage(messageId, EbmsConstants.MESSAGE_DIRECTION_INBOUND, MessageStatusType.RECEIVED,"Message Received"); Message message = messageStore.findByMessageId("testSoapMessage1",EbmsConstants.MESSAGE_DIRECTION_INBOUND); assertThat(message,notNullValue()); assertThat(message.getMessageId(),equalTo("testSoapMessage1")); assertThat(message.getStatus(),equalTo(MessageStatusType.RECEIVED)); assertThat(message.getStatusDescription(),equalTo("Message Received")); } |
JDBCMessageStore implements MessageStore { @Override public InputStream findPayloadById(String messageId) { InputStream payload = repositoryManager.selectRepositoryBy("message_id",messageId); return payload; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); } | @Test public void testFindPayloadById() throws Exception { testFindByMessageId(); InputStream stream = messageStore.findPayloadById("testSoapMessage1"); assertThat(stream,notNullValue()); assertThat(IOUtils.toString(stream),equalTo(IOUtils.toString(new FileInputStream(fileFromClasspath("simple-as4-receipt.xml"))))); } |
JDBCMessageStore implements MessageStore { @Override public List<Message> findByMessageStatus(String messageDirection, String status) { Map<String,Object> fields = new HashMap<>(); fields.put("status",status); fields.put("message_box",messageDirection); fields.put("orderByDesc","time_stamp"); fields.put("maxResults",100); List<Message> messages = repositoryManager.selectMessageBy(fields); return messages; } void init(); @Override void store(InputStream message, Exchange exchange); void storeMessage(Exchange exchange); @Override void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription); @Override Message findByMessageId(String messageId, String messageDirection); @Override InputStream findPayloadById(String messageId); @Override List<Message> findByMessageStatus(String messageDirection, String status); RepositoryManager getRepositoryManager(); void setRepositoryManager(RepositoryManager repositoryManager); boolean isCreateTables(); void setCreateTables(boolean createTables); UUIDGenerator getUuidGenerator(); void setUuidGenerator(UUIDGenerator uuidGenerator); } | @Test public void testFindMessageByStatus() throws Exception { testFindByMessageId(); List<Message> messages = messageStore.findByMessageStatus(EbmsConstants.MESSAGE_DIRECTION_INBOUND,MessageStatusType.RECEIVED.name()); assertThat(messages,notNullValue()); assertThat(messages,hasSize(1)); Message message = messages.get(0); assertThat(message,notNullValue()); assertThat(message.getMessageId(),equalTo("testSoapMessage1")); assertThat(message.getStatus(),equalTo(MessageStatusType.RECEIVED)); assertThat(message.getStatusDescription(),equalTo("Message Received")); } |
AvailableSegment extends Segment implements Serializable { public ITEM get(int position) { if (items == null) { return null; } if (covered(position)) { int index = position - getFrom(); return index < items.size() ? items.get(index) : null; } return null; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); } | @Test public void testGet() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); assertEquals(20, a.getFrom()); assertEquals(30, a.getTo()); assertEquals(2, a.getPage()); a.dataProvided(TestItem.range(20, 30)); assertEquals("p.20", a.get(20).toString()); assertEquals("p.29", a.get(29).toString()); assertNull(a.get(19)); assertNull(a.get(30)); } |
AvailableSegment extends Segment implements Serializable { public boolean covered(int position) { return model.getPage(position) == page; } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); } | @Test public void testCovered() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); when(model.getPage(anyInt())).thenReturn(2); assertTrue(a.covered(0)); when(model.getPage(anyInt())).thenReturn(1); assertFalse(a.covered(0)); } |
AvailableSegment extends Segment implements Serializable { public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } } AvailableSegment(UncoveringDataModel<?> model, int page); int getMaxIndex(); ITEM get(int position); boolean covered(int position); void dataProvided(List<ITEM> items); void dataProvided(List<ITEM> items, int maxIndex); List<ITEM> getData(); String toString(); } | @Test public void testDataProvided() { AvailableSegment<TestItem> a = new AvailableSegment<>(model, 2); assertNull(a.get(20)); assertNull(a.get(29)); assertNull(a.get(19)); assertNull(a.get(30)); assertEquals(0, a.getMaxIndex()); a.dataProvided(TestItem.range(20, 29)); assertEquals("p.20", a.get(20).toString()); assertEquals("p.28", a.get(28).toString()); assertNull(a.get(19)); assertNull(a.get(29)); assertNull(a.get(30)); assertEquals(29, a.getMaxIndex()); a.dataProvided(TestItem.range(20, 30)); assertEquals(30, a.getMaxIndex()); assertEquals("p.29", a.get(29).toString()); a.dataProvided(null); assertNull(a.get(20)); assertNull(a.get(29)); assertNull(a.get(19)); assertNull(a.get(30)); assertEquals(0, a.getMaxIndex()); } |
Segment implements Serializable { public Segment(UncoveringDataModel<ITEM> model, int page) { this.model = model; this.page = page; } Segment(UncoveringDataModel<ITEM> model, int page); int getFrom(); int getTo(); int getPage(); @Override boolean equals(Object o); void setModel(UncoveringDataModel<ITEM> model); @Override int hashCode(); String toString(); } | @Test public void testSegment() { UncoveringDataModel<TestItem> model = mock(UncoveringDataModel.class); when(model.getPageSize()).thenReturn(10); Segment s = new Segment(model, 20); assertEquals(200, s.getFrom()); assertEquals(210, s.getTo()); assertEquals(20, s.getPage()); } |
DataFetchManager implements DataAvailableListener<ITEM> { public synchronized void requestData(int page) { AvailableSegment<ITEM> segment = new AvailableSegment<>(dataModel, page); PrimaryRequest request = new PrimaryRequest(segment.getFrom(), segment.getTo(), dataModel.getQuery(), dataModel.isFirstQueryResult()); request.setPage(segment.getPage()); coverage.put(segment.getPage(), segment); queue.push(request); int c = bestChannel(); if (now() - fetchInProcessing[c] > delayWhenPending) { servePending(); } else { scheduleServePending(); } } DataFetchManager(); DataFetcher getDataFetcher(); DataFetchManager setDataFetcher(DataFetcher dataFetcher); UncoveringDataModel<ITEM> getDataModel(); DataFetchManager setDataModel(UncoveringDataModel<ITEM> dataModel); synchronized void requestData(int page); long getDelayWhenPending(); DataFetchManager setDelayWhenPending(long delayWhenPending); boolean alreadyFetching(int page); @Override synchronized void dataAvailable(PrimaryRequest request, PrimaryResponse<ITEM> data); @Override void notifyVisibleArea(int fromInclusive, int endExclusive); @Override synchronized void dataUnavailable(PrimaryRequest request); void reset(); DataFetchManager<ITEM> setThreads(int threads); int getTreads(); void lowMemory(); } | @Test public void testRequestData() throws Exception { DataFetchManager<TestItem> fetcher = new DataFetchManager<>(); fetcher.setDataFetcher(primary); fetcher.setDataModel(model); fetcher.setDelayWhenPending(700); fetcher.setThreads(1); int pg2 = 2; int pg10 = 10; int pg20 = 20; int pg50 = 50; AvailableSegment<TestItem> s2 = new AvailableSegment<>(model, pg2); AvailableSegment<TestItem> s10 = new AvailableSegment<>(model, pg10); AvailableSegment<TestItem> s20 = new AvailableSegment<>(model, pg20); AvailableSegment<TestItem> s50 = new AvailableSegment<>(model, pg50); assertFalse(fetcher.alreadyFetching(pg2)); assertFalse(fetcher.alreadyFetching(pg10)); assertFalse(fetcher.alreadyFetching(pg20)); assertFalse(fetcher.alreadyFetching(pg50)); fetcher.requestData(pg2); assertTrue(fetcher.alreadyFetching(pg2)); assertFalse(fetcher.alreadyFetching(pg10)); assertFalse(fetcher.alreadyFetching(pg20)); assertFalse(fetcher.alreadyFetching(pg50)); fetcher.requestData(pg10); assertTrue(fetcher.alreadyFetching(pg2)); assertTrue(fetcher.alreadyFetching(pg10)); assertFalse(fetcher.alreadyFetching(pg20)); assertFalse(fetcher.alreadyFetching(pg50)); assertFalse(fetcher.alreadyFetching(3)); fetcher.requestData(pg20); fetcher.requestData(pg50); assertTrue(fetcher.alreadyFetching(pg2)); assertTrue(fetcher.alreadyFetching(pg10)); assertTrue(fetcher.alreadyFetching(pg20)); assertTrue(fetcher.alreadyFetching(pg50)); assertNotNull(primary.request()); assertEquals("Second request must only be queued", 1, primary.requests.size()); assertEquals(s2.getFrom(), primary.request().getFrom()); assertEquals(s2.getTo(), primary.request().getTo()); PrimaryResponse r2 = new PrimaryResponse(TestItem.range(s2.getFrom(), s2.getTo()), 777); fetcher.dataAvailable(primary.request(), r2); verify(model).dataAvailable(s2); assertEquals("Second request must be sent", 2, primary.requests.size()); assertEquals("p50 request must be sent first", 500, primary.request().getFrom()); Thread.sleep(2 * (fetcher.getDelayWhenPending() + fetcher.timerExtraDelay) + 300); assertEquals("All requests must be sent", 4, primary.requests.size()); assertEquals(20, primary.requests.get(0).getFrom()); assertEquals(500, primary.requests.get(1).getFrom()); assertEquals(200, primary.requests.get(2).getFrom()); assertEquals(100, primary.requests.get(3).getFrom()); PrimaryResponse r50 = new PrimaryResponse(TestItem.range(s50.getFrom(), s50.getTo()), 777); fetcher.dataAvailable(primary.request(1), r50); verify(model).dataAvailable(s50); PrimaryResponse r20 = new PrimaryResponse(TestItem.range(s20.getFrom(), s20.getTo()), 777); fetcher.dataAvailable(primary.request(2), r20); verify(model).dataAvailable(s20); PrimaryResponse r10 = new PrimaryResponse(TestItem.range(s10.getFrom(), s10.getTo()), 777); fetcher.dataAvailable(primary.request(3), r10); verify(model).dataAvailable(s10); } |
WeatherService { public Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude) { return api.getForecastWeather(longitude, latitude) .subscribeOn(scheduler) .take(1); } @Inject WeatherService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler, ImageRequestManager imageRequestManager); Observable<Bitmap> loadIcon(String icon); Observable<TomorrowWeather> getTomorrowWeather(double longitude, double latitude); Observable<ThreeHoursForecastWeather> getForecastWeather(double longitude, double latitude); Observable<TodayWeather> getCurrentWeather(double longitude, double latitude); } | @Test public void shouldLoadForecastWeather() throws ParseException, IOException { final ThreeHoursForecastWeather item = Fakes.fakeResponse(Responses.JSON.THREE_HOUR_FORECAST); doReturn(Observable.just(item)) .when(weatherApi).getForecastWeather(anyDouble(), anyDouble()); TestObserver<ThreeHoursForecastWeather> testObserver = new TestObserver<>(); weatherService.getForecastWeather(1.0, 1.0).subscribe(testObserver); testObserver.assertSubscribed().assertNoErrors().assertComplete().assertValue(item); } |
SearchService { public Observable<SearchModel> searchByCity(String city) { lastCity = city; return api.searchWeather(city).subscribeOn(this.scheduler); } @Inject SearchService(WeatherApi api, @RxScheduler(NETWORK) Scheduler scheduler); Observable<SearchModel> searchByCity(String city); String getLastSearch(); } | @Test public void searchApiFunctionIsCalled() { final TestObserver<SearchModel> observer = new TestObserver<>(); searchService.searchByCity(CITY).subscribe(observer); verify(weatherApi).searchWeather(CITY); observer.assertSubscribed() .assertNoErrors() .assertComplete() .assertValue(item); } |
TomorrowWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(this::handleForecastDataResult, this::showError); } } @Inject @Replaceable TomorrowWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService,
WeatherService weatherService,
TomorrowWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForTomorrow(); } | @Test public void shouldNotLoadForecastsIfNoLocationIsPresent() { when(locationService.lastLocation()).thenReturn(null); vm.onViewAttached(); vm.loadForecastWeatherDataForTomorrow(); verifyZeroInteractions(weatherService); }
@Test public void shouldLoadForecastsIfLocationIsPresent() throws ParseException, IOException { double longitude = 1.0; double latitude = 1.0; final Location location = mockLocation(mock(Location.class), 1.0, 1.0); when(locationService.lastLocation()).thenReturn(location); String expectedResult = Responses.createExpectedFilteredResult(); when(weatherParser.parse(any(ThreeHoursForecastWeather.class))).thenReturn(expectedResult); when(weatherService.getForecastWeather(longitude, latitude)) .thenReturn(Observable.just(fakeResponse(Responses.JSON.THREE_HOUR_FORECAST))); vm.loadForecastWeatherDataForTomorrow(); verify(navigation).toForecastActivity(expectedResult); } |
TodayWeatherViewModel extends WeatherViewModel { public void loadForecastWeatherDataForToday() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); weatherService.getForecastWeather(longitude, latitude) .map(weatherParser::parse) .observeOn(androidScheduler) .subscribe(forecastData -> { dispatchRequestFinished(); navigateToForecastActivity(forecastData); }, this::showError); } } @Inject @Replaceable TodayWeatherViewModel(NavigationController navigation,
@RxObservable(PAGE) Observable<Integer> pageChangeObservable,
PermissionService permissionService,
LocationService locationService, WeatherService weatherService,
TodayWeatherResponseFilter weatherParser,
@RxScheduler(MAIN) Scheduler androidScheduler); void loadForecastWeatherDataForToday(); } | @Test public void shouldNotLoadForecastsIfNoLocationIsPresent() { when(locationService.lastLocation()).thenReturn(null); vm.onViewAttached(); vm.loadForecastWeatherDataForToday(); verifyZeroInteractions(weatherService); }
@Test public void shouldLoadForecastsIfLocationIsPresent() throws ParseException, IOException { double longitude = 1.0; double latitude = 1.0; final Location location = mockLocation(mock(Location.class), 1.0, 1.0); when(locationService.lastLocation()).thenReturn(location); String expectedResult = Responses.createExpectedFilteredResult(); when(weatherParser.parse(any(ThreeHoursForecastWeather.class))).thenReturn(expectedResult); when(weatherService.getForecastWeather(longitude, latitude)) .thenReturn(Observable.just(fakeResponse(Responses.JSON.THREE_HOUR_FORECAST))); vm.loadForecastWeatherDataForToday(); verify(navigation).toForecastActivity(expectedResult); } |
SyncTrigger { public void check(){ check(false); } SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold); SyncTrigger(DoThisWhenTriggered doThisWhenTriggered, CheckTriggerThreshold checkTriggerThreshold, ResetRule resetRule); void check(); void checkLazy(); } | @Test public void testCheckReset_IMMEDIATELY() { SyncTrigger syncTrigger = new SyncTrigger( () -> mockTrigger.triggered(), () -> mockThreshold.shouldTrigger(), IMMEDIATELY); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); }
@Test public void testCheckReset_ONLY_AFTER_REVERSION() { SyncTrigger syncTrigger = new SyncTrigger( () -> mockTrigger.triggered(), () -> mockThreshold.shouldTrigger(), ONLY_AFTER_REVERSION); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); }
@Test public void testCheckReset_NEVER() { SyncTrigger syncTrigger = new SyncTrigger( () -> mockTrigger.triggered(), () -> mockThreshold.shouldTrigger(), NEVER); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, times(1)).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(false); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); when(mockThreshold.shouldTrigger()).thenReturn(true); syncTrigger.check(); verify(mockTrigger, never()).triggered(); verify(mockThreshold, times(1)).shouldTrigger(); reset(mockTrigger); reset(mockThreshold); } |
BasicTextWrapper { public static List<String> wrapMonospaceText(String fullText, int charactersAvailable) { Affirm.notNull(fullText); if (charactersAvailable <= 0) { throw new IllegalArgumentException("charactersAvailable needs to be larger than 0, charactersAvailable:" + charactersAvailable); } List<String> linesWithExtractedLineBreaks = new ArrayList<>(); expandLineBreaks(linesWithExtractedLineBreaks, fullText); List<String> finalLines = new ArrayList<>(); for (String line : linesWithExtractedLineBreaks) { if (EMPTY.equals(line)) { finalLines.add(line); } else { String trimmedLine = line.trim(); if (EMPTY.equals(trimmedLine)) { finalLines.add(SPACE); } else { StringTokenizer stringTokenizer = new StringTokenizer(line, SPACE, false); List<String> words = new ArrayList<String>(); while (stringTokenizer.hasMoreTokens()) { words.add(stringTokenizer.nextToken()); } extractWrappedLines(finalLines, words, charactersAvailable); } } } return finalLines; } static List<String> wrapMonospaceText(String fullText, int charactersAvailable); static final String SPACE; static final String EMPTY; } | @Test public void testMultipleSpaceText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(DOUBLE_SPACE_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE_DOUBLE_SPACE, wrappedLines.get(0)); Assert.assertEquals("-multi space text", wrappedLines.get(1)); Assert.assertEquals(2, wrappedLines.size()); }
@Test public void testLineBreakText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LINE_BREAK_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE_LINE_BREAK, wrappedLines.get(0)); Assert.assertEquals("fox jumped over the abc defghi", wrappedLines.get(1)); Assert.assertEquals("jklmnopqrstuvwxyz0123", wrappedLines.get(2)); Assert.assertEquals("", wrappedLines.get(3)); Assert.assertEquals("", wrappedLines.get(4)); Assert.assertEquals("45678 9abcde fghijklm nopqrs tuvwxyz0", wrappedLines.get(5)); Assert.assertEquals("123456", wrappedLines.get(6)); Assert.assertEquals(7, wrappedLines.size()); }
@Test public void testLongText_zeroWidthAvailable() { boolean exceptionThrown = false; try { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_TEXT, ZERO_CHARACTERS_AVAILABLE); } catch (IllegalArgumentException e) { exceptionThrown = true; } Assert.assertEquals(true, exceptionThrown); }
@Test public void testMediumText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE, wrappedLines.get(0)); Assert.assertEquals(SECOND_LINE, wrappedLines.get(1)); Assert.assertEquals(THIRD_LINE, wrappedLines.get(2)); Assert.assertEquals(3, wrappedLines.size()); }
@Test public void testSmallText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(SHORT_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(SHORT_TEXT, wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
@Test public void testEmptyText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(EMPTY_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals("", wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
@Test public void testSpaceText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(SPACE_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(SPACE_TEXT, wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
@Test public void testLongSpaceText_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_SPACE_TEXT, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(SPACE_TEXT, wrappedLines.get(0)); Assert.assertEquals(1, wrappedLines.size()); }
@Test public void testShortText_tinyWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(SHORT_TEXT, TINY_CHARACTERS_AVAILABLE); Assert.assertEquals("h", wrappedLines.get(0)); Assert.assertEquals("e", wrappedLines.get(1)); Assert.assertEquals("l", wrappedLines.get(2)); Assert.assertEquals("l", wrappedLines.get(3)); Assert.assertEquals("o", wrappedLines.get(4)); Assert.assertEquals(5, wrappedLines.size()); }
@Test public void testLongTextWithLongWord_mediumWidthAvailable() { List<String> wrappedLines = BasicTextWrapper.wrapMonospaceText(LONG_TEXT_LONG_WORD, MEDIUM_CHARACTERS_AVAILABLE); Assert.assertEquals(FIRST_LINE, wrappedLines.get(0)); Assert.assertEquals("1", wrappedLines.get(1)); Assert.assertEquals("abcdefghijklmnopqrstuvwxyz0123456789abcd", wrappedLines.get(2)); Assert.assertEquals("efghijklmnopqrstuvwxyz0123456789 the", wrappedLines.get(3)); Assert.assertEquals("quick brown fox", wrappedLines.get(4)); Assert.assertEquals(5, wrappedLines.size()); } |
TextPadder { public static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter) { Affirm.notNull(textOriginal); Affirm.notNull(pad); int paddingCharactersRequired = desiredLength - textOriginal.length(); if (paddingCharactersRequired < 0) { throw new IllegalArgumentException("textOriginal is already longer than the desiredLength, textOriginal.length():" + textOriginal.length() + " desiredLength:" + desiredLength); } StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < paddingCharactersRequired; ii++) { sb.append(paddingCharacter); } if (pad == LEFT) { sb.append(textOriginal); } else { sb.insert(0, textOriginal); } return sb.toString(); } static String padText(String textOriginal, int desiredLength, Pad pad, char paddingCharacter); } | @Test public void testPaddingOnTheRight() { String paddedText = TextPadder.padText(TEXT_ORIG, 10, TextPadder.Pad.RIGHT, '+'); Assert.assertEquals(TEXT_ORIG + "+++++++", paddedText); }
@Test public void testPaddingOnTheLeft() { String paddedText = TextPadder.padText(TEXT_ORIG, 10, TextPadder.Pad.LEFT, '*'); Assert.assertEquals("*******" + TEXT_ORIG, paddedText); }
@Test public void testPaddingWhenAlreadyPadded() { String paddedText = TextPadder.padText(TEXT_ORIG, 3, TextPadder.Pad.LEFT, PADDING_CHARACTER); Assert.assertEquals(TEXT_ORIG, paddedText); }
@Test public void testPaddingIllegalValues() { try { TextPadder.padText(null, 3, TextPadder.Pad.LEFT, PADDING_CHARACTER); Assert.fail("should have thrown an exception by now: original text was null"); } catch (Exception e) { } try { TextPadder.padText(TEXT_ORIG, 3, null, PADDING_CHARACTER); Assert.fail("should have thrown an exception by now: pad direction was null"); } catch (Exception e) { } try { TextPadder.padText(TEXT_ORIG, 2, TextPadder.Pad.LEFT, PADDING_CHARACTER); Assert.fail("should have thrown an exception by now: original text was already longer than the desiredLength"); } catch (Exception e) { } } |
CounterWithProgress extends ObservableImp { @SuppressLint("StaticFieldLeak") public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new Async<Void, Integer, Integer>(workMode) { @Override protected Integer doInBackground(Void... voids) { int totalIncrease = 0; for (int ii=0; ii<20; ii++) { synchronized (this) { try { wait(workMode == WorkMode.SYNCHRONOUS ? 1 : 100); } catch (InterruptedException e) { } } publishProgressTask(++totalIncrease); } return totalIncrease; } @Override protected void onProgressUpdate(Integer... values) { logger.i(TAG, "-tick-"); progress = values[0]; notifyObservers(); } @Override protected void onPostExecute(Integer result) { logger.i(TAG, "done"); count = count + result; isBusy = false; progress = 0; notifyObservers(); } }.executeTask((Void)null); } CounterWithProgress(WorkMode workMode, Logger logger); @SuppressLint("StaticFieldLeak") void increaseBy20(); boolean isBusy(); int getCount(); int getProgress(); static final String TAG; } | @Test public void observersNotifiedAtLeastOnce() throws Exception { CounterWithProgress counterWithProgress = new CounterWithProgress(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); counterWithProgress.addObserver(mockObserver); counterWithProgress.increaseBy20(); verify(mockObserver, atLeastOnce()).somethingChanged(); } |
CounterWithLambdas extends ObservableImp { public void increaseBy20(){ logger.i(TAG, "increaseBy20()"); isBusy = true; notifyObservers(); new AsyncBuilder<Void, Integer>(workMode) .doInBackground(input -> CounterWithLambdas.this.doStuffInBackground(input)) .onPostExecute(result -> CounterWithLambdas.this.doThingsWithTheResult(result)) .execute((Void) null); } CounterWithLambdas(WorkMode workMode, Logger logger); void increaseBy20(); boolean isBusy(); int getCount(); static final String TAG; } | @Test public void observersNotifiedAtLeastOnce() throws Exception { CounterWithLambdas counterWithLambdas = new CounterWithLambdas(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); counterWithLambdas.addObserver(mockObserver); counterWithLambdas.increaseBy20(); verify(mockObserver, atLeastOnce()).somethingChanged(); } |
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void addNewTrack() { logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); } | @Test public void addNewTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.addNewTrack(); Assert.assertEquals(1, playlistAdvancedModel.getTrackListSize()); Assert.assertEquals(1, playlistAdvancedModel.getTrack(0).getNumberOfPlaysRequested()); }
@Test public void observersNotifiedAtLeastOnceForAddTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); playlistAdvancedModel.addObserver(mockObserver); playlistAdvancedModel.addNewTrack(); verify(mockObserver, atLeastOnce()).somethingChanged(); } |
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeTrack(int index) { logger.i(TAG, "removeTrack() " + index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); } | @Test public void removeTrack() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.removeTrack(0); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); } |
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); } | @Test public void add5NewTracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); Assert.assertEquals(5, playlistAdvancedModel.getTrackListSize()); Assert.assertEquals(1, playlistAdvancedModel.getTrack(4).getNumberOfPlaysRequested()); } |
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.removeRange(0, 5); notifyObservers(); } } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); } | @Test public void remove5Tracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); playlistAdvancedModel.remove5Tracks(); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); } |
PlaylistAdvancedModel extends ObservableImp implements Updateable { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistAdvancedModel(SystemTimeWrapper systemTimeWrapper, WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); @Override UpdateSpec getAndClearLatestUpdateSpec(long maxAgeMs); } | @Test public void removeAllTracks() throws Exception { PlaylistAdvancedModel playlistAdvancedModel = new PlaylistAdvancedModel(mockSystemTimeWrapper, WorkMode.SYNCHRONOUS, logger); playlistAdvancedModel.add5NewTracks(); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.addNewTrack(); playlistAdvancedModel.removeAllTracks(); Assert.assertEquals(0, playlistAdvancedModel.getTrackListSize()); } |
PlaylistSimpleModel extends ObservableImp { public int getTrackListSize(){ return trackList.size(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); } | @Test public void initialConditions() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(false, playlistSimpleModel.hasObservers()); } |
PlaylistSimpleModel extends ObservableImp { public void addNewTrack(){ logger.i(TAG, "addNewTrack()"); trackList.add(new Track(generateRandomColourResource())); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); } | @Test public void addNewTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.addNewTrack(); Assert.assertEquals(1, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(1, playlistSimpleModel.getTrack(0).getNumberOfPlaysRequested()); }
@Test public void observersNotifiedAtLeastOnceForAddTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); Observer mockObserver = mock(Observer.class); playlistSimpleModel.addObserver(mockObserver); playlistSimpleModel.addNewTrack(); verify(mockObserver, atLeastOnce()).somethingChanged(); } |
PlaylistSimpleModel extends ObservableImp { public void removeTrack(int index){ logger.i(TAG, "removeTrack() "+index); checkIndex(index); trackList.remove(index); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); } | @Test public void removeTrack() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.addNewTrack(); playlistSimpleModel.removeTrack(0); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); } |
PlaylistSimpleModel extends ObservableImp { public void add5NewTracks() { logger.i(TAG, "add5NewTracks()"); List<Track> newTracks = new ArrayList<>(); for (int ii=0; ii<5; ii++){ newTracks.add(new Track(generateRandomColourResource())); } trackList.addAll(0, newTracks); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); } | @Test public void add5NewTracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); Assert.assertEquals(5, playlistSimpleModel.getTrackListSize()); Assert.assertEquals(1, playlistSimpleModel.getTrack(4).getNumberOfPlaysRequested()); } |
PlaylistSimpleModel extends ObservableImp { public void remove5Tracks() { logger.i(TAG, "remove5Tracks()"); if (getTrackListSize()>4){ trackList.subList(0, 5).clear(); notifyObservers(); } } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); } | @Test public void remove5Tracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); playlistSimpleModel.remove5Tracks(); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); } |
PlaylistSimpleModel extends ObservableImp { public void removeAllTracks() { logger.i(TAG, "removeAllTracks()"); trackList.clear(); notifyObservers(); } PlaylistSimpleModel(WorkMode workMode, Logger logger); void addNewTrack(); void removeTrack(int index); void removeAllTracks(); void increasePlaysForTrack(int index); void decreasePlaysForTrack(int index); Track getTrack(int index); int getTrackListSize(); void add5NewTracks(); void remove5Tracks(); } | @Test public void removeAllTracks() throws Exception { PlaylistSimpleModel playlistSimpleModel = new PlaylistSimpleModel(WorkMode.SYNCHRONOUS, logger); playlistSimpleModel.add5NewTracks(); playlistSimpleModel.addNewTrack(); playlistSimpleModel.addNewTrack(); playlistSimpleModel.removeAllTracks(); Assert.assertEquals(0, playlistSimpleModel.getTrackListSize()); } |
Wallet extends ObservableImp { public void increaseMobileWallet() { if (canIncrease()) { mobileWalletDollars++; logger.i(TAG, "Increasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); final int totalDollarsAvailable; } | @Test public void increaseMobileWallet() throws Exception { Wallet wallet = new Wallet(logger); wallet.increaseMobileWallet(); Assert.assertEquals(true, wallet.canIncrease()); Assert.assertEquals(true, wallet.canDecrease()); Assert.assertEquals(wallet.totalDollarsAvailable - 1, wallet.getSavingsWalletAmount()); Assert.assertEquals(1, wallet.getMobileWalletAmount()); }
@Test public void observersNotifiedAtLeastOnceForIncrease() throws Exception { Wallet wallet = new Wallet(logger); Observer mockObserver = mock(Observer.class); wallet.addObserver(mockObserver); wallet.increaseMobileWallet(); verify(mockObserver, atLeastOnce()).somethingChanged(); } |
Wallet extends ObservableImp { public void decreaseMobileWallet(){ if (canDecrease()) { mobileWalletDollars--; logger.i(TAG, "Decreasing mobile wallet to:" + mobileWalletDollars); notifyObservers(); } } Wallet(Logger logger); void increaseMobileWallet(); void decreaseMobileWallet(); int getMobileWalletAmount(); int getSavingsWalletAmount(); boolean canIncrease(); boolean canDecrease(); final int totalDollarsAvailable; } | @Test public void decreaseMobileWallet() throws Exception { Wallet wallet = new Wallet(logger); wallet.increaseMobileWallet(); Assert.assertEquals(1, wallet.getMobileWalletAmount()); wallet.decreaseMobileWallet(); Assert.assertEquals(true, wallet.canIncrease()); Assert.assertEquals(false, wallet.canDecrease()); Assert.assertEquals(wallet.totalDollarsAvailable, wallet.getSavingsWalletAmount()); Assert.assertEquals(0, wallet.getMobileWalletAmount()); } |
AmazonWebServiceClient { public String getServiceName() { return getServiceNameIntern(); } protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final RequestMetricCollector requestMetricCollector); protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient,
final RequestMetricCollector requestMetricCollector); void setEndpoint(final String endpoint); String getEndpoint(); String getEndpointPrefix(); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setEndpoint(final String endpoint,
final String serviceName,
final String regionId); @SuppressWarnings("checkstyle:hiddenfield") Signer getSignerByURI(final URI uri); @SuppressWarnings("checkstyle:hiddenfield") void setRegion(final Region region); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setConfiguration(final ClientConfiguration clientConfiguration); void shutdown(); @Deprecated void addRequestHandler(final RequestHandler requestHandler); void addRequestHandler(final RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(final RequestHandler requestHandler); void removeRequestHandler(final RequestHandler2 requestHandler2); void setTimeOffset(final int timeOffset); @SuppressWarnings("checkstyle:hiddenfield") AmazonWebServiceClient withTimeOffset(final int timeOffset); int getTimeOffset(); @Deprecated RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); @SuppressWarnings("checkstyle:hiddenfield") final void setServiceNameIntern(final String serviceName); final String getSignerRegionOverride(); @SuppressWarnings("checkstyle:hiddenfield") final void setSignerRegionOverride(final String signerRegionOverride); static final boolean LOGGING_AWS_REQUEST_METRIC; } | @Test public void emptyClient() { final AmazonWebServiceClient client = new AmazonWebServiceClient(new ClientConfiguration()) { }; try { client.getServiceName(); } catch (final IllegalStateException exception) { } }
@Test public void testGetServiceNameWithExplicitInternalConfiguration() { final AmazonSimpleDBClient testClient = new AmazonSimpleDBClient(); assertEquals(testClient.getServiceName(), "sdb"); }
@Test public void testGetServiceNameWithAWSPrefix() { final AWSTestClient testClient = new AWSTestClient(); assertEquals(testClient.getServiceName(), "test"); } |
AmazonWebServiceClient { protected Signer getSigner() { return signer; } protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final RequestMetricCollector requestMetricCollector); protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient,
final RequestMetricCollector requestMetricCollector); void setEndpoint(final String endpoint); String getEndpoint(); String getEndpointPrefix(); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setEndpoint(final String endpoint,
final String serviceName,
final String regionId); @SuppressWarnings("checkstyle:hiddenfield") Signer getSignerByURI(final URI uri); @SuppressWarnings("checkstyle:hiddenfield") void setRegion(final Region region); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setConfiguration(final ClientConfiguration clientConfiguration); void shutdown(); @Deprecated void addRequestHandler(final RequestHandler requestHandler); void addRequestHandler(final RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(final RequestHandler requestHandler); void removeRequestHandler(final RequestHandler2 requestHandler2); void setTimeOffset(final int timeOffset); @SuppressWarnings("checkstyle:hiddenfield") AmazonWebServiceClient withTimeOffset(final int timeOffset); int getTimeOffset(); @Deprecated RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); @SuppressWarnings("checkstyle:hiddenfield") final void setServiceNameIntern(final String serviceName); final String getSignerRegionOverride(); @SuppressWarnings("checkstyle:hiddenfield") final void setSignerRegionOverride(final String signerRegionOverride); static final boolean LOGGING_AWS_REQUEST_METRIC; } | @Test public void testOverrideSigner() { final ClientConfiguration config = new ClientConfiguration(); config.setSignerOverride("QueryStringSignerType"); final AmazonTestClient client = new AmazonTestClient(config); Assert.assertTrue(client.getSigner() instanceof QueryStringSigner); } |
AmazonWebServiceClient { @SuppressWarnings("checkstyle:hiddenfield") public final void setServiceNameIntern(final String serviceName) { this.serviceName = serviceName; } protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final RequestMetricCollector requestMetricCollector); protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient,
final RequestMetricCollector requestMetricCollector); void setEndpoint(final String endpoint); String getEndpoint(); String getEndpointPrefix(); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setEndpoint(final String endpoint,
final String serviceName,
final String regionId); @SuppressWarnings("checkstyle:hiddenfield") Signer getSignerByURI(final URI uri); @SuppressWarnings("checkstyle:hiddenfield") void setRegion(final Region region); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setConfiguration(final ClientConfiguration clientConfiguration); void shutdown(); @Deprecated void addRequestHandler(final RequestHandler requestHandler); void addRequestHandler(final RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(final RequestHandler requestHandler); void removeRequestHandler(final RequestHandler2 requestHandler2); void setTimeOffset(final int timeOffset); @SuppressWarnings("checkstyle:hiddenfield") AmazonWebServiceClient withTimeOffset(final int timeOffset); int getTimeOffset(); @Deprecated RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); @SuppressWarnings("checkstyle:hiddenfield") final void setServiceNameIntern(final String serviceName); final String getSignerRegionOverride(); @SuppressWarnings("checkstyle:hiddenfield") final void setSignerRegionOverride(final String signerRegionOverride); static final boolean LOGGING_AWS_REQUEST_METRIC; } | @Test public void setServiceNameIntern() { final AmazonTestClient client = new AmazonTestClient(); assertEquals(client.getServiceName(), client.getServiceNameIntern()); final String serviceNameOverride = "foo"; assertFalse(serviceNameOverride.equals(client.getServiceName())); client.setServiceNameIntern(serviceNameOverride); assertEquals(serviceNameOverride, client.getServiceName()); } |
AmazonWebServiceClient { public void setEndpoint(final String endpoint) { final URI uri = toURI(endpoint); @SuppressWarnings("checkstyle:hiddenfield") final Signer signer = computeSignerByURI(uri, signerRegionOverride, false); synchronized (this) { this.endpoint = uri; this.signer = signer; } } protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final RequestMetricCollector requestMetricCollector); protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient,
final RequestMetricCollector requestMetricCollector); void setEndpoint(final String endpoint); String getEndpoint(); String getEndpointPrefix(); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setEndpoint(final String endpoint,
final String serviceName,
final String regionId); @SuppressWarnings("checkstyle:hiddenfield") Signer getSignerByURI(final URI uri); @SuppressWarnings("checkstyle:hiddenfield") void setRegion(final Region region); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setConfiguration(final ClientConfiguration clientConfiguration); void shutdown(); @Deprecated void addRequestHandler(final RequestHandler requestHandler); void addRequestHandler(final RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(final RequestHandler requestHandler); void removeRequestHandler(final RequestHandler2 requestHandler2); void setTimeOffset(final int timeOffset); @SuppressWarnings("checkstyle:hiddenfield") AmazonWebServiceClient withTimeOffset(final int timeOffset); int getTimeOffset(); @Deprecated RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); @SuppressWarnings("checkstyle:hiddenfield") final void setServiceNameIntern(final String serviceName); final String getSignerRegionOverride(); @SuppressWarnings("checkstyle:hiddenfield") final void setSignerRegionOverride(final String signerRegionOverride); static final boolean LOGGING_AWS_REQUEST_METRIC; } | @Test public void testSetEndpoint() throws URISyntaxException { final AmazonTestClient client = new AmazonTestClient(); client.setEndpoint("http: assertEquals(client.endpoint, new URI("http: } |
AmazonWebServiceClient { @SuppressWarnings("checkstyle:hiddenfield") public final void setSignerRegionOverride(final String signerRegionOverride) { final Signer signer = computeSignerByURI(endpoint, signerRegionOverride, true); synchronized (this) { this.signer = signer; this.signerRegionOverride = signerRegionOverride; } } protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final RequestMetricCollector requestMetricCollector); protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient,
final RequestMetricCollector requestMetricCollector); void setEndpoint(final String endpoint); String getEndpoint(); String getEndpointPrefix(); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setEndpoint(final String endpoint,
final String serviceName,
final String regionId); @SuppressWarnings("checkstyle:hiddenfield") Signer getSignerByURI(final URI uri); @SuppressWarnings("checkstyle:hiddenfield") void setRegion(final Region region); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setConfiguration(final ClientConfiguration clientConfiguration); void shutdown(); @Deprecated void addRequestHandler(final RequestHandler requestHandler); void addRequestHandler(final RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(final RequestHandler requestHandler); void removeRequestHandler(final RequestHandler2 requestHandler2); void setTimeOffset(final int timeOffset); @SuppressWarnings("checkstyle:hiddenfield") AmazonWebServiceClient withTimeOffset(final int timeOffset); int getTimeOffset(); @Deprecated RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); @SuppressWarnings("checkstyle:hiddenfield") final void setServiceNameIntern(final String serviceName); final String getSignerRegionOverride(); @SuppressWarnings("checkstyle:hiddenfield") final void setSignerRegionOverride(final String signerRegionOverride); static final boolean LOGGING_AWS_REQUEST_METRIC; } | @Test public void testSetSignerRegionOverride() { final AmazonTestClient client = new AmazonTestClient(); client.setSignerRegionOverride("test"); assertEquals(client.getSignerRegionOverride(), "test"); } |
AmazonWebServiceClient { protected ExecutionContext createExecutionContext(final AmazonWebServiceRequest req) { final boolean isMetricsEnabled = isRequestMetricsEnabled(req) || isProfilingEnabled(); return new ExecutionContext(requestHandler2s, isMetricsEnabled, this); } protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final RequestMetricCollector requestMetricCollector); protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient); @Deprecated protected AmazonWebServiceClient(
final ClientConfiguration clientConfiguration,
final HttpClient httpClient,
final RequestMetricCollector requestMetricCollector); void setEndpoint(final String endpoint); String getEndpoint(); String getEndpointPrefix(); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setEndpoint(final String endpoint,
final String serviceName,
final String regionId); @SuppressWarnings("checkstyle:hiddenfield") Signer getSignerByURI(final URI uri); @SuppressWarnings("checkstyle:hiddenfield") void setRegion(final Region region); @Deprecated @SuppressWarnings("checkstyle:hiddenfield") void setConfiguration(final ClientConfiguration clientConfiguration); void shutdown(); @Deprecated void addRequestHandler(final RequestHandler requestHandler); void addRequestHandler(final RequestHandler2 requestHandler2); @Deprecated void removeRequestHandler(final RequestHandler requestHandler); void removeRequestHandler(final RequestHandler2 requestHandler2); void setTimeOffset(final int timeOffset); @SuppressWarnings("checkstyle:hiddenfield") AmazonWebServiceClient withTimeOffset(final int timeOffset); int getTimeOffset(); @Deprecated RequestMetricCollector getRequestMetricsCollector(); String getServiceName(); @SuppressWarnings("checkstyle:hiddenfield") final void setServiceNameIntern(final String serviceName); final String getSignerRegionOverride(); @SuppressWarnings("checkstyle:hiddenfield") final void setSignerRegionOverride(final String signerRegionOverride); static final boolean LOGGING_AWS_REQUEST_METRIC; } | @Test public void testCreateExecutionContextWithAmazonWebServiceRequest() { final AmazonWebServiceRequest awsr = new TestRequest(); final AmazonTestClient client = new AmazonTestClient(); final ExecutionContext ec = client.createExecutionContext(awsr); assertEquals(client.requestHandler2s, ec.getRequestHandler2s()); }
@Test public void testCreateExecutionContextWithRequest() { final AmazonWebServiceRequest awsr = new TestRequest(); final Request<String> req = new DefaultRequest<String>(awsr, "test"); final AmazonTestClient client = new AmazonTestClient(); final ExecutionContext ec = client.createExecutionContext(req); assertEquals(client.requestHandler2s, ec.getRequestHandler2s()); } |
AmazonHttpClient { void setUserAgent(Request<?> request) { String userAgent = ClientConfiguration.DEFAULT_USER_AGENT; final AmazonWebServiceRequest awsreq = request.getOriginalRequest(); if (awsreq != null) { final RequestClientOptions opts = awsreq.getRequestClientOptions(); if (opts != null) { final String userAgentMarker = opts.getClientMarker(Marker.USER_AGENT); if (userAgentMarker != null) { userAgent = createUserAgentString(userAgent, userAgentMarker); } } } if (!ClientConfiguration.DEFAULT_USER_AGENT.equals(config.getUserAgent())) { userAgent = createUserAgentString(userAgent, config.getUserAgent()); } request.addHeader(HEADER_USER_AGENT, userAgent); } AmazonHttpClient(ClientConfiguration config); @Deprecated AmazonHttpClient(ClientConfiguration config,
RequestMetricCollector requestMetricCollector); AmazonHttpClient(ClientConfiguration config, HttpClient httpClient); @Deprecated AmazonHttpClient(ClientConfiguration config, HttpClient httpClient,
RequestMetricCollector requestMetricCollector); @Deprecated ResponseMetadata getResponseMetadataForRequest(AmazonWebServiceRequest request); Response<T> execute(Request<?> request,
HttpResponseHandler<AmazonWebServiceResponse<T>> responseHandler,
HttpResponseHandler<AmazonServiceException> errorResponseHandler,
ExecutionContext executionContext); void shutdown(); RequestMetricCollector getRequestMetricCollector(); } | @Test public void testSetUserAgentDefault() { ClientConfiguration config = new ClientConfiguration(); client = new AmazonHttpClient(config); final Request<?> request = new DefaultRequest<String>("ServiceName"); client.setUserAgent(request); String userAgent = request.getHeaders().get("User-Agent"); assertEquals("same user agent", ClientConfiguration.DEFAULT_USER_AGENT, userAgent); }
@Test public void testSetUserAgentCustom() { String versionInfoUserAgent = ClientConfiguration.DEFAULT_USER_AGENT; String customUserAgent = "custom_user_agent"; String requestUserAgent = "request_user_agent"; String targetUserAgent = versionInfoUserAgent + " " + requestUserAgent + " " + customUserAgent; AmazonWebServiceRequest originalRequest = new AmazonWebServiceRequest() { }; RequestClientOptions opts = originalRequest.getRequestClientOptions(); opts.appendUserAgent("request_user_agent"); ClientConfiguration config = new ClientConfiguration(); config.setUserAgent("custom_user_agent"); client = new AmazonHttpClient(config); final Request<?> request = new DefaultRequest<String>(originalRequest, "ServiceName"); client.setUserAgent(request); String userAgent = request.getHeaders().get("User-Agent"); assertEquals("same user agent", targetUserAgent, userAgent); } |
HttpRequestFactory { public HttpRequest createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration, ExecutionContext context) { final URI endpoint = request.getEndpoint(); String uri = HttpUtils.appendUri(endpoint.toString(), request.getResourcePath(), true); final String encodedParams = HttpUtils.encodeParameters(request); HttpMethodName method = request.getHttpMethod(); final boolean requestHasNoPayload = request.getContent() != null; final boolean requestIsPost = method == HttpMethodName.POST; final boolean putParamsInUri = !requestIsPost || requestHasNoPayload; if (encodedParams != null && putParamsInUri) { uri += "?" + encodedParams; } final Map<String, String> headers = new HashMap<String, String>(); configureHeaders(headers, request, context, clientConfiguration); InputStream is = request.getContent(); if (method == HttpMethodName.PATCH) { method = HttpMethodName.POST; headers.put("X-HTTP-Method-Override", HttpMethodName.PATCH.toString()); } if (method == HttpMethodName.POST) { if (request.getContent() == null && encodedParams != null) { final byte[] contentBytes = encodedParams.getBytes(StringUtils.UTF8); is = new ByteArrayInputStream(contentBytes); headers.put("Content-Length", String.valueOf(contentBytes.length)); } } if (clientConfiguration.isEnableGzip() && headers.get("Accept-Encoding") == null) { headers.put("Accept-Encoding", "gzip"); } else { headers.put("Accept-Encoding", "identity"); } final HttpRequest httpRequest = new HttpRequest(method.toString(), URI.create(uri), headers, is); httpRequest.setStreaming(request.isStreaming()); return httpRequest; } HttpRequest createHttpRequest(Request<?> request,
ClientConfiguration clientConfiguration, ExecutionContext context); } | @Test public void testContextUserAgent() { final String contextUserAgent = "context_user_agent"; context.setContextUserAgent(contextUserAgent); final HttpRequest httpRequest = factory.createHttpRequest(request, clientConfiguration, context); final String userAgent = httpRequest.getHeaders().get(HttpHeader.USER_AGENT); assertTrue("context user agent", userAgent.endsWith(contextUserAgent)); }
@Test public void testHeaders() { final HttpRequest httpRequest = factory.createHttpRequest(request, clientConfiguration, context); final Map<String, String> headers = httpRequest.getHeaders(); assertNotNull(headers.get(HttpHeader.HOST)); assertNotNull(headers.get(HttpHeader.CONTENT_TYPE)); }
@Test public void testEnableCompression() { clientConfiguration.withEnableGzip(true); final HttpRequest httpRequest = factory.createHttpRequest(request, clientConfiguration, context); final Map<String, String> headers = httpRequest.getHeaders(); assertEquals("accept encoding is gzip", "gzip", headers.get("Accept-Encoding")); } |
ClientConnectionRequestFactory { static ClientConnectionRequest wrap(ClientConnectionRequest orig) { if (orig instanceof Wrapped) throw new IllegalArgumentException(); return (ClientConnectionRequest) Proxy.newProxyInstance( ClientConnectionRequestFactory.class.getClassLoader(), INTERFACES, new Handler(orig)); } } | @Test public void wrapOnce() { ClientConnectionRequest wrapped = ClientConnectionRequestFactory.wrap(noop); assertTrue(wrapped instanceof Wrapped); }
@Test(expected = IllegalArgumentException.class) public void wrapTwice() { ClientConnectionRequest wrapped = ClientConnectionRequestFactory.wrap(noop); ClientConnectionRequestFactory.wrap(wrapped); } |
ClientConnectionManagerFactory { public static ClientConnectionManager wrap(ClientConnectionManager orig) { if (orig instanceof Wrapped) throw new IllegalArgumentException(); final Class<?>[] interfaces = new Class<?>[] { ClientConnectionManager.class, Wrapped.class }; return (ClientConnectionManager) Proxy.newProxyInstance( ClientConnectionManagerFactory.class.getClassLoader(), interfaces, new Handler(orig)); } static ClientConnectionManager wrap(ClientConnectionManager orig); } | @Test public void wrapOnce() { ClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop); assertTrue(wrapped instanceof Wrapped); }
@Test(expected = IllegalArgumentException.class) public void wrapTwice() { ClientConnectionManager wrapped = ClientConnectionManagerFactory.wrap(noop); ClientConnectionManagerFactory.wrap(wrapped); } |
JsonResponseHandler implements HttpResponseHandler<AmazonWebServiceResponse<T>> { @Override public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception { log.trace("Parsing service response JSON"); final String crc32Checksum = response.getHeaders().get("x-amz-crc32"); CRC32ChecksumCalculatingInputStream crc32ChecksumInputStream = null; InputStream content = response.getRawContent(); if (content == null) { content = new ByteArrayInputStream("{}".getBytes(StringUtils.UTF8)); } log.debug("CRC32Checksum = " + crc32Checksum); log.debug("content encoding = " + response.getHeaders().get("Content-Encoding")); if (crc32Checksum != null) { crc32ChecksumInputStream = new CRC32ChecksumCalculatingInputStream(content); if ("gzip".equals(response.getHeaders().get("Content-Encoding"))) { content = new GZIPInputStream(crc32ChecksumInputStream); } else { content = crc32ChecksumInputStream; } } final AwsJsonReader jsonReader = JsonUtils.getJsonReader(new InputStreamReader(content, StringUtils.UTF8)); try { final AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>(); final JsonUnmarshallerContext unmarshallerContext = new JsonUnmarshallerContext(jsonReader, response); final T result = responseUnmarshaller.unmarshall(unmarshallerContext); if (crc32Checksum != null) { final long serverSideCRC = Long.parseLong(crc32Checksum); final long clientSideCRC = crc32ChecksumInputStream.getCRC32Checksum(); if (clientSideCRC != serverSideCRC) { throw new CRC32MismatchException( "Client calculated crc32 checksum didn't match that calculated by server side"); } } awsResponse.setResult(result); final Map<String, String> metadata = new HashMap<String, String>(); metadata.put(ResponseMetadata.AWS_REQUEST_ID, response.getHeaders().get("x-amzn-RequestId")); awsResponse.setResponseMetadata(new ResponseMetadata(metadata)); log.trace("Done parsing service response"); return awsResponse; } finally { if (!needsConnectionLeftOpen) { try { jsonReader.close(); } catch (final IOException e) { log.warn("Error closing json parser", e); } } } } JsonResponseHandler(Unmarshaller<T, JsonUnmarshallerContext> responseUnmarshaller); @Override AmazonWebServiceResponse<T> handle(HttpResponse response); @Override boolean needsConnectionLeftOpen(); @SuppressWarnings({"checkstyle:constantname", "checkstyle:visibilitymodifier"})
public boolean needsConnectionLeftOpen; } | @Test public void testHandleWithNoCRC32() throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream( "{\"key\" :\"Content\"}".getBytes(StringUtils.UTF8)); HttpResponse response = new HttpResponse.Builder().statusText("testResponse") .statusCode(200).header("testKey", "testValue").content(bais).build(); Unmarshaller<String, JsonUnmarshallerContext> unmarshaller = new Unmarshaller<String, JsonUnmarshallerContext>() { @Override public String unmarshall(JsonUnmarshallerContext in) throws Exception { in.getReader().beginObject(); in.getReader().nextName(); return in.getReader().nextString(); } }; JsonResponseHandler<String> toTest = new JsonResponseHandler<String>(unmarshaller); AmazonWebServiceResponse<String> awsResponse = toTest.handle(response); assertEquals(awsResponse.getResult(), "Content"); }
@Test public void testHandleWithNullContent() throws Exception { HttpResponse response = new HttpResponse.Builder().statusText("testResponse") .statusCode(200).header("testKey", "testValue").content(null).build(); Unmarshaller<String, JsonUnmarshallerContext> unmarshaller = new Unmarshaller<String, JsonUnmarshallerContext>() { @Override public String unmarshall(JsonUnmarshallerContext in) throws Exception { in.getReader().beginObject(); assertFalse(in.getReader().hasNext()); return "NullContent"; } }; JsonResponseHandler<String> toTest = new JsonResponseHandler<String>(unmarshaller); AmazonWebServiceResponse<String> awsResponse = toTest.handle(response); assertEquals(awsResponse.getResult(), "NullContent"); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.