src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends Gr... | @Test public void isAccountNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonExpired", accountNonExpiredS); assertEquals(entity0.isAccountNonExpired(), accountNonExpiredS); } |
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends Grant... | @Test public void isAccountNonLocked() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonLocked", accountNonLockedS); assertEquals(entity0.isAccountNonLocked(), accountNonLockedS); } |
EUser extends GmsEntity implements UserDetails { @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<... | @Test public void isCredentialsNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "credentialsNonExpired", credentialsNonExpiredS); assertEquals(entity0.isCredentialsNonExpired(), credentialsNonExpiredS); } |
EUser extends GmsEntity implements UserDetails { @Override public boolean isEnabled() { return enabled != null && enabled; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAuthorities... | @Test public void isEnabled() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "enabled", enabledS); assertEquals(entity0.isEnabled(), enabledS); } |
EUser extends GmsEntity implements UserDetails { public boolean isEmailVerified() { return emailVerified != null && emailVerified; } EUser(final String username, final String email, final String name, final String lastName,
final String password); @Override Collection<? extends GrantedAuthority> getAut... | @Test public void isEmailVerified() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "emailVerified", emailVerifiedS); assertEquals(entity0.isEmailVerified(), emailVerifiedS); } |
SecurityConst { public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER; ... | @Test public void getFreeURLsGetRequest() { assertArrayEquals(autowiredSc.getFreeURLsGetRequest(), freeURLsGetRequestBind.split(SEPARATOR)); } |
BRole extends GmsEntity { public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); } | @Test public void addPermission() { cleanEntity0(); entity0.addPermission(sampleP); final Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissions.contains(sampleP)); } |
BRole extends GmsEntity { public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); } | @Test public void removePermission() { Collection<BPermission> auxP = new HashSet<>(); auxP.add(sampleP); cleanEntity0(); ReflectionTestUtils.setField(entity0, "permissions", auxP); Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissio... |
Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPa... | @Test public void mainTest() { Runnable runnable = () -> Application.main(noArgs); Thread thread = new Thread(runnable); thread.start(); } |
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPas... | @Test public void configureTest() { Application app = new Application(); assertNotNull(app.configure(new SpringApplicationBuilder(Application.class))); } |
Application extends SpringBootServletInitializer { @Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; } ... | @Test public void commandLineRunnerBeanCreationIsOK() { Application app = new Application(); assertNotNull(app.commandLineRunner(appService)); } |
Application extends SpringBootServletInitializer { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean... | @Test public void bCryptPasswordEncoderTest() { Application app = new Application(); assertNotNull(app.bCryptPasswordEncoder()); } |
SecurityConst { public String[] getFreeURLsPostRequest() { return freeURLsPostRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER... | @Test public void getFreeURLsPostRequest() { assertArrayEquals(autowiredSc.getFreeURLsPostRequest(), freeURLsPostRequestBind.split(SEPARATOR)); } |
ReplayingRandom extends Random { @Override public int nextInt(int n) { if (n == 5) { return getNextValueOf(fives, indexInFives++); } else if (n == 9) { return getNextValueOf(nines, indexInNines++); } throw new UnsupportedOperationException("not expected invocation of nextInt(" + n + ")"); } ReplayingRandom(String five,... | @Test public void shouldReturnExpectedRandomsFor5And9() { assertThat(rand.nextInt(5), equalTo(2)); assertThat(rand.nextInt(9), equalTo(3)); assertThat(rand.nextInt(5), equalTo(3)); assertThat(rand.nextInt(9), equalTo(3)); assertThat(rand.nextInt(5), equalTo(3)); assertThat(rand.nextInt(9), equalTo(8)); assertThat(rand.... |
HttpServletResponseExcelWrite implements OutputStreamDelegate { public static ExcelWrite build(InputStream inputStream, String fileName, HttpServletRequest request, HttpServletResponse response) { Objects.requireNonNull(inputStream); Objects.requireNonNull(fileName); Objects.requireNonNull(request); Objects.requireNonN... | @Test public void testWriteExcel() { HttpServletResponseExcelWrite.build(fileName, request, response) .deal(ExcelDataList.getTitle(), get(), ExcelDataList.getTenList()) .write(); }
@Test public void testWriteExcelByInputStream() { HttpServletResponseExcelWrite.build(this.getClass().getResourceAsStream("/c.xls"), fileNa... |
SpringProxyUtils { public static <T> T getRealTarget(Object proxy) { Assert.notNull(proxy, "proxy not null"); while (AopUtils.isAopProxy(proxy)) { ProxyFactory proxyFactory = getProxyFactory(proxy); if (proxyFactory == null) { return null; } ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectField... | @Test public void testCglibGetProxy() { ProxyFactory proxyFactory = new ProxyFactory(); Audi audi = new Audi(); TargetSource targetSource = new SingletonTargetSource(audi); proxyFactory.setTargetSource(targetSource); Advisor[] advisors = new Advisor[1]; advisors[0] = advisorAdapterRegistry.wrap(new TestMethodIntercepto... |
SpringProxyUtils { public static boolean isMultipleProxy(Object proxy) { try { ProxyFactory proxyFactory = getProxyFactory(proxy); if (proxyFactory == null) { return false; } ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(proxyFactory); TargetSource targetSource = (TargetSource) ac... | @Test public void testIsMultipleProxy() { Bmw bmw = new Bmw(); ProxyFactory proxyFactory1 = new ProxyFactory(); TargetSource targetSource1 = new SingletonTargetSource(bmw); proxyFactory1.setTargetSource(targetSource1); Advisor[] advisors = new Advisor[1]; advisors[0] = advisorAdapterRegistry.wrap(new TestMethodIntercep... |
SpringProxyUtils { public static ProxyFactory findJdkDynamicProxyFactory(Object proxy) { InvocationHandler h = Proxy.getInvocationHandler(proxy); ConfigurablePropertyAccessor accessor = PropertyAccessorFactory.forDirectFieldAccess(h); return (ProxyFactory) accessor.getPropertyValue("advised"); } static T getRealTarget... | @Test public void testFindJdkDynamicProxyFactory() { ProxyFactory proxyFactory = new ProxyFactory(); Bmw bmw = new Bmw(); TargetSource targetSource = new SingletonTargetSource(bmw); proxyFactory.setTargetSource(targetSource); Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(bmw.getClass()); for (Class<... |
ServiceLocator implements ApplicationContextAware { public static ApplicationContext getFactory() { Assert.notNull(factory, "没有注入spring factory"); return factory; } static ApplicationContext getFactory(); static void setFactory(ApplicationContext context); @SuppressWarnings("unchecked") static T getBean(String beanNam... | @Test public void testGetFactory() { try { ServiceLocator.getBean("test"); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "没有注入spring factory"); } } |
PlaceholderResolver { public String doParse(String strVal) { if (strVal == null) { return null; } return parseStringValue(strVal, visitedPlaceholders); } PlaceholderResolver(PlaceholderResolved resolvedInterceptor); String doParse(String strVal); boolean hasPlaceHolder(String strVal); static boolean substringMatch(Char... | @Test public void testDoParse() { final Map<String, String> placeholderVals = new HashMap<>(5); placeholderVals.put("key1", "china"); placeholderVals.put("key2", "3"); placeholderVals.put("key3", "beijin"); String testStr = "hello ${key1}"; PlaceholderResolver resolver = new PlaceholderResolver(placeholderVals::get); r... |
JndiSupportFilter implements Filter { @Override public final void init(FilterConfig filterConfig) throws ServletException { Assert.notNull(filterConfig, "FilterConfig must not be null"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Initializing filter '" + filterConfig.getFilterName() + "'"); } initPlaceHolderConfigure... | @Test public void testInit() { Company company = new Company(); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(company); bw.setPropertyValue("name", "Some Company Inc."); PropertyValue value = new PropertyValue("name", "Some Company Inc1."); bw.setPropertyValue(value); Employee employee = new Employee()... |
EasyUITreeServiceImpl implements EasyUITreeService<T> { private EasyUITreeModel findModel(List<T> list, Function<T, EasyUITreeModel> mc) { if (null == list) { throw new RuntimeException("没有EasyUI菜单"); } Map<Integer, EasyUITreeModel> p = new HashMap<>(list.size() + 1); EasyUITreeModel root = new EasyUITreeModel(); root.... | @Test public void testFindModel() { List<EasyUITreeModel> json = service.findChildren(getList(), p -> { EasyUITreeModel m = new EasyUITreeModel(); m.setId(p.getParamId()); m.setText(p.getParamName()); m.setPid(p.getParamType()); return m; }); assertNotNull(json); } |
FileExcelWrite implements OutputStreamDelegate { public static ExcelWrite build(InputStream inputStream, String fileName) { Objects.requireNonNull(inputStream); Objects.requireNonNull(fileName); return new CopyInputStreamExcelWrite(inputStream, fileName, new FileExcelWrite()); } private FileExcelWrite(); @Override Out... | @Test public void testWriteSingleLtMaxSheetExcel() { FileExcelWrite.build(fileName) .setLargeDataMode(false) .deal(getTitle(), get(), ExcelDataList.getTenList()) .deal(getTitle(), get(), ExcelDataList.getTenList()) .deal(getTitle(), get(), ExcelDataList.getTenList()) .deal(getTitle(), get(), ExcelDataList.getTenList())... |
ExcelRead { public static <E> void read(InputStream inputStream, ExcelReadDeal<E> deal) { Objects.requireNonNull(inputStream); Objects.requireNonNull(deal); try (Workbook wb = WorkbookFactory.create(inputStream)) { for (int i = 0; i < wb.getNumberOfSheets(); i++) { Sheet sheet = wb.getSheetAt(i); if (null == sheet) { c... | @Test public void testRead() { ExcelRead.read(ExcelReadTest.class.getResourceAsStream("/a.xls"), new ExcelReadDeal<ExcelReadDto>() { @Override public ExcelReadDto dealBean(Row row) { ExcelReadDto dto = new ExcelReadDto(); dto.setId(new BigDecimal(row.getCell(0).toString()).longValue()); dto.setName(row.getCell(1).toStr... |
CSVRead { public static <E> void read(InputStream inputStream, CSVReadDeal<E> deal) { Objects.requireNonNull(inputStream); Objects.requireNonNull(deal); try (CSVReader reader = new CSVReader(new InputStreamReader(new DataInputStream(inputStream)))) { int tmp = deal.getBatchCount(); List<E> l = new ArrayList<>(tmp); int... | @Test public void testRead() { CSVRead.read(CSVReadTest.class.getResourceAsStream("/a.csv"), new CSVReadDeal<CsvReadDto>() { @Override public CsvReadDto dealBean(String[] arr) { CsvReadDto dto = new CsvReadDto(); dto.setId(Long.valueOf(arr[0])); dto.setName(arr[1]); dto.setAge(Integer.valueOf(arr[2])); return dto; } @O... |
FilePdfWrite extends AbstractPdfWrite { public static FilePdfWrite build(String fileName) { Objects.requireNonNull(fileName); return new FilePdfWrite(fileName); } private FilePdfWrite(String fileName); @Override PdfWrite createOutputStream(); static FilePdfWrite build(String fileName); } | @Test public void testWrite() { String path = FilePdfWriteTest.class.getResource("/d.html").getPath(); FilePdfWrite.build(fileName) .addFontPath(fontPath) .deal(() -> { File file = new File(path); String html = null; try { html = FileUtils.readFileToString(file, Charset.forName("GBK")); } catch (IOException e) { e.prin... |
HttpServletResponsePdfWrite extends AbstractPdfWrite { public static HttpServletResponsePdfWrite build(String fileName, HttpServletRequest request, HttpServletResponse response) { Objects.requireNonNull(fileName); Objects.requireNonNull(request); Objects.requireNonNull(response); return new HttpServletResponsePdfWrite(... | @Test public void testWrite() { String path = FilePdfWriteTest.class.getResource("/d.html").getPath(); HttpServletResponsePdfWrite.build(fileName, request, response) .addFontPath(fontPath) .deal(() -> { File file = new File(path); String html = null; try { html = FileUtils.readFileToString(file, Charset.forName("GBK"))... |
SystemException extends BaseSystemException { public String getMessage(Throwable t) { String oldMessage; if (t instanceof InvocationTargetException) { oldMessage = getMessage(((InvocationTargetException) t).getTargetException()); } else if (t instanceof SystemException) { oldMessage = t.getMessage(); } else if (t insta... | @Test public void testGetMessageCustomExceptionAndCustomMessage() { try { try { String s = null; s.toString(); } catch (Exception e) { String[] str = {"a", "b"}; throw new SystemException("first={0}, second={1}", e, str); } } catch (Exception e) { assertEquals(e.getMessage(), "first=a, second=b"); } }
@Test public void... |
PathPatternMatcher { public static boolean match(String pattern, String str) { if (str.startsWith("/") != pattern.startsWith("/")) { return false; } List patDirs = tokenizePath(pattern); List strDirs = tokenizePath(str); int patIdxStart = 0; int patIdxEnd = patDirs.size() - 1; int strIdxStart = 0; int strIdxEnd = strDi... | @Test public void testMatch() { String s = "/time/;jsessionid=6E697A0D5DDDBC4F7206250E5E594305js/frame/menuModel.js"; assertTrue(PathPatternMatcher.match("*.js", s)); } |
BigDecimalUtil { public static double add(double v1, double v2) { return add(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale... | @Test public void testAdd() { assertEquals(BigDecimalUtil.add(123, 234), 357.0); }
@Test public void testAdd1() { BigDecimal v1 = new BigDecimal(123); BigDecimal v2 = new BigDecimal(234); assertEquals(BigDecimalUtil.add(v1, v2), new BigDecimal("357.00")); } |
BigDecimalUtil { public static double sub(double v1, double v2) { return sub(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale... | @Test public void testSub() { assertEquals(BigDecimalUtil.sub(123, 234), -111.0); }
@Test public void testSub1() { BigDecimal v1 = new BigDecimal(123); BigDecimal v2 = new BigDecimal(234); assertEquals(BigDecimalUtil.sub(v1, v2), new BigDecimal("-111.00")); } |
BigDecimalUtil { public static double mul(double v1, double v2) { return mul(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale... | @Test public void testMul() { assertEquals(BigDecimalUtil.mul(10, 23), 230.0); }
@Test public void testMul1() { BigDecimal v1 = new BigDecimal(10); BigDecimal v2 = new BigDecimal(23); assertEquals(BigDecimalUtil.mul(v1, v2), new BigDecimal("230.00")); } |
BigDecimalUtil { public static double div(double v1, double v2) { return div(v1, v2, Constant.DEFAULT_SCALE); } static double add(double v1, double v2); static double add(double v1, double v2, int scale); static BigDecimal add(BigDecimal v1, BigDecimal v2); static BigDecimal add(BigDecimal v1, BigDecimal v2, int scale... | @Test public void testDiv() { assertEquals(BigDecimalUtil.div(23, 10), 2.3); }
@Test public void testDiv1() { BigDecimal v1 = new BigDecimal(23); BigDecimal v2 = new BigDecimal(10); assertEquals(BigDecimalUtil.div(v1, v2), new BigDecimal("2.30")); }
@Test public void testDiv2() { BigDecimal v1 = new BigDecimal(23); Big... |
JsonUtil { public static String toJson(Object obj, String... ignoreProperties) { return gson(ignoreProperties).toJson(obj); } static T fromJson(String json, Class<T> clazz); static String toJson(Object obj, String... ignoreProperties); static Gson gson(String... ignoreProperties); static Gson gson1(String... ignorePro... | @Test public void testToJson() { User user = new User(); user.setName("名称"); user.setDesc("测试"); user.setAge(27); assertEquals("{\"name\":\"名称\",\"age\":27}", JsonUtil.toJson(user, "desc")); } |
MapDistance { public static double getDistance(double lng1, double lat1, double lng2, double lat2) { double radLat1 = rad(lng1); double radLat2 = rad(lng2); double difference = radLat1 - radLat2; double mdifference = rad(lat1) - rad(lat2); double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2) ... | @Test public void testGetDistance() { assertEquals(MapDistance.getDistance(116.327396, 39.938416, 120.332685, 37.617222), 462.0); assertEquals(MapDistance.getDistance(120.332685, 37.617222, 116.327396, 39.938416), 462.0); } |
MapDistance { public static Map<String, Double> getAround(double lng, double lat, double raidusMile) { Map<String, Double> map = new HashMap<>(); double degree = (24901 * 1609) / 360.0; double mpdLng = Double.parseDouble((degree * Math.cos(lng * (Math.PI / 180)) + "").replace("-", "")); double dpmLng = 1 / mpdLng; doub... | @Test public void testGetAround() { Map<String, Double> map = MapDistance.getAround(117.11811, 36.68484, 13000); assertEquals(map.get("maxLat"), Double.valueOf("36.941095784459634")); assertEquals(map.get("minLat"), Double.valueOf("36.42858421554037")); assertEquals(map.get("minLng"), Double.valueOf("117.001301883613")... |
Num62 { public static String longToN62(long l) { return longToNBuf(l, N62_CHARS).reverse().toString(); } static String longToN62(long l); static String longToN36(long l); static String longToN62(long l, int length); static String longToN36(long l, int length); static long n62ToLong(String n62); static long n36ToLong(S... | @Test public void testLongToN62() throws Exception { assertEquals(Num62.longToN62(Long.MAX_VALUE), "AzL8n0Y58m7"); } |
MapUtil { public static <K, V> MapPlain<K, V> build() { return new MapPlain<>(); } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Object> toMap(Object o, String... ignoreProperties)... | @Test public void testMapPlainPut() { Map<String, Object> map = MapUtil.<String, Object>build(1).put("name", "name").get(); assertEquals(map.get("name"), "name"); }
@Test public void testMapPlainPutAll() { Map<String, Object> mapAll = new HashMap<>(); mapAll.put("name", "name"); mapAll.put("age", 25); Map<String, Objec... |
MapUtil { public static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties) { PropertyDescriptor[] ts = ReflectUtil.getPropertyDescriptors(o); List<String> ignoreList = (ignoreProperties != null && ignoreProperties.length > 0) ? Arrays.asList(ignoreProperties) : null; Map<String, Ob... | @Test public void testDefaultToMap() { A a = new A(); a.setName("name"); a.setAge(25); Map<String, Object> params = MapUtil.toMap(a); assertEquals(params.get("name"), "name"); assertEquals(params.get("age"), 25); }
@Test public void testAliasMapToMap() { Map<String, String> alias = new HashMap<>(); alias.put("name", "t... |
MapUtil { public static void toObject(Map<String, Object> source, Object target, String... ignoreProperties) { PropertyDescriptor[] ts = ReflectUtil.getPropertyDescriptors(target); List<String> ignoreList = (ignoreProperties != null && ignoreProperties.length > 0) ? Arrays.asList(ignoreProperties) : null; for (Property... | @Test public void testToObject() { Map<String, Object> params = new HashMap<>(); params.put("name", "name"); params.put("age", 25); A a = new A(); MapUtil.toObject(params, a); assertEquals(a.getName(), "name"); assertEquals(a.getAge(), 25); } |
MapUtil { public static <K, V> List<Map<String, Object>> mapConvertToList(Map<K, V> map) { return mapConvertToList(map, null); } static MapPlain<K, V> build(); static MapPlain<K, V> build(int cap); static Map<String, Object> toMap(Object o, Map<String, String> map, String... ignoreProperties); static Map<String, Objec... | @Test public void testEmptyMapConvertToList() { Map<String, Object> map = new HashMap<>(); List<Map<String, Object>> list = MapUtil.mapConvertToList(map); assertEquals(list.size(), 0); }
@Test public void testMapConvertToList() { Map<String, Object> map = new HashMap<>(); map.put("name", "name"); map.put("age", 25); Li... |
WebUtil { public static String guessContentType(String fileName) { return URLConnection.getFileNameMap().getContentTypeFor(fileName); } static String guessContentType(String fileName); static String encodeContentDisposition(String userAgent, String fileName); } | @Test public void testGuessContentType() throws Exception { assertEquals(WebUtil.guessContentType("1.jpg"), "image/jpeg"); assertNull(WebUtil.guessContentType("2.xlsx")); assertEquals(WebUtil.guessContentType("3.png"), "image/png"); assertNull(WebUtil.guessContentType("4.csv")); assertEquals(WebUtil.guessContentType("5... |
WebUtil { public static String encodeContentDisposition(String userAgent, String fileName) { try { String lowUserAgent = userAgent.toLowerCase(); if (lowUserAgent.contains("msie") || lowUserAgent.contains("trident")) { return "attachment;filename=" + StringUtils.replace(URLEncoder.encode(fileName, StandardCharsets.UTF_... | @Test public void testEncodeContentDisposition() throws Exception { assertEquals(MimeUtility.encodeWord("1.jpg"), "1.jpg"); } |
DateUtil { public static String dateRedMonthBegin(Date date, int n) { String str = ""; int year = year(date); int month = month(date); if (n >= 12) { int m = n % 12; int s = n / 12; month = 12 - m + month; year = year - s; } else { month = month - n; } if (month == 0) { year = year - 1; month = 12; } if (month < 10) { ... | @Test public void testDateRedMonthBegin() { Date date = DateUtil.parse(DateUtil.YYYY_MM, "201603"); String startDate = DateUtil.dateRedMonthBegin(date, 0); assertEquals(startDate, "2016-03-01"); } |
DateUtil { public static String dateRedMonthEnd(Date date, int n) { String str = ""; int year = year(date); int month = month(date); if (n >= 12) { int m = n % 12; int s = n / 12; month = 12 - m + month; year = year - s; } else { month = month - n; } if (month == 0) { year = year - 1; month = 12; } if (month < 10) { st... | @Test public void testDateRedMonthEnd() { Date date = DateUtil.parse(DateUtil.YYYY_MM, "201603"); String endDate = DateUtil.dateRedMonthEnd(date, 0); assertEquals(endDate, "2016-03-31"); } |
DateUtil { public static String format(String format, Date date) { return date != null ? getDateFormat(format).format(date) : null; } static DateFormat getDateFormat(String format); static String format(String format, Date date); static Date parse(String format, String date); static String getDateStr(Date date, String... | @Test public void testFormat() { int count = 2; int j = 2; while (j > 0) { Thread[] threads = new Thread[count]; for (int i = 0; i < count; i++) { Thread thread = new Thread(() -> { String date = DateUtil.format(DateUtil.YYYY_MM_DD_HH_MM_SS, new Date()); assertNotNull(date); date = DateUtil.format(DateUtil.YYYY_MM_DD, ... |
CsvUtil { public static void writeCsvFile(HttpServletResponse response, HttpServletRequest request, String filename, String[] title, List<String[]> bodyList) { response.setContentType("application/octet-stream;charset=GBK"); String fileName = FileUtilies.getFileName(filename, request); response.setHeader("Content-Dispo... | @Test public void testStringArrayWriteCsvFile() { String[] title = {"id" , "name"}; List<String[]> bodyList = new ArrayList<>(); String[] data = new String[2]; data[0] = "1"; data[1] = "张三"; bodyList.add(data); data = new String[2]; data[0] = "2"; data[1] = "李四"; bodyList.add(data); CsvUtil.writeCsvFile(fileName, title... |
SystemPropertyUtil { public static String get(String key) { return get(key, null); } private SystemPropertyUtil(); static boolean contains(String key); static String get(String key); static String get(final String key, String def); static int getInt(String key, int def); } | @Test(expectedExceptions = NullPointerException.class) public void testGetWithKeyNull() { SystemPropertyUtil.get(null, null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testGetWithKeyEmpty() { SystemPropertyUtil.get("", null); }
@Test public void testGetDefaultValueWithPropertyNull() { ass... |
SystemPropertyUtil { public static int getInt(String key, int def) { String value = get(key); if (value == null) { return def; } value = value.trim(); try { return Integer.parseInt(value); } catch (Exception e) { } return def; } private SystemPropertyUtil(); static boolean contains(String key); static String get(Strin... | @Test public void getIntDefaultValueWithPropertyNull() { assertEquals(1, SystemPropertyUtil.getInt("key", 1)); }
@Test public void getIntWithPropertValueIsInt() { System.setProperty("key", "123"); assertEquals(123, SystemPropertyUtil.getInt("key", 1)); }
@Test public void getIntDefaultValueWithPropertValueIsNotInt() { ... |
ISOUtil { public static String unicode2String(String str) { Matcher matcher = UNICODE_2_STRING_PATTERN.matcher(str); while (matcher.find()) { char ch = (char) Integer.parseInt(matcher.group(2), 16); str = str.replace(matcher.group(1), ch + ""); } return str; } ISOUtil(); static String ebcdicToAscii(byte[] e); static St... | @Test public void testUnicode2String() { assertEquals(unicode2String("\u674e"), "李"); } |
DbManager { public Connection getConnection() { try { Class.forName(this.driveName); return DriverManager.getConnection(this.url, this.user, this.password); } catch (ClassNotFoundException e) { throw new RuntimeException("load database class exception : " + e.getMessage(), e); } catch (SQLException e) { throw new Runti... | @Test public void testGetConnection() { Connection connection = dbManager.getConnection(); assertNotNull(connection); dbManager.close(connection); } |
DbManager { public PreparedStatement getPreparedStatement(Connection connection, String sql) { try { return connection.prepareStatement(sql); } catch (SQLException e) { throw new RuntimeException("get PrepareStatement exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String passwo... | @Test public void testGetPreparedStatement() { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); assertNotNull(preparedStatement); dbManager.close(connection, preparedStatement, null); } |
DbManager { public ResultSet getResultSet(PreparedStatement preparedStatement) { try { return preparedStatement.executeQuery(); } catch (SQLException e) { throw new RuntimeException("get ResultSet exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getCo... | @Test public void testGetResultSet() throws Exception { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); ResultSet resultSet = dbManager.getResultSet(preparedStatement); assertNotNull(resultSet);... |
DbManager { public ResultSet getTables(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getTables(localCatalog, localSchema, localTableName, null); } catch (SQLException e) { throw new RuntimeException("get tables exception : " + e.get... | @Test public void testGetTables() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getTables(connection, "", "test_tmp", ""); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 1); dbManager.close(connection, null, resultS... |
DbManager { public ResultSet getColumns(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getColumns(localCatalog, localSchema, localTableName, null); } catch (SQLException e) { throw new RuntimeException("get columns exception : " + e.... | @Test public void testGetColumns() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getColumns(connection, "", "test_tmp", "tb_user"); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 6); dbManager.close(connection, null... |
DbManager { public ResultSet getPrimaryKeys(Connection connection, String localCatalog, String localSchema, String localTableName) { try { return getDatabaseMetaData(connection).getPrimaryKeys(localCatalog, localSchema, localTableName); } catch (SQLException e) { throw new RuntimeException("get primary key exception : ... | @Test public void testGetPrimaryKeys() throws Exception { Connection connection = dbManager.getConnection(); ResultSet resultSet = dbManager.getPrimaryKeys(connection, "", "test_tmp", "tb_user"); assertNotNull(resultSet); int size = 0; while (resultSet.next()) { size++; } assertEquals(size, 1); dbManager.close(connecti... |
DbManager { public ResultSetMetaData getResultSetMetaData(ResultSet resultSet) { try { return resultSet.getMetaData(); } catch (SQLException e) { throw new RuntimeException("get ResultSetMetaData exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getCon... | @Test public void testGetResultSetMetaData() throws Exception { Connection connection = dbManager.getConnection(); PreparedStatement preparedStatement = dbManager.getPreparedStatement(connection, "select count(1) as count from tb_user"); ResultSet resultSet = dbManager.getResultSet(preparedStatement); ResultSetMetaData... |
DbManager { public DatabaseMetaData getDatabaseMetaData(Connection connection) { try { return connection.getMetaData(); } catch (SQLException e) { throw new RuntimeException("get DatabaseMetaData exception : " + e.getMessage(), e); } } DbManager(); DbManager(String url, String user, String password); Connection getCon... | @Test public void testGetDatabaseMetaData() throws Exception { Connection connection = dbManager.getConnection(); DatabaseMetaData databaseMetaData = dbManager.getDatabaseMetaData(connection); assertNotNull(databaseMetaData); assertEquals(databaseMetaData.getDatabaseProductName().toLowerCase(), "mysql"); dbManager.clos... |
Coder { public static int ASCIIToEBCDIC(int ascii) { return ASCII.AToE[ascii & 0xff] & 0xff; } static int ASCIIToEBCDIC(int ascii); static int EBCDICToASCII(int ebcdic); static byte[] ASCIIToEBCDIC(byte[] ascii); static byte[] EBCDICToASCII(byte[] ebcdic); static String ASCIIToEBCDIC(String ascii); static String EBCDI... | @Test public void testASCIIToEBCDIC() { byte[]c = new byte[]{1,2,3,4}; byte[] a = Coder.ASCIIToEBCDIC(c); assertEquals(a[0], 1); assertEquals(a[1], 2); assertEquals(a[2], 3); assertEquals(a[3], 55); } |
ValidateUtils { public static <T> void validate(T bean, Class<?>... groups) { validate(bean, true, groups); } static void validate(T bean, Class<?>... groups); static void validate(T bean, boolean flag, Class<?>... groups); } | @Test public void testValidate() { User user = new User(); user.setRealName("a"); try { ValidateUtils.validate(user); } catch (Exception e) { String str = e.getMessage(); assertEquals(str, "用户id不能为空"); } }
@Test public void testFastValidate() { User user = new User(); try { ValidateUtils.validate(user, false); } catch ... |
PBE { public static byte[] initSalt() { byte[] salt = new byte[8]; Random random = new Random(); random.nextBytes(salt); return salt; } static byte[] encrypt(byte[] data, byte[] key, byte[] salt); static byte[] decrypt(byte[] data, byte[] key, byte[] salt); static Key generateRandomKey(byte[] key); static AlgorithmPar... | @Test public void testInitSalt() { assertNotNull(PBE.initSalt()); } |
AES { public static byte[] encrypt(byte[] data, byte[] key) { validation(data, key); Key secretKeySpec = Symmetry.generateRandomKey(key, AES_ALGORITHM); return Symmetry.encrypt(AES_ALGORITHM, secretKeySpec, data); } static byte[] encrypt(byte[] data, byte[] key); static byte[] decrypt(byte[] data, byte[] key); static ... | @Test public void encrypt() { String data = "root1"; byte[] key = "1111111111111111".getBytes(); byte[] encryption = AES.encrypt(data.getBytes(), key); assertEquals(Base64.getEncoder().encodeToString(encryption), "8/mudtZ/bQOhcV/K6JFrug=="); String decryptData = new String(AES.decrypt(encryption, key)); assertEquals(de... |
HMAC { public static byte[] initMacKey() { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(ISecurity.HMAC_ALGORITHM); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("获取自增密钥错误", e); } } static byte[] encrypt(b... | @Test public void testInitMacKey() { assertNotNull(HMAC.initMacKey()); } |
HMAC { public static byte[] encrypt(byte[] data, byte[] key) { try { SecretKey secretKey = new SecretKeySpec(key, ISecurity.HMAC_ALGORITHM); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); return mac.doFinal(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此算法错误", e);... | @Test public void testEncrypt() { byte[] key = Base64.getDecoder().decode("aDoeS0jpEa7R6YssPU7gZvf95RYH4slqbQgr2gpijhviXyOa16xxOAYmlg0VqBKTE0QPYB26wySLruNJNsbO3A=="); byte[] data = "aaaa".getBytes(); byte[] encryptData = HMAC.encrypt(data, key); String result = Base64.getEncoder().encodeToString(encryptData); assertEqu... |
SHA { public static String digest(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance(ISecurity.SHA_ALGORITHM); BigInteger bigInteger = new BigInteger(md.digest(bytes)); return bigInteger.toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此[" + ISecurity.SHA_ALGORITHM + "]算... | @Test public void testDigest() { byte[] data = "aaa".getBytes(); String result = SHA.digest(data); assertEquals(result, "7e240de74fb1ed08fa08d38063f6a6a91462a815"); } |
MD5 { public static String digest(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance(ISecurity.MD5_ALGORITHM); BigInteger bigInteger = new BigInteger(md.digest(bytes)); return bigInteger.toString(16); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("无此[" + ISecurity.MD5_ALGORITHM + "]算... | @Test public void testDigest() { byte[] data = "aaa".getBytes(); String result = MD5.digest(data); assertEquals(result, "47bce5c74f589f4867dbd57e9ca9f808"); } |
WeatherSecurity { public static String standardURLEncoder(String data, String key) { try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(spec); byte[] byteHMAC = mac.doFinal(data.getBytes()); if (byteHMAC != null) { String oauth = encode(byteHMAC); r... | @Test public void testExecuteGet() { try { String type = "forecast_f"; String appid = "0efe9e3c08151b8d"; String date = "201503030741"; String areaid = "101010100"; String key = "a0f6ac_SmartWeatherAPI_cd7e788"; String data = "http: String str = WeatherSecurity.standardURLEncoder(data + appid, key); assertEquals(str, "... |
RSAC { public static byte[] encryptByPublicKey(byte[] data, String ns, String es) { return encryptByPublicKey(data, ns, es, ISecurity.RSA_ECB_ALGORITHM); } static byte[] encryptByPublicKey(byte[] data, String ns, String es); static byte[] encryptByPublicKey(byte[] data, String ns, String es, String cipherS); static by... | @Test public void testEncryptByPublicKey() { String data = "abc"; byte[] result = RSAC.encryptByPublicKey(data.getBytes(), ns, es); assertEquals(ISOUtil.hexString(result), "AD04F695A18D6C400F301C3704EA472F6AB875967B66A6F196558E163173F783C1BD8CADD277E518603C2BD819DCB3B8364C9B2E2A89B769A32A678EAD345A1F"); } |
RSAC { public static byte[] decryptByPrivateKey(byte[] data, String ns, String ds) { return decryptByPrivateKey(data, ns, ds, ISecurity.RSA_ECB_ALGORITHM); } static byte[] encryptByPublicKey(byte[] data, String ns, String es); static byte[] encryptByPublicKey(byte[] data, String ns, String es, String cipherS); static ... | @Test public void testDecryptByPrivateKey() { String data = "AD04F695A18D6C400F301C3704EA472F6AB875967B66A6F196558E163173F783C1BD8CADD277E518603C2BD819DCB3B8364C9B2E2A89B769A32A678EAD345A1F"; byte[] result = RSAC.decryptByPrivateKey(ISOUtil.hex2byte(data), ns, ds); assertEquals(new String(result).trim(), "abc"); } |
PercentageTypeConverter extends NumberTypeConverterSupport implements TypeConverter<Number> { public Number convert( String input, Class<? extends Number> targetType, Collection<ValidationError> errors ) { Number number = parse( input, errors ); if ( errors.size() == 0 ) { if ( targetType.equals( Float.class ) || targe... | @Test(groups = "fast") public void parseBasic() throws Exception { Number result = getConverter().convert("80%", Float.class, errors()); Assert.assertEquals(result, new Float(0.8f)); }
@Test(groups = "fast") public void parseSpaceBeforePercentSignDouble() throws Exception { Number result = getConverter().convert("0.8 %... |
CreditCardTypeConverter implements TypeConverter<String> { public String convert(String input, Class<? extends String> targetType, Collection<ValidationError> errors) { String cardNumber = input.replaceAll("\\D", ""); if (getCardType(cardNumber) != null) { return cardNumber; } errors.add(new ScopedLocalizableError("con... | @Test(groups = "fast") public void validNumber() { CreditCardTypeConverter c = new CreditCardTypeConverter(); Assert.assertEquals(c.convert("4111111111111111", String.class, new ArrayList<ValidationError>()), "4111111111111111"); }
@Test(groups = "fast") public void invalidNumber() { CreditCardTypeConverter c = new Cre... |
BigDecimalTypeConverter extends NumberTypeConverterSupport implements TypeConverter<BigDecimal> { public BigDecimal convert(String input, Class<? extends BigDecimal> targetType, Collection<ValidationError> errors) { return (BigDecimal) parse(input, errors); } BigDecimal convert(String input,
Class<? extend... | @Test(groups = "fast") public void basicParse() throws Exception { TypeConverter<BigDecimal> converter = new BigDecimalTypeConverter(); converter.setLocale(Locale.US); BigDecimal result = converter.convert("12345.67", BigDecimal.class, errors()); Assert.assertEquals(result, new BigDecimal("12345.67")); }
@Test(groups =... |
BigIntegerTypeConverter extends NumberTypeConverterSupport implements TypeConverter<BigInteger> { public BigInteger convert(String input, Class<? extends BigInteger> targetType, Collection<ValidationError> errors) { BigDecimal decimal = (BigDecimal) parse(input, errors); if (errors.size() == 0) { return decimal.toBigIn... | @Test(groups = "fast") public void basicParse() throws Exception { TypeConverter<BigInteger> converter = new BigIntegerTypeConverter(); converter.setLocale(Locale.US); BigInteger result = converter.convert("1234567", BigInteger.class, errors()); Assert.assertEquals(result, new BigInteger("1234567")); }
@Test(groups = "... |
DateTypeConverter implements TypeConverter<Date> { public Date convert(String input, Class<? extends Date> targetType, Collection<ValidationError> errors) { String parseable = preProcessInput(input); Date date = null; for (DateFormat format : this.formats) { try { date = format.parse(parseable); break; } catch (ParseEx... | @Test(groups = "fast") public void testBasicUsLocaleDates() { Collection<ValidationError> errors = new ArrayList<ValidationError>(); DateTypeConverter converter = getConverter(Locale.US); Date date = converter.convert("1/31/07", Date.class, errors); Assert.assertNotNull(date); Assert.assertEquals(0, errors.size()); Ass... |
NumberTypeConverterSupport { protected Number parse(String input, Collection<ValidationError> errors) { input = preprocess(input); ParsePosition pp = new ParsePosition(0); for (NumberFormat format : this.formats) { pp.setIndex(0); Number number = format.parse(input, pp); if (number != null && input.length() == pp.getIn... | @Test(groups = "fast") public void basicPositiveTests() { Number number = getConverter().parse("10912", new ArrayList<ValidationError>()); Assert.assertEquals(number.intValue(), 10912); number = getConverter().parse("-1,000,000", new ArrayList<ValidationError>()); Assert.assertEquals(number.intValue(), -1000000); }
@Te... |
UrlBuilder { @Override public String toString() { if (url == null) { url = build(); } if (this.anchor != null && this.anchor.length() > 0) { return url + "#" + StringUtil.uriFragmentEncode(this.anchor); } else { return url; } } UrlBuilder(Locale locale, String url, boolean isForPage); UrlBuilder(Locale locale, Class<?... | @Test(groups = "fast") public void testBasicUrl() throws Exception { String path = "/test/page.jsp"; UrlBuilder builder = new UrlBuilder(Locale.getDefault(), path, false); String result = builder.toString(); Assert.assertEquals(result, path); } |
HtmlUtil { public static String combineValues(Collection<String> values) { if (values == null || values.size() == 0) { return ""; } else { StringBuilder builder = new StringBuilder(values.size() * 30); for (String value : values) { builder.append(value).append(FIELD_DELIMITER_STRING); } return encode(builder.toString()... | @Test(groups = "fast") public void testJoinWithNoStrings() throws Exception { String combined = HtmlUtil.combineValues(null); Assert.assertEquals(combined, ""); combined = HtmlUtil.combineValues(new HashSet<String>()); Assert.assertEquals(combined, ""); } |
HtmlUtil { public static Collection<String> splitValues(String value) { if (value == null || value.length() == 0) { return Collections.emptyList(); } else { String[] splits = FIELD_DELIMITER_PATTERN.split(value); return Arrays.asList(splits); } } static String encode(String fragment); static String combineValues(Colle... | @Test(groups = "fast") public void testSplitWithNoValues() throws Exception { Collection<String> values = HtmlUtil.splitValues(null); Assert.assertNotNull(values); Assert.assertEquals(values.size(), 0); values = HtmlUtil.splitValues(""); Assert.assertNotNull(values); Assert.assertEquals(values.size(), 0); } |
CollectionUtil { public static boolean empty(String[] arr) { if (arr == null || arr.length == 0) { return true; } for (String s : arr) { if (s != null && !"".equals(s)) { return false; } } return true; } static boolean contains(Object[] arr, Object item); static boolean empty(String[] arr); static boolean applies(Stri... | @Test(groups = "fast") public void testEmptyOnNullCollection() { Assert.assertTrue(CollectionUtil.empty(null)); }
@Test(groups = "fast") public void testEmptyOnCollectionOfNulls() { Assert.assertTrue(CollectionUtil.empty(new String[]{null, null, null})); }
@Test(groups = "fast") public void testEmptyZeroLengthCollectio... |
CollectionUtil { public static boolean applies(String events[], String event) { if (events == null || events.length == 0) { return true; } boolean isPositive = events[0].charAt(0) != '!'; if (isPositive) { return contains(events, event); } else { return !contains(events, "!" + event); } } static boolean contains(Objec... | @Test(groups = "fast") public void testApplies() { Assert.assertTrue(CollectionUtil.applies(null, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{}, "foo")); Assert.assertTrue(CollectionUtil.applies(new String[]{"bar", "foo"}, "foo")); Assert.assertFalse(CollectionUtil.applies(new String[]{"bar", "f00"},... |
CollectionUtil { public static List<Object> asList(Object in) { if (in == null || !in.getClass().isArray()) { throw new IllegalArgumentException("Parameter to asObjectArray must be a non-null array."); } else { int length = Array.getLength(in); LinkedList<Object> list = new LinkedList<Object>(); for (int i = 0; i < len... | @Test(groups = "fast") public void testAsList() { List<Object> list = CollectionUtil.asList(new String[]{"foo", "bar"}); Assert.assertEquals(list.get(0), "foo"); Assert.assertEquals(list.get(1), "bar"); list = CollectionUtil.asList(new String[]{}); Assert.assertEquals(list.size(), 0); list = CollectionUtil.asList(new i... |
CryptoUtil { public static String decrypt(String input) { if (input == null) { return null; } Configuration configuration = StripesFilter.getConfiguration(); if (configuration != null && configuration.isDebugMode()) { return input; } byte[] bytes = Base64.decode(input, BASE64_OPTIONS); if (bytes == null || bytes.length... | @Test(groups = "fast") public void decryptNullTest() throws Exception { String input = null; String decrypted = CryptoUtil.decrypt(input); Assert.assertNull(decrypted, "Decrypting null should give back null."); }
@Test(groups = "fast") public void decryptBogusInputTest() throws Exception { String input = "_sipApTvfAXjn... |
CryptoUtil { public static String encrypt(String input) { if (input == null) { input = ""; } Configuration configuration = StripesFilter.getConfiguration(); if (configuration != null && configuration.isDebugMode()) { return input; } try { byte[] inbytes = input.getBytes(); final int inputLength = inbytes.length; byte[]... | @Test(groups = "fast") public void failOnECB() throws Exception { String input1 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; String encrypted1 = CryptoUtil.encrypt(input1); String encrypted2 = CryptoUtil.encrypt(input1); for (int i = 0; i < encryp... |
ReflectUtil { public static Method findAccessibleMethod(final Method m) { if (isPublic(m.getModifiers()) && isPublic(m.getDeclaringClass().getModifiers())) { return m; } if (m.isAccessible()) { return m; } final Class<?> clazz = m.getDeclaringClass(); final String name = m.getName(); final Class<?>[] ptypes = m.getPara... | @Test(groups = "fast") public void testAccessibleMethodBaseCase() throws Exception { Method m = Object.class.getMethod("getClass"); Method m2 = ReflectUtil.findAccessibleMethod(m); Assert.assertSame(m, m2); } |
ReflectUtil { public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz, String property) { if (!propertyDescriptors.containsKey(clazz)) { getPropertyDescriptors(clazz); } return propertyDescriptors.get(clazz).get(property); } private ReflectUtil(); static boolean isDefault(Method method); @SuppressWarning... | @Test(groups = "fast") public void testCovariantProperty() { abstract class Base { abstract Object getId(); } class ROSub extends Base { protected String id; @Override public String getId() { return id; } } class RWSub extends ROSub { @SuppressWarnings("unused") public void setId(String id) { this.id = id; } } Property... |
ReflectUtil { public static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType) { return getActualTypeArguments(clazz, targetType, null); } private ReflectUtil(); static boolean isDefault(Method method); @SuppressWarnings("rawtypes") // this allows us to assign without casting static Class findClass(Str... | @Test(groups = "fast") public void testResolveTypeArgsOfSuperInterface() { class Impl implements C { } Type[] typeArgs = ReflectUtil.getActualTypeArguments(Impl.class, A.class); Assert.assertEquals(typeArgs.length, 3); Assert.assertEquals(typeArgs[0], Long.class); Assert.assertEquals(typeArgs[1], String.class); Assert.... |
AnnotatedClassActionResolver implements ActionResolver { public Class<? extends ActionBean> getActionBeanByName(String actionBeanName) { return actionBeansByName.get(actionBeanName); } @Override void init(Configuration configuration); UrlBindingFactory getUrlBindingFactory(); String getUrlBindingFromPath(String path);... | @Test(groups = "fast") public void findByName() { Class<? extends ActionBean> actionBean = resolver.getActionBeanByName("SimpleActionBean"); Assert.assertNotNull(actionBean); }
@Test(groups = "fast") public void multipleActionBeansWithSameSimpleName() { Class<? extends ActionBean> actionBean = resolver.getActionBeanByN... |
NameBasedActionResolver extends AnnotatedClassActionResolver { @Override public String getUrlBinding(Class<? extends ActionBean> clazz) { String binding = super.getUrlBinding(clazz); if (binding == null && !Modifier.isAbstract(clazz.getModifiers())) { binding = getUrlBinding(clazz.getName()); } return binding; } @Over... | @Test(groups = "fast") public void generateBinding() { String binding = this.resolver.getUrlBinding("foo.bar.web.admin.ControlCenterActionBean"); Assert.assertEquals(binding, "/admin/ControlCenter.action"); }
@Test(groups = "fast") public void generateBindingForNonPackagedClass() { String binding = this.resolver.getUrl... |
NameBasedActionResolver extends AnnotatedClassActionResolver { protected List<String> getFindViewAttempts(String urlBinding) { List<String> attempts = new ArrayList<String>(3); int lastPeriod = urlBinding.lastIndexOf('.'); String path = urlBinding.substring(0, urlBinding.lastIndexOf("/") + 1); String name = (lastPeriod... | @Test(groups = "fast") public void testGetFindViewAttempts() { String urlBinding = "/account/ViewAccount.action"; List<String> viewAttempts = this.resolver.getFindViewAttempts(urlBinding); Assert.assertEquals(viewAttempts.size(), 3); Assert.assertEquals(viewAttempts.get(0), "/account/ViewAccount.jsp"); Assert.assertEqu... |
LocalizationUtility { public static String makePseudoFriendlyName(String fieldNameKey) { StringBuilder builder = new StringBuilder(fieldNameKey.length() + 10); char[] characters = fieldNameKey.toCharArray(); builder.append(Character.toUpperCase(characters[0])); boolean upcaseNextChar = false; for (int i = 1; i < charac... | @Test(groups = "fast") public void testBaseCase() throws Exception { String input = "Hello"; String output = LocalizationUtility.makePseudoFriendlyName(input); Assert.assertEquals(output, input); }
@Test(groups = "fast") public void testSimpleCase() throws Exception { String input = "hello"; String output = Localizatio... |
LocalizationUtility { public static String getSimpleName(Class<?> c) { if (c.getEnclosingClass() == null) { return c.getSimpleName(); } else { return prefixSimpleName(new StringBuilder(), c).toString(); } } static String getLocalizedFieldName(String fieldName,
String actionPath,
Class<? extends... | @Test(groups = "fast") public void testSimpleClassName() throws Exception { String output = LocalizationUtility.getSimpleName(TestEnum.class); Assert.assertEquals(output, "LocalizationUtilityTest.TestEnum"); output = LocalizationUtility.getSimpleName(A.B.C.class); Assert.assertEquals(output, "LocalizationUtilityTest.A.... |
MockRoundtrip { public void addParameter(String name, String... value) { if (this.request.getParameterValues(name) == null) { setParameter(name, value); } else { String[] oldValues = this.request.getParameterMap().get(name); String[] combined = new String[oldValues.length + value.length]; System.arraycopy(oldValues, 0,... | @Test(groups = "fast") public void testAddParameter() throws Exception { MockRoundtrip trip = new MockRoundtrip(getMockServletContext(), TestMockRoundtrip.class); trip.addParameter("param", "a"); trip.addParameter("param", "b"); trip.execute(); TestMockRoundtrip bean = trip.getActionBean(TestMockRoundtrip.class); Strin... |
RedirectResolution extends OnwardResolution<RedirectResolution> { @SuppressWarnings("unchecked") @Override public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (permanent) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response = new Ht... | @Test(groups = "fast") public void testTemporaryRedirect() throws Exception { RedirectResolution resolution = new RedirectResolution("http: MockHttpServletResponse response = new MockHttpServletResponse(); resolution.execute(buildMockServletRequest(), response); Assert.assertEquals(response.getStatus(), HttpServletResp... |
TurkishSpellChecker { public boolean check(String input) { WordAnalysis analyses = morphology.analyze(input); WordAnalysisSurfaceFormatter.CaseType caseType = formatter.guessCase(input); for (SingleAnalysis analysis : analyses) { if (analysis.isUnknown()) { continue; } if (analysisPredicate != null && !analysisPredicat... | @Test public void checkProperNounsTest() throws IOException { TurkishMorphology morphology = TurkishMorphology.builder() .disableCache() .setLexicon("Ankara", "Iphone [Pr:ayfon]", "Google [Pr:gugıl]") .build(); TurkishSpellChecker spellChecker = new TurkishSpellChecker(morphology); String[] correct = {"Ankara", "ANKARA... |
SimpleTextReader implements AutoCloseable { public LineIterator getLineIterator() throws IOException { return new LineIterator(getReader(), trim, filters); } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); SimpleTextReader(String fileNam... | @Test public void lineIteratorTest2() throws IOException { try (LineIterator li = new SimpleTextReader(multi_line_text_file.getFile()).getLineIterator()) { while (li.hasNext()) { out.println(li.next().toUpperCase()); } } }
@Test public void lineIteratorWithConstraint() throws IOException { try (LineIterator li = new Si... |
LogMath { public static double logSum(double logA, double logB) { if (Double.isInfinite(logA)) { return logB; } if (Double.isInfinite(logB)) { return logA; } if (logA > logB) { double dif = logA - logB; return dif >= 30d ? logA : logA + Math.log(1 + Math.exp(-dif)); } else { double dif = logB - logA; return dif >= 30d ... | @Test public void logSumTest() throws IOException { double[] aLinear = new double[1000]; double[] bLinear = new double[1000]; for (int i = 0; i < bLinear.length; i++) { aLinear[i] = (double) i / 1000d; bLinear[i] = aLinear[i]; } LogMath.LogSumLookup logSumE = LogMath.LOG_SUM; for (double a : aLinear) { for (double b : ... |
LogMath { public static double log(double base, double val) { return Math.log(val) / Math.log(base); } private LogMath(); static double logSum(double logA, double logB); static double logSum10(double log10A, double log10B); static double logSum(double... logValues); static double log(double base, double val); static d... | @Test public void logSumFloatTest() throws IOException { float[] aLinear = new float[1000]; float[] bLinear = new float[1000]; for (int i = 0; i < bLinear.length; i++) { aLinear[i] = (float) i / 1000f; bLinear[i] = aLinear[i]; } for (float a : aLinear) { for (float b : bLinear) { float logSumExpected = (float) Math.log... |
LogMath { public static double log2(double input) { return Math.log(input) * INVERSE_LOG_TWO; } private LogMath(); static double logSum(double logA, double logB); static double logSum10(double log10A, double log10B); static double logSum(double... logValues); static double log(double base, double val); static double l... | @Test public void testLog2() { Assert.assertEquals(2, LogMath.log2(4), 0.0001); Assert.assertEquals(3, LogMath.log2(8), 0.0001); Assert.assertEquals(10, LogMath.log2(1024), 0.0001); Assert.assertEquals(-1, LogMath.log2(0.5), 0.0001); } |
FloatArrays { public static float sum(float... input) { float sum = 0; for (float v : input) { sum += v; } return sum; } private FloatArrays(); static boolean inRange(float d1, float d2, float range); static float[] reverse(float[] input); static float[] convert(int[] input); static float[][] convert(int[][] input); s... | @Test public void testSum() { float[] da = {1, 2, 0, -1, -3}; float[] da2 = {0.5f, -2, 30, 1, -30}; Assert.assertTrue(inDelta(FloatArrays.sum(da), -1)); Assert.assertTrue(inDelta(FloatArrays.sum(da, da2), new float[]{1.5f, 0, 30, 0, -33})); FloatArrays.addToFirst(da, da2); Assert.assertTrue(inDelta(da, new float[]{1.5f... |
FloatArrays { public static void addToFirstScaled(float[] first, float[] second, float scale) { validateArrays(first, second); for (int i = 0; i < first.length; i++) { first[i] = first[i] + second[i] * scale; } } private FloatArrays(); static boolean inRange(float d1, float d2, float range); static float[] reverse(flo... | @Test public void addToFirstScaledTest() { float[] da1 = {1, 2, 0, -1, -30}; float[] da2 = {-0.5f, -1, 0, 0.5f, 15}; FloatArrays.addToFirstScaled(da1, da2, 2); Assert.assertEquals(FloatArrays.max(da1), 0f, 0.0001); Assert.assertEquals(FloatArrays.min(da1), 0f, 0.0001); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.