method2testcases stringlengths 118 3.08k |
|---|
### Question:
ArkServiceContainer { public void stop() throws ArkRuntimeException { if (stopped.compareAndSet(false, true)) { LOGGER.info("Begin to stop ArkServiceContainer"); ClassLoader oldClassLoader = ClassLoaderUtils.pushContextClassLoader(getClass() .getClassLoader()); try { Collections.reverse(arkServiceList); for (ArkService arkService : arkServiceList) { LOGGER.info(String.format("Dispose service: %s", arkService.getClass() .getName())); arkService.dispose(); } LOGGER.info("Finish to stop ArkServiceContainer"); } finally { ClassLoaderUtils.popContextClassLoader(oldClassLoader); } } } ArkServiceContainer(String[] arguments); void start(); T getService(Class<T> clazz); void stop(); boolean isStarted(); boolean isRunning(); }### Answer:
@Test public void testStop() { arkServiceContainer.start(); arkServiceContainer.stop(); Assert.assertFalse(arkServiceContainer.isRunning()); } |
### Question:
ArkServiceContainer { public <T> T getService(Class<T> clazz) { return injector.getInstance(clazz); } ArkServiceContainer(String[] arguments); void start(); T getService(Class<T> clazz); void stop(); boolean isStarted(); boolean isRunning(); }### Answer:
@Test public void testGetService() { arkServiceContainer.start(); Pipeline pipeline = arkServiceContainer.getService(Pipeline.class); Assert.assertNotNull(pipeline); Assert.assertTrue(pipeline instanceof StandardPipeline); } |
### Question:
StringUtils { public static String setToStr(Set<String> stringSet, String delimiter) { return setToStr(stringSet, delimiter, EMPTY_STRING); } static boolean isEmpty(String str); static boolean isSameStr(String a, String b); static String setToStr(Set<String> stringSet, String delimiter); static String setToStr(Set<String> stringSet, String delimiter, String defaultRet); static Set<String> strToSet(String str, String delimiter); static List<String> strToList(String str, String delimiter); static boolean startWithToLowerCase(String thisString, String anotherString); static final String EMPTY_STRING; static final int CHAR_A; static final int CHAR_Z; static final int CASE_GAP; }### Answer:
@Test @SuppressWarnings("unchecked") public void testListToStr() { Assert.assertTrue("".equals(StringUtils.setToStr(null, ","))); Assert.assertTrue("".equals(StringUtils.setToStr(Collections.<String> emptySet(), ","))); Assert.assertTrue("ast".equals(StringUtils.setToStr(Collections.singleton("ast"), "&&"))); LinkedHashSet linkedHashSet = new LinkedHashSet(); linkedHashSet.add("ab"); linkedHashSet.add(" ba "); Assert.assertTrue("ab,ba".equals(StringUtils.setToStr(linkedHashSet, ","))); linkedHashSet.add("cb"); Assert.assertTrue("ab&&ba&&cb".equals(StringUtils.setToStr(linkedHashSet, "&&"))); Assert.assertTrue("abbacb".equals(StringUtils.setToStr(linkedHashSet, ""))); } |
### Question:
StringUtils { public static List<String> strToList(String str, String delimiter) { if (str == null || str.isEmpty()) { return Collections.emptyList(); } List<String> stringList = new ArrayList<>(); for (String s : str.split(delimiter)) { stringList.add(s.trim()); } return stringList; } static boolean isEmpty(String str); static boolean isSameStr(String a, String b); static String setToStr(Set<String> stringSet, String delimiter); static String setToStr(Set<String> stringSet, String delimiter, String defaultRet); static Set<String> strToSet(String str, String delimiter); static List<String> strToList(String str, String delimiter); static boolean startWithToLowerCase(String thisString, String anotherString); static final String EMPTY_STRING; static final int CHAR_A; static final int CHAR_Z; static final int CASE_GAP; }### Answer:
@Test public void testStrToList() { List<String> list = StringUtils.strToList("ab,ba,cb", ","); Assert.assertTrue(list.size() == 3); Assert.assertTrue(list.get(0).equals("ab")); Assert.assertTrue(list.get(1).equals("ba")); Assert.assertTrue(list.get(2).equals("cb")); } |
### Question:
StringUtils { public static Set<String> strToSet(String str, String delimiter) { return new LinkedHashSet<>(strToList(str, delimiter)); } static boolean isEmpty(String str); static boolean isSameStr(String a, String b); static String setToStr(Set<String> stringSet, String delimiter); static String setToStr(Set<String> stringSet, String delimiter, String defaultRet); static Set<String> strToSet(String str, String delimiter); static List<String> strToList(String str, String delimiter); static boolean startWithToLowerCase(String thisString, String anotherString); static final String EMPTY_STRING; static final int CHAR_A; static final int CHAR_Z; static final int CASE_GAP; }### Answer:
@Test public void testStrToSet() { Set<String> set = StringUtils.strToSet(null, "&&"); Assert.assertTrue(set.isEmpty()); set = StringUtils.strToSet("ab&&ba&&cb&&cb", "&&"); Assert.assertTrue(set.size() == 3); Object[] array = set.toArray(); Assert.assertTrue(array[0].equals("ab")); Assert.assertTrue(array[1].equals("ba")); Assert.assertTrue(array[2].equals("cb")); } |
### Question:
StringUtils { public static boolean startWithToLowerCase(String thisString, String anotherString) { AssertUtils.assertNotNull(thisString, "Param must not be null!"); AssertUtils.assertNotNull(anotherString, "Param must not be null!"); if (thisString.length() < anotherString.length()) { return false; } boolean ret; int index = 0; do { if (thisString.charAt(index) > CHAR_Z || thisString.charAt(index) < CHAR_A) { ret = thisString.charAt(index) == anotherString.charAt(index); } else { ret = thisString.charAt(index) + CASE_GAP == anotherString.charAt(index); } } while (ret && ++index < anotherString.length()); return ret; } static boolean isEmpty(String str); static boolean isSameStr(String a, String b); static String setToStr(Set<String> stringSet, String delimiter); static String setToStr(Set<String> stringSet, String delimiter, String defaultRet); static Set<String> strToSet(String str, String delimiter); static List<String> strToList(String str, String delimiter); static boolean startWithToLowerCase(String thisString, String anotherString); static final String EMPTY_STRING; static final int CHAR_A; static final int CHAR_Z; static final int CASE_GAP; }### Answer:
@Test public void testStartWithToLowerCase() { Assert.assertFalse(StringUtils.startWithToLowerCase("ab", "abc")); Assert.assertTrue(StringUtils.startWithToLowerCase("AbC", "abc")); Assert.assertTrue(StringUtils.startWithToLowerCase("aB#", "ab#")); Assert.assertTrue(StringUtils.startWithToLowerCase("~Ab", "~ab")); } |
### Question:
ClassUtils { public static String getPackageName(String className) { AssertUtils.isFalse(StringUtils.isEmpty(className), "ClassName should not be empty!"); int index = className.lastIndexOf('.'); if (index > 0) { return className.substring(0, index); } return Constants.DEFAULT_PACKAGE; } static String getPackageName(String className); static String getCodeBase(Class<?> cls); }### Answer:
@Test public void testGetPackageName() { Assert.assertTrue(ClassUtils.getPackageName("a.b.C").equals("a.b")); Assert.assertTrue(ClassUtils.getPackageName("C").equals(Constants.DEFAULT_PACKAGE)); } |
### Question:
LoggerSpaceManager { public static Logger getLoggerBySpace(String name, String spaceName) { ClassLoader callerClassLoader = ClassLoaderUtil.getCallerClassLoader(); return getLoggerBySpace(name, spaceName, callerClassLoader); } static Logger getLoggerBySpace(String name, String spaceName); static Logger getLoggerBySpace(String name, SpaceId spaceId,
Map<String, String> properties); static Logger getLoggerBySpace(String name, String spaceName,
ClassLoader spaceClassloader); static Logger getLoggerBySpace(String name, SpaceId spaceId,
Map<String, String> properties,
ClassLoader spaceClassloader); static Logger setLoggerLevel(String loggerName, String spaceName,
AdapterLevel adapterLevel); static Logger setLoggerLevel(String loggerName, SpaceId spaceId,
AdapterLevel adapterLevel); static ILoggerFactory removeILoggerFactoryBySpaceName(String spaceName); static ILoggerFactory removeILoggerFactoryBySpaceId(SpaceId spaceId); }### Answer:
@Test public void TestDisableLoggerSpaceFactory() { System.setProperty(SOFA_MIDDLEWARE_LOG_DISABLE_PROP_KEY, "true"); Logger logger = LoggerSpaceManager.getLoggerBySpace("com.foo.Bar", "com.alipay.sofa.rpc"); Logger logger2 = LoggerSpaceManager.getLoggerBySpace("com.foo.Bar", "com.alipay.sofa.rpc"); Assert.assertSame(logger, logger2); Assert.assertSame(logger, Constants.DEFAULT_LOG); System.setProperty(SOFA_MIDDLEWARE_LOG_DISABLE_PROP_KEY, "false"); } |
### Question:
AssertUtil { public static void isTrue(boolean expression, String message) { if (!expression) { throw new IllegalArgumentException(message); } } static void isTrue(boolean expression, String message); static void isTrue(boolean expression); static void isNull(Object object, String message); static void isNull(Object object); static void notNull(Object object, String message); static void notNull(Object object); static void notEmpty(Object[] array, String message); static void notEmpty(Object[] array); static void noNullElements(Object[] array, String message); static void noNullElements(Object[] array); static void notEmpty(Collection collection, String message); static void notEmpty(Collection collection); static void notEmpty(Map map, String message); static void notEmpty(Map map); static void isInstanceOf(Class clazz, Object obj); static void isInstanceOf(Class type, Object obj, String message); static void isAssignable(Class superType, Class subType); static void isAssignable(Class superType, Class subType, String message); static void state(boolean expression, String message); static void state(boolean expression); static void hasText(String text, String message); static void hasText(String text); }### Answer:
@Test public void testIsTrueForExpressionMessage() throws Exception { boolean isSuccess = false; AssertUtil.isTrue(!isSuccess, "isTrue"); boolean isException = false; try { AssertUtil.isTrue(isSuccess, "isTrue"); } catch (Exception ex) { isException = true; } AssertUtil.isTrue(isException); } |
### Question:
AssertUtil { public static void isNull(Object object, String message) { if (object != null) { throw new IllegalArgumentException(message); } } static void isTrue(boolean expression, String message); static void isTrue(boolean expression); static void isNull(Object object, String message); static void isNull(Object object); static void notNull(Object object, String message); static void notNull(Object object); static void notEmpty(Object[] array, String message); static void notEmpty(Object[] array); static void noNullElements(Object[] array, String message); static void noNullElements(Object[] array); static void notEmpty(Collection collection, String message); static void notEmpty(Collection collection); static void notEmpty(Map map, String message); static void notEmpty(Map map); static void isInstanceOf(Class clazz, Object obj); static void isInstanceOf(Class type, Object obj, String message); static void isAssignable(Class superType, Class subType); static void isAssignable(Class superType, Class subType, String message); static void state(boolean expression, String message); static void state(boolean expression); static void hasText(String text, String message); static void hasText(String text); }### Answer:
@Test public void testIsNullForObjectMessage() throws Exception { Object object = null; AssertUtil.isNull(object, "null"); AssertUtil.isNull(object); } |
### Question:
TimeWaitRunner { public void doWithRunnable(Runnable runnable) { long currentTimeMillis = System.currentTimeMillis(); if (runImmediately) { runnable.run(); } else if (currentTimeMillis > lastLogTime + waitTime) { synchronized (this) { if (currentTimeMillis > lastLogTime + waitTime) { lastLogTime = currentTimeMillis; runnable.run(); } } } } TimeWaitRunner(long waitTimeMills); TimeWaitRunner(long waitTimeMills, boolean runImmediately); void doWithRunnable(Runnable runnable); }### Answer:
@Test public void testTimeWait() throws InterruptedException { TimeWaitRunner timeWaitLogger = new TimeWaitRunner(1000); AtomicLong atomicLong = new AtomicLong(); new Thread(()->{ while (true){ timeWaitLogger.doWithRunnable(atomicLong::incrementAndGet); } }).start(); Thread.sleep(1500); Assert.assertEquals(2L,atomicLong.get()); } |
### Question:
ResourceUtil { public static File getFile(URL resourceUrl) throws FileNotFoundException { return getFile(resourceUrl, "URL"); } static File getFile(URL resourceUrl); static File getFile(URL resourceUrl, String description); static URI toURI(URL url); static URI toURI(String location); static final String URL_PROTOCOL_FILE; }### Answer:
@Test public void testGetFile() throws Exception { URL url = this.getClass().getClassLoader().getResource("test-resource-utils.properties"); File file = ResourceUtil.getFile(url); Properties properties = new Properties(); properties.load(new FileInputStream(file)); Assert.assertEquals(properties.getProperty("keyA"), "A"); Assert.assertEquals(properties.getProperty("keyB"), "B"); } |
### Question:
ClassUtil { @SuppressWarnings("unchecked") public static <T> T getField(String fieldName, Object o) { Class<?> klass = o.getClass(); while (klass != null) { try { Field f = klass.getDeclaredField(fieldName); f.setAccessible(true); return (T) f.get(o); } catch (Exception e) { klass = klass.getSuperclass(); } } return null; } ClassUtil(); static boolean isPresent(String className); static boolean isPresent(String className, ClassLoader classLoader); static String getClassNameForObject(Object object); static String getClassName(Class clazz); static String getClassName(String className); static String getShortClassNameForObject(Object object); static String getShortClassName(Class clazz); static String getShortClassName(String className); static String getPackageNameForObject(Object object); static String getPackageName(Class clazz); static String getPackageName(String className); static String getClassNameForObjectAsResource(Object object); static String getClassNameAsResource(Class clazz); static String getClassNameAsResource(String className); static String getPackageNameForObjectAsResource(Object object); static String getPackageNameAsResource(Class clazz); static String getPackageNameAsResource(String className); static Class getArrayClass(Class componentType, int dimension); static Class getArrayComponentType(Class type); static int getArrayDimension(Class clazz); static List getSuperclasses(Class clazz); static List getInterfaces(Class clazz); static boolean isInnerClass(Class clazz); static boolean isAssignable(Class[] classes, Class[] fromClasses); static boolean isAssignable(Class clazz, Class fromClass); static Class getPrimitiveType(Class clazz); static Class getNonPrimitiveType(Class clazz); @SuppressWarnings("unchecked") static T getField(String fieldName, Object o); static void setField(String fieldName, Object o, T value); }### Answer:
@Test public void getFieldTest() { ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); Integer capacity = ClassUtil.getField("queueCapacity", threadPool); if (capacity != null) { Assert.assertEquals(Integer.MAX_VALUE, (long) capacity); } } |
### Question:
ClassUtil { public static <T> void setField(String fieldName, Object o, T value) { Class<?> klass = o.getClass(); while (klass != null) { try { Field f = klass.getDeclaredField(fieldName); f.setAccessible(true); f.set(o, value); return; } catch (Exception e) { klass = klass.getSuperclass(); } } } ClassUtil(); static boolean isPresent(String className); static boolean isPresent(String className, ClassLoader classLoader); static String getClassNameForObject(Object object); static String getClassName(Class clazz); static String getClassName(String className); static String getShortClassNameForObject(Object object); static String getShortClassName(Class clazz); static String getShortClassName(String className); static String getPackageNameForObject(Object object); static String getPackageName(Class clazz); static String getPackageName(String className); static String getClassNameForObjectAsResource(Object object); static String getClassNameAsResource(Class clazz); static String getClassNameAsResource(String className); static String getPackageNameForObjectAsResource(Object object); static String getPackageNameAsResource(Class clazz); static String getPackageNameAsResource(String className); static Class getArrayClass(Class componentType, int dimension); static Class getArrayComponentType(Class type); static int getArrayDimension(Class clazz); static List getSuperclasses(Class clazz); static List getInterfaces(Class clazz); static boolean isInnerClass(Class clazz); static boolean isAssignable(Class[] classes, Class[] fromClasses); static boolean isAssignable(Class clazz, Class fromClass); static Class getPrimitiveType(Class clazz); static Class getNonPrimitiveType(Class clazz); @SuppressWarnings("unchecked") static T getField(String fieldName, Object o); static void setField(String fieldName, Object o, T value); }### Answer:
@Test public void setFieldTest() { ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor(); ClassUtil.setField("queueCapacity", threadPool, 10); Integer capacity = ClassUtil.getField("queueCapacity", threadPool); if (capacity != null) { Assert.assertEquals(10, (long) capacity); } } |
### Question:
ReportUtil { public static void reportError(String msg, Throwable throwable) { LogLog.error(msg, throwable); } static void reportDebug(String msg); @Deprecated static void report(String msg); static void reportInfo(String msg); static void reportWarn(String msg); static void reportError(String msg, Throwable throwable); }### Answer:
@Test public void testUtils() { String errMsg = "Some Error Msg"; boolean isException = false; try { ReportUtil.reportError("RuntimeException", new RuntimeException()); } catch (Exception ex) { isException = true; } assertFalse(isException); } |
### Question:
Cocos2DIndexServiceImpl implements Cocos2dIndexService { @Override public NewRole queryRoleMsgQx(Integer id) throws Exception { NewRole role = null; Object ob = redisdaoservice.get(RoleMsgUtil.ROLEMSG + id); if (ob == null) { role = rolemapper.queryTotalShuXingToRole(id); if (role != null) { RoleFujiang rf = new RoleFujiang(); rf.setStatus("休息"); rf.setShuxing(1); rf.setRoleid(id); List<RoleFujiang> rfLi = rolefujiangmapper.selectAll(rf); if (rfLi != null && rfLi.size() > 0) { for (RoleFujiang f : rfLi) { List<RoleNewShuXing> kxLi = rolenewshuxingmapper.queryRoleShuXing(f.getId(), 1); f.setShuXingLi(kxLi); } } role.setFuLi(rfLi); } redisdaoservice.set(RoleMsgUtil.ROLEMSG + id, role, null); } else { role = (NewRole) ob; } return role; } @Override NewRole queryRoleMsg(Integer id); @Override NewRole queryRoleById(Integer id); @Override NewRole queryRoleMsgQx(Integer id); @Override NewRole queryRoleMsg(Integer id, Integer friendId); @Override Object[] chatMsg(); @Override GjsgMap moveCity(String city, HttpSession session); @Override MapGuai queryMapGuai(String city); @Override YeGuaiQun queryYeGuaiQun(String name); @Override List<NewRole> nearbyRole(String city, String key); }### Answer:
@Test public void queryRoleMsgQx() throws Exception { NewRole role=cocos2dindexservice.queryRoleMsgQx(1000); } |
### Question:
PkServerDaoImpl extends TextWebSocketHandler implements PkServerDao { @Override public void loading() { } @Override void loading(); @Override void proA(); @Override void proB(); @Override void proData(); @Override void excute(); @Override void afterConnectionEstablished(WebSocketSession session); @Override void afterConnectionClosed(WebSocketSession session, CloseStatus status); }### Answer:
@Test public void loading() throws Exception { } |
### Question:
LoadGuaiServiceImpl implements LoadGuaiService { @Override public List<FuJiang> queryGuaiData(String name) throws Exception{ YeGuaiQun ygq=yeguaiqunmapper.selectByName(name); List<FuJiang> li=fujiangmapper.queryFuJiangByName(ygq.getGuai1(),ygq.getGuai2(),ygq.getGuai3(),ygq.getGuai4(),ygq.getGuai5(),ygq.getGuai6()); return li; } @Override List<FuJiang> queryGuaiData(String name); @Override void pkTest(); }### Answer:
@Test public void queryGuaiData() throws Exception { } |
### Question:
Cocos2DIndexServiceImpl implements Cocos2dIndexService { @Override public NewRole queryRoleMsgQx(Integer id) throws Exception { NewRole role= rolemapper.queryTotalShuXingToRole(id); if(role!=null){ RoleFujiang rf=new RoleFujiang(); rf.setStatus("休息"); rf.setShuxing(1); List<RoleFujiang> rfLi= rolefujiangmapper.selectAll(rf); if(rfLi!=null&&rfLi.size()>0){ for(RoleFujiang f:rfLi){ List<RoleNewShuXing> kxLi= rolenewshuxingmapper.queryRoleShuXing(f.getId(),1); f.setShuXingLi(kxLi); } } role.setFuLi(rfLi); } return role; } @Override NewRole queryRoleMsg(Integer id); @Override NewRole queryRoleById(Integer id); @Override NewRole queryRoleMsgQx(Integer id); @Override NewRole queryRoleMsg(Integer id,Integer friendId); @Override Object[] chatMsg(); @Override GjsgMap moveCity(String city,HttpSession session); @Override MapGuai queryMapGuai(String city); @Override YeGuaiQun queryYeGuaiQun(String name); @Override List<NewRole> nearbyRole(String city,String key); static void main(String[] args); }### Answer:
@Test public void queryRoleMsgQx() throws Exception { System.out.println("----------"); } |
### Question:
Elements extends ArrayList<Element> { public Elements filter(NodeFilter nodeFilter) { NodeTraversor.filter(nodeFilter, this); return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void filter() { String h = "<p>Excl</p><div class=headline><p>Hello</p><p>There</p></div><div class=headline><h1>Headline</h1></div>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".headline").select("p"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("There", els.get(1).text()); } |
### Question:
Document extends Element { public String location() { return location; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); Parser parser(); Document parser(Parser parser); }### Answer:
@Test public void testLocation() throws IOException { File in = new ParseTest().getFile("/htmltests/yahoo-jp.html"); Document doc = Jsoup.parse(in, "UTF-8", "http: String location = doc.location(); String baseUri = doc.baseUri(); assertEquals("http: assertEquals("http: in = new ParseTest().getFile("/htmltests/nyt-article-1.html"); doc = Jsoup.parse(in, null, "http: location = doc.location(); baseUri = doc.baseUri(); assertEquals("http: assertEquals("http: } |
### Question:
Elements extends ArrayList<Element> { public Elements wrap(String html) { Validate.notEmpty(html); for (Element element : this) { element.wrap(html); } return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void wrap() { String h = "<p><b>This</b> is <b>jsoup</b></p>"; Document doc = Jsoup.parse(h); doc.select("b").wrap("<i></i>"); assertEquals("<p><i><b>This</b></i> is <i><b>jsoup</b></i></p>", doc.body().html()); } |
### Question:
Document extends Element { public static Document createShell(String baseUri) { Validate.notNull(baseUri); Document doc = new Document(baseUri); doc.parser = doc.parser(); Element html = doc.appendElement("html"); html.appendElement("head"); html.appendElement("body"); return doc; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); Parser parser(); Document parser(Parser parser); }### Answer:
@Test public void testMetaCharsetUpdateDisabled() { final Document docDisabled = Document.createShell(""); final String htmlNoCharset = "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlNoCharset, docDisabled.toString()); assertNull(docDisabled.select("meta[charset]").first()); } |
### Question:
Document extends Element { public void charset(Charset charset) { updateMetaCharsetElement(true); outputSettings.charset(charset); ensureMetaCharsetElement(); } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); Parser parser(); Document parser(Parser parser); }### Answer:
@Test public void testMetaCharsetUpdateEnabledAfterCharsetChange() { final Document doc = createHtmlDocument("dontTouch"); doc.charset(Charset.forName(charsetUtf8)); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetUtf8, selectedElement.attr("charset")); assertTrue(doc.select("meta[name=charset]").isEmpty()); } |
### Question:
Document extends Element { public void updateMetaCharsetElement(boolean update) { this.updateMetaCharset = update; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); Parser parser(); Document parser(Parser parser); }### Answer:
@Test public void testMetaCharsetUpdatedDisabledPerDefault() { final Document doc = createHtmlDocument("none"); assertFalse(doc.updateMetaCharsetElement()); } |
### Question:
Elements extends ArrayList<Element> { public Elements unwrap() { for (Element element : this) { element.unwrap(); } return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void unwrap() { String h = "<div><font>One</font> <font><a href=\"/\">Two</a></font></div"; Document doc = Jsoup.parse(h); doc.select("font").unwrap(); assertEquals("<div>One <a href=\"/\">Two</a></div>", TextUtil.stripNewlines(doc.body().html())); } |
### Question:
Attribute implements Map.Entry<String, String>, Cloneable { public String html() { StringBuilder sb = StringUtil.borrowBuilder(); try { html(sb, (new Document("")).outputSettings()); } catch(IOException exception) { throw new SerializationException(exception); } return StringUtil.releaseBuilder(sb); } Attribute(String key, String value); Attribute(String key, String val, Attributes parent); String getKey(); void setKey(String key); String getValue(); String setValue(String val); String html(); @Override String toString(); static Attribute createFromEncoded(String unencodedKey, String encodedValue); @Override boolean equals(Object o); @Override int hashCode(); @Override Attribute clone(); }### Answer:
@Test public void html() { Attribute attr = new Attribute("key", "value &"); assertEquals("key=\"value &\"", attr.html()); assertEquals(attr.html(), attr.toString()); } |
### Question:
Attribute implements Map.Entry<String, String>, Cloneable { public void setKey(String key) { Validate.notNull(key); key = key.trim(); Validate.notEmpty(key); if (parent != null) { int i = parent.indexOfKey(this.key); if (i != Attributes.NotFound) parent.keys[i] = key; } this.key = key; } Attribute(String key, String value); Attribute(String key, String val, Attributes parent); String getKey(); void setKey(String key); String getValue(); String setValue(String val); String html(); @Override String toString(); static Attribute createFromEncoded(String unencodedKey, String encodedValue); @Override boolean equals(Object o); @Override int hashCode(); @Override Attribute clone(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void validatesKeysNotEmptyViaSet() { Attribute attr = new Attribute("One", "Check"); attr.setKey(" "); } |
### Question:
TextNode extends LeafNode { public TextNode splitText(int offset) { final String text = coreValue(); Validate.isTrue(offset >= 0, "Split offset must be not be negative"); Validate.isTrue(offset < text.length(), "Split offset must not be greater than current text length"); String head = text.substring(0, offset); String tail = text.substring(offset); text(head); TextNode tailNode = new TextNode(tail); if (parent() != null) parent().addChildren(siblingIndex()+1, tailNode); return tailNode; } TextNode(String text); TextNode(String text, String baseUri); String nodeName(); String text(); TextNode text(String text); String getWholeText(); boolean isBlank(); TextNode splitText(int offset); @Override String toString(); static TextNode createFromEncoded(String encodedText, String baseUri); static TextNode createFromEncoded(String encodedText); }### Answer:
@Test public void testSplitText() { Document doc = Jsoup.parse("<div>Hello there</div>"); Element div = doc.select("div").first(); TextNode tn = (TextNode) div.childNode(0); TextNode tail = tn.splitText(6); assertEquals("Hello ", tn.getWholeText()); assertEquals("there", tail.getWholeText()); tail.text("there!"); assertEquals("Hello there!", div.text()); assertTrue(tn.parent() == tail.parent()); }
@Test public void testSplitAnEmbolden() { Document doc = Jsoup.parse("<div>Hello there</div>"); Element div = doc.select("div").first(); TextNode tn = (TextNode) div.childNode(0); TextNode tail = tn.splitText(6); tail.wrap("<b></b>"); assertEquals("Hello <b>there</b>", TextUtil.stripNewlines(div.html())); } |
### Question:
Elements extends ArrayList<Element> { public Elements empty() { for (Element element : this) { element.empty(); } return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void empty() { Document doc = Jsoup.parse("<div><p>Hello <b>there</b></p> <p>now!</p></div>"); doc.outputSettings().prettyPrint(false); doc.select("p").empty(); assertEquals("<div><p></p> <p></p></div>", doc.body().html()); } |
### Question:
Elements extends ArrayList<Element> { public Elements remove() { for (Element element : this) { element.remove(); } return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void remove() { Document doc = Jsoup.parse("<div><p>Hello <b>there</b></p> jsoup <p>now!</p></div>"); doc.outputSettings().prettyPrint(false); doc.select("p").remove(); assertEquals("<div> jsoup </div>", doc.body().html()); } |
### Question:
Elements extends ArrayList<Element> { public Elements eq(int index) { return size() > index ? new Elements(get(index)) : new Elements(); } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void eq() { String h = "<p>Hello<p>there<p>world"; Document doc = Jsoup.parse(h); assertEquals("there", doc.select("p").eq(1).text()); assertEquals("there", doc.select("p").get(1).text()); } |
### Question:
Elements extends ArrayList<Element> { public boolean is(String query) { Evaluator eval = QueryParser.parse(query); for (Element e : this) { if (e.is(eval)) return true; } return false; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void is() { String h = "<p>Hello<p title=foo>there<p>world"; Document doc = Jsoup.parse(h); Elements ps = doc.select("p"); assertTrue(ps.is("[title=foo]")); assertFalse(ps.is("[title=bar]")); } |
### Question:
Entities { public static String getByName(String name) { String val = multipoints.get(name); if (val != null) return val; int codepoint = extended.codepointForName(name); if (codepoint != empty) return new String(new int[]{codepoint}, 0, 1); return emptyName; } private Entities(); static boolean isNamedEntity(final String name); static boolean isBaseNamedEntity(final String name); static Character getCharacterByName(String name); static String getByName(String name); static int codepointsForName(final String name, final int[] codepoints); static String escape(String string, Document.OutputSettings out); static String escape(String string); static String unescape(String string); }### Answer:
@Test public void getByName() { assertEquals("≫⃒", Entities.getByName("nGt")); assertEquals("fj", Entities.getByName("fjlig")); assertEquals("≫", Entities.getByName("gg")); assertEquals("©", Entities.getByName("copy")); } |
### Question:
Elements extends ArrayList<Element> { public Elements parents() { HashSet<Element> combo = new LinkedHashSet<>(); for (Element e: this) { combo.addAll(e.parents()); } return new Elements(combo); } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void parents() { Document doc = Jsoup.parse("<div><p>Hello</p></div><p>There</p>"); Elements parents = doc.select("p").parents(); assertEquals(3, parents.size()); assertEquals("div", parents.get(0).tagName()); assertEquals("body", parents.get(1).tagName()); assertEquals("html", parents.get(2).tagName()); } |
### Question:
Elements extends ArrayList<Element> { public Elements not(String query) { Elements out = Selector.select(query, this); return Selector.filterOut(this, out); } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void not() { Document doc = Jsoup.parse("<div id=1><p>One</p></div> <div id=2><p><span>Two</span></p></div>"); Elements div1 = doc.select("div").not(":has(p > span)"); assertEquals(1, div1.size()); assertEquals("1", div1.first().id()); Elements div2 = doc.select("div").not("#1"); assertEquals(1, div2.size()); assertEquals("2", div2.first().id()); } |
### Question:
Elements extends ArrayList<Element> { public boolean hasAttr(String attributeKey) { for (Element element : this) { if (element.hasAttr(attributeKey)) return true; } return false; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void hasAttr() { Document doc = Jsoup.parse("<p title=foo><p title=bar><p class=foo><p class=bar>"); Elements ps = doc.select("p"); assertTrue(ps.hasAttr("class")); assertFalse(ps.hasAttr("style")); } |
### Question:
Parser { public static String unescapeEntities(String string, boolean inAttribute) { Tokeniser tokeniser = new Tokeniser(new CharacterReader(string), ParseErrorList.noTracking()); return tokeniser.unescapeEntities(inAttribute); } Parser(TreeBuilder treeBuilder); Document parseInput(String html, String baseUri); Document parseInput(Reader inputHtml, String baseUri); List<Node> parseFragmentInput(String fragment, Element context, String baseUri); TreeBuilder getTreeBuilder(); Parser setTreeBuilder(TreeBuilder treeBuilder); boolean isTrackErrors(); Parser setTrackErrors(int maxErrors); ParseErrorList getErrors(); Parser settings(ParseSettings settings); ParseSettings settings(); static Document parse(String html, String baseUri); static List<Node> parseFragment(String fragmentHtml, Element context, String baseUri); static List<Node> parseFragment(String fragmentHtml, Element context, String baseUri, ParseErrorList errorList); static List<Node> parseXmlFragment(String fragmentXml, String baseUri); static Document parseBodyFragment(String bodyHtml, String baseUri); static String unescapeEntities(String string, boolean inAttribute); static Document parseBodyFragmentRelaxed(String bodyHtml, String baseUri); static Parser htmlParser(); static Parser xmlParser(); }### Answer:
@Test public void unescapeEntities() { String s = Parser.unescapeEntities("One & Two", false); assertEquals("One & Two", s); }
@Test public void unescapeEntitiesHandlesLargeInput() { StringBuilder longBody = new StringBuilder(500000); do { longBody.append("SomeNonEncodedInput"); } while (longBody.length() < 64 * 1024); String body = longBody.toString(); assertEquals(body, Parser.unescapeEntities(body, false)); } |
### Question:
CharacterReader { char consume() { bufferUp(); char val = isEmptyNoBufferUp() ? EOF : charBuf[bufPos]; bufPos++; return val; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer:
@Test public void consume() { CharacterReader r = new CharacterReader("one"); assertEquals(0, r.pos()); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals(1, r.pos()); assertEquals('n', r.current()); assertEquals(1, r.pos()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); } |
### Question:
CharacterReader { void unconsume() { if (bufPos < 1) throw new UncheckedIOException(new IOException("No buffer left to unconsume")); bufPos--; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer:
@Test public void unconsume() { CharacterReader r = new CharacterReader("one"); assertEquals('o', r.consume()); assertEquals('n', r.current()); r.unconsume(); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.unconsume(); assertFalse(r.isEmpty()); assertEquals('e', r.current()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); r.unconsume(); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.current()); } |
### Question:
CharacterReader { void mark() { bufSplitPoint = 0; bufferUp(); bufMark = bufPos; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer:
@Test public void mark() { CharacterReader r = new CharacterReader("one"); r.consume(); r.mark(); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.rewindToMark(); assertEquals('n', r.consume()); } |
### Question:
CharacterReader { public String consumeToAny(final char... chars) { bufferUp(); int pos = bufPos; final int start = pos; final int remaining = bufLength; final char[] val = charBuf; final int charLen = chars.length; int i; OUTER: while (pos < remaining) { for (i = 0; i < charLen; i++) { if (val[pos] == chars[i]) break OUTER; } pos++; } bufPos = pos; return pos > start ? cacheString(charBuf, stringCache, start, pos -start) : ""; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer:
@Test public void consumeToAny() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One ", r.consumeToAny('&', ';')); assertTrue(r.matches('&')); assertTrue(r.matches("&bar;")); assertEquals('&', r.consume()); assertEquals("bar", r.consumeToAny('&', ';')); assertEquals(';', r.consume()); assertEquals(" qux", r.consumeToAny('&', ';')); } |
### Question:
CharacterReader { String consumeLetterThenDigitSequence() { bufferUp(); int start = bufPos; while (bufPos < bufLength) { char c = charBuf[bufPos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c)) bufPos++; else break; } while (!isEmptyNoBufferUp()) { char c = charBuf[bufPos]; if (c >= '0' && c <= '9') bufPos++; else break; } return cacheString(charBuf, stringCache, start, bufPos - start); } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer:
@Test public void consumeLetterThenDigitSequence() { CharacterReader r = new CharacterReader("One12 Two &bar; qux"); assertEquals("One12", r.consumeLetterThenDigitSequence()); assertEquals(' ', r.consume()); assertEquals("Two", r.consumeLetterThenDigitSequence()); assertEquals(" &bar; qux", r.consumeToEnd()); } |
### Question:
CharacterReader { private void bufferUp() { final int pos = bufPos; if (pos < bufSplitPoint) return; try { reader.skip(pos); reader.mark(maxBufferLen); final int read = reader.read(charBuf); reader.reset(); if (read != -1) { bufLength = read; readerPos += pos; bufPos = 0; bufMark = -1; bufSplitPoint = bufLength > readAheadLimit ? readAheadLimit : bufLength; } } catch (IOException e) { throw new UncheckedIOException(e); } } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer:
@Test public void bufferUp() { String note = "HelloThere"; int loopCount = 64; StringBuilder sb = new StringBuilder(); for (int i = 0; i < loopCount; i++) { sb.append(note); sb.append("!"); } String s = sb.toString(); BufferedReader br = new BufferedReader(new StringReader(s)); CharacterReader r = new CharacterReader(br); for (int i = 0; i < loopCount; i++) { String pull = r.consumeTo('!'); assertEquals(note, pull); assertEquals('!', r.current()); r.advance(); } assertTrue(r.isEmpty()); } |
### Question:
TokenQueue { public static String unescape(String in) { StringBuilder out = StringUtil.borrowBuilder(); char last = 0; for (char c : in.toCharArray()) { if (c == ESC) { if (last != 0 && last == ESC) out.append(c); } else out.append(c); last = c; } return StringUtil.releaseBuilder(out); } TokenQueue(String data); boolean isEmpty(); char peek(); void addFirst(Character c); void addFirst(String seq); boolean matches(String seq); boolean matchesCS(String seq); boolean matchesAny(String... seq); boolean matchesAny(char... seq); boolean matchesStartTag(); boolean matchChomp(String seq); boolean matchesWhitespace(); boolean matchesWord(); void advance(); char consume(); void consume(String seq); String consumeTo(String seq); String consumeToIgnoreCase(String seq); String consumeToAny(String... seq); String chompTo(String seq); String chompToIgnoreCase(String seq); String chompBalanced(char open, char close); static String unescape(String in); boolean consumeWhitespace(); String consumeWord(); String consumeTagName(); String consumeElementSelector(); String consumeCssIdentifier(); String consumeAttributeKey(); String remainder(); @Override String toString(); }### Answer:
@Test public void unescape() { assertEquals("one ( ) \\", TokenQueue.unescape("one \\( \\) \\\\")); } |
### Question:
TokenQueue { public String chompToIgnoreCase(String seq) { String data = consumeToIgnoreCase(seq); matchChomp(seq); return data; } TokenQueue(String data); boolean isEmpty(); char peek(); void addFirst(Character c); void addFirst(String seq); boolean matches(String seq); boolean matchesCS(String seq); boolean matchesAny(String... seq); boolean matchesAny(char... seq); boolean matchesStartTag(); boolean matchChomp(String seq); boolean matchesWhitespace(); boolean matchesWord(); void advance(); char consume(); void consume(String seq); String consumeTo(String seq); String consumeToIgnoreCase(String seq); String consumeToAny(String... seq); String chompTo(String seq); String chompToIgnoreCase(String seq); String chompBalanced(char open, char close); static String unescape(String in); boolean consumeWhitespace(); String consumeWord(); String consumeTagName(); String consumeElementSelector(); String consumeCssIdentifier(); String consumeAttributeKey(); String remainder(); @Override String toString(); }### Answer:
@Test public void consumeToIgnoreSecondCallTest() { String t = "<textarea>one < two </TEXTarea> third </TEXTarea>"; TokenQueue tq = new TokenQueue(t); String data = tq.chompToIgnoreCase("</textarea>"); assertEquals("<textarea>one < two ", data); data = tq.chompToIgnoreCase("</textarea>"); assertEquals(" third ", data); }
@Test public void chompToIgnoreCase() { String t = "<textarea>one < two </TEXTarea>"; TokenQueue tq = new TokenQueue(t); String data = tq.chompToIgnoreCase("</textarea"); assertEquals("<textarea>one < two ", data); tq = new TokenQueue("<textarea> one two < three </oops>"); data = tq.chompToIgnoreCase("</textarea"); assertEquals("<textarea> one two < three </oops>", data); } |
### Question:
Tag { public static Tag valueOf(String tagName, ParseSettings settings) { Validate.notNull(tagName); Tag tag = tags.get(tagName); if (tag == null) { tagName = settings.normalizeTag(tagName); Validate.notEmpty(tagName); tag = tags.get(tagName); if (tag == null) { tag = new Tag(tagName); tag.isBlock = false; } } return tag; } private Tag(String tagName); String getName(); String normalName(); static Tag valueOf(String tagName, ParseSettings settings); static Tag valueOf(String tagName); boolean isBlock(); boolean formatAsBlock(); boolean canContainBlock(); boolean isInline(); boolean isData(); boolean isEmpty(); boolean isSelfClosing(); boolean isKnownTag(); static boolean isKnownTag(String tagName); boolean preserveWhitespace(); boolean isFormListed(); boolean isFormSubmittable(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test @MultiLocaleTest public void canBeInsensitive() { Tag script1 = Tag.valueOf("script", ParseSettings.htmlDefault); Tag script2 = Tag.valueOf("SCRIPT", ParseSettings.htmlDefault); assertSame(script1, script2); }
@Test public void trims() { Tag p1 = Tag.valueOf("p"); Tag p2 = Tag.valueOf(" p "); assertEquals(p1, p2); }
@Test(expected = IllegalArgumentException.class) public void valueOfChecksNotNull() { Tag.valueOf(null); }
@Test(expected = IllegalArgumentException.class) public void valueOfChecksNotEmpty() { Tag.valueOf(" "); } |
### Question:
HttpConnection implements Connection { public Connection cookies(Map<String, String> cookies) { Validate.notNull(cookies, "Cookie map must not be null"); for (Map.Entry<String, String> entry : cookies.entrySet()) { req.cookie(entry.getKey(), entry.getValue()); } return this; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void ignoresEmptySetCookies() { Map<String, List<String>> headers = new HashMap<>(); headers.put("Set-Cookie", Collections.<String>emptyList()); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals(0, res.cookies().size()); } |
### Question:
HttpConnection implements Connection { public static Connection connect(String url) { Connection con = new HttpConnection(); con.url(url); return con; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test(expected=IllegalArgumentException.class) public void throwsOnMalformedUrl() { Connection con = HttpConnection.connect("bzzt"); } |
### Question:
HttpConnection implements Connection { public Connection userAgent(String userAgent) { Validate.notNull(userAgent, "User agent must not be null"); req.header(USER_AGENT, userAgent); return this; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void userAgent() { Connection con = HttpConnection.connect("http: assertEquals(HttpConnection.DEFAULT_UA, con.request().header("User-Agent")); con.userAgent("Mozilla"); assertEquals("Mozilla", con.request().header("User-Agent")); } |
### Question:
HttpConnection implements Connection { public Connection timeout(int millis) { req.timeout(millis); return this; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void timeout() { Connection con = HttpConnection.connect("http: assertEquals(30 * 1000, con.request().timeout()); con.timeout(1000); assertEquals(1000, con.request().timeout()); } |
### Question:
HttpConnection implements Connection { public Connection referrer(String referrer) { Validate.notNull(referrer, "Referrer must not be null"); req.header("Referer", referrer); return this; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void referrer() { Connection con = HttpConnection.connect("http: con.referrer("http: assertEquals("http: } |
### Question:
HttpConnection implements Connection { public Connection method(Method method) { req.method(method); return this; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void method() { Connection con = HttpConnection.connect("http: assertEquals(Connection.Method.GET, con.request().method()); con.method(Connection.Method.POST); assertEquals(Connection.Method.POST, con.request().method()); } |
### Question:
HttpConnection implements Connection { public Connection cookie(String name, String value) { req.cookie(name, value); return this; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void cookie() { Connection con = HttpConnection.connect("http: con.cookie("Name", "Val"); assertEquals("Val", con.request().cookie("Name")); } |
### Question:
HttpConnection implements Connection { public Connection requestBody(String body) { req.requestBody(body); return this; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void requestBody() { Connection con = HttpConnection.connect("http: con.requestBody("foo"); assertEquals("foo", con.request().requestBody()); } |
### Question:
HttpConnection implements Connection { private static String encodeUrl(String url) { try { URL u = new URL(url); return encodeUrl(u).toExternalForm(); } catch (Exception e) { return url; } } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void encodeUrl() throws MalformedURLException { URL url1 = new URL("http: URL url2 = HttpConnection.encodeUrl(url1); assertEquals("http: } |
### Question:
HttpConnection implements Connection { public Connection.Response execute() throws IOException { res = Response.execute(req); return res; } HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection data(String key, String value); Connection sslSocketFactory(SSLSocketFactory sslSocketFactory); Connection data(String key, String filename, InputStream inputStream); @Override Connection data(String key, String filename, InputStream inputStream, String contentType); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; static final String CONTENT_TYPE; static final String MULTIPART_FORM_DATA; static final String FORM_URL_ENCODED; }### Answer:
@Test public void noUrlThrowsValidationError() throws IOException { HttpConnection con = new HttpConnection(); boolean threw = false; try { con.execute(); } catch (IllegalArgumentException e) { threw = true; assertEquals("URL must be specified to connect", e.getMessage()); } assertTrue(threw); } |
### Question:
DataUtil { static String mimeBoundary() { final StringBuilder mime = StringUtil.borrowBuilder(); final Random rand = new Random(); for (int i = 0; i < boundaryLength; i++) { mime.append(mimeBoundaryChars[rand.nextInt(mimeBoundaryChars.length)]); } return StringUtil.releaseBuilder(mime); } private DataUtil(); static Document load(File in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri, Parser parser); static ByteBuffer readToByteBuffer(InputStream inStream, int maxSize); }### Answer:
@Test public void generatesMimeBoundaries() { String m1 = DataUtil.mimeBoundary(); String m2 = DataUtil.mimeBoundary(); assertEquals(DataUtil.boundaryLength, m1.length()); assertEquals(DataUtil.boundaryLength, m2.length()); assertNotSame(m1, m2); } |
### Question:
NodeWalker { public void skipChildren() { int childLen = (currentChildren != null) ? currentChildren.getLength() : 0; for (int i = 0; i < childLen; i++) { Node child = nodes.peek(); if (child.equals(currentChildren.item(i))) { nodes.pop(); } } } NodeWalker(Node rootNode); Node nextNode(); void skipChildren(); Node getCurrentNode(); boolean hasNext(); }### Answer:
@Test public void testSkipChildren() { DOMParser parser = new DOMParser(); try { parser.setFeature("http: parser.setFeature( "http: false); parser .parse(new InputSource(new ByteArrayInputStream(WEBPAGE.getBytes()))); } catch (Exception e) { e.printStackTrace(); } StringBuffer sb = new StringBuffer(); NodeWalker walker = new NodeWalker(parser.getDocument()); while (walker.hasNext()) { Node currentNode = walker.nextNode(); short nodeType = currentNode.getNodeType(); if (nodeType == Node.TEXT_NODE) { String text = currentNode.getNodeValue(); text = text.replaceAll("\\s+", " "); sb.append(text); } } assertTrue("UL Content can NOT be found in the node", findSomeUlContent(sb.toString())); StringBuffer sbSkip = new StringBuffer(); NodeWalker walkerSkip = new NodeWalker(parser.getDocument()); while (walkerSkip.hasNext()) { Node currentNode = walkerSkip.nextNode(); String nodeName = currentNode.getNodeName(); short nodeType = currentNode.getNodeType(); if ("ul".equalsIgnoreCase(nodeName)) { walkerSkip.skipChildren(); } if (nodeType == Node.TEXT_NODE) { String text = currentNode.getNodeValue(); text = text.replaceAll("\\s+", " "); sbSkip.append(text); } } assertFalse("UL Content can be found in the node", findSomeUlContent(sbSkip.toString())); } |
### Question:
Elements extends ArrayList<Element> { public String attr(String attributeKey) { for (Element element : this) { if (element.hasAttr(attributeKey)) return element.attr(attributeKey); } return ""; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void attr() { Document doc = Jsoup.parse("<p title=foo><p title=bar><p class=foo><p class=bar>"); String classVal = doc.select("p").attr("class"); assertEquals("foo", classVal); } |
### Question:
Elements extends ArrayList<Element> { public boolean hasText() { for (Element element: this) { if (element.hasText()) return true; } return false; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void hasText() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p></p></div>"); Elements divs = doc.select("div"); assertTrue(divs.hasText()); assertFalse(doc.select("div + div").hasText()); } |
### Question:
Elements extends ArrayList<Element> { public String html() { StringBuilder sb = StringUtil.borrowBuilder(); for (Element element : this) { if (sb.length() != 0) sb.append("\n"); sb.append(element.html()); } return StringUtil.releaseBuilder(sb); } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void html() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p>There</p></div>"); Elements divs = doc.select("div"); assertEquals("<p>Hello</p>\n<p>There</p>", divs.html()); } |
### Question:
Elements extends ArrayList<Element> { public String outerHtml() { StringBuilder sb = StringUtil.borrowBuilder(); for (Element element : this) { if (sb.length() != 0) sb.append("\n"); sb.append(element.outerHtml()); } return StringUtil.releaseBuilder(sb); } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void outerHtml() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div><p>There</p></div>"); Elements divs = doc.select("div"); assertEquals("<div><p>Hello</p></div><div><p>There</p></div>", TextUtil.stripNewlines(divs.outerHtml())); } |
### Question:
Selector { public static Element selectFirst(String cssQuery, Element root) { Validate.notEmpty(cssQuery); return Collector.findFirst(QueryParser.parse(cssQuery), root); } private Selector(); static Elements select(String query, Element root); static Elements select(Evaluator evaluator, Element root); static Elements select(String query, Iterable<Element> roots); static Element selectFirst(String cssQuery, Element root); }### Answer:
@Test public void selectFirst() { String html = "<p>One<p>Two<p>Three"; Document doc = Jsoup.parse(html); assertEquals("One", doc.selectFirst("p").text()); }
@Test public void selectFirstWithAnd() { String html = "<p>One<p class=foo>Two<p>Three"; Document doc = Jsoup.parse(html); assertEquals("Two", doc.selectFirst("p.foo").text()); }
@Test public void selectFirstWithOr() { String html = "<p>One<p>Two<p>Three<div>Four"; Document doc = Jsoup.parse(html); assertEquals("One", doc.selectFirst("p, div").text()); } |
### Question:
Elements extends ArrayList<Element> { public String val() { if (size() > 0) return first().val(); else return ""; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void val() { Document doc = Jsoup.parse("<input value='one' /><textarea>two</textarea>"); Elements els = doc.select("input, textarea"); assertEquals(2, els.size()); assertEquals("one", els.val()); assertEquals("two", els.last().val()); els.val("three"); assertEquals("three", els.first().val()); assertEquals("three", els.last().val()); assertEquals("<textarea>three</textarea>", els.last().outerHtml()); } |
### Question:
Elements extends ArrayList<Element> { public Elements before(String html) { for (Element element : this) { element.before(html); } return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void before() { Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>"); doc.select("a").before("<span>foo</span>"); assertEquals("<p>This <span>foo</span><a>is</a> <span>foo</span><a>jsoup</a>.</p>", TextUtil.stripNewlines(doc.body().html())); } |
### Question:
Node implements Cloneable { public void remove() { Validate.notNull(parentNode); parentNode.removeChild(this); } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); String getAttr(String attributeKey, String defaultValue); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); @Deprecated void addAttr(String attributeKey, String attributeValue, String separator); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); @NotNull Node getOwnerDocumentNode(); @NotNull Node getOwnerBody(); String getImmutableText(); void setImmutableText(String immutableText); @NotNull RealVector getFeatures(); void setFeatures(@NotNull RealVector features); @NotNull Map<String, Object> getVariables(); @NotNull Map<String, List<Object>> getTuples(); int siblingSize(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); Node filter(NodeFilter nodeFilter); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); Node shallowClone(); static final String EmptyString; static final RealVector EMPTY_FEATURE; }### Answer:
@Test public void testRemove() { Document doc = Jsoup.parse("<p>One <span>two</span> three</p>"); Element p = doc.select("p").first(); p.childNode(0).remove(); assertEquals("two three", p.text()); assertEquals("<span>two</span> three", TextUtil.stripNewlines(p.html())); } |
### Question:
Node implements Cloneable { public Document ownerDocument() { Node root = root(); return (root instanceof Document) ? (Document) root : null; } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); String getAttr(String attributeKey, String defaultValue); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); @Deprecated void addAttr(String attributeKey, String attributeValue, String separator); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); @NotNull Node getOwnerDocumentNode(); @NotNull Node getOwnerBody(); String getImmutableText(); void setImmutableText(String immutableText); @NotNull RealVector getFeatures(); void setFeatures(@NotNull RealVector features); @NotNull Map<String, Object> getVariables(); @NotNull Map<String, List<Object>> getTuples(); int siblingSize(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); Node filter(NodeFilter nodeFilter); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); Node shallowClone(); static final String EmptyString; static final RealVector EMPTY_FEATURE; }### Answer:
@Test public void ownerDocument() { Document doc = Jsoup.parse("<p>Hello"); Element p = doc.select("p").first(); assertTrue(p.ownerDocument() == doc); assertTrue(doc.ownerDocument() == doc); assertNull(doc.parent()); } |
### Question:
Elements extends ArrayList<Element> { public Elements after(String html) { for (Element element : this) { element.after(html); } return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); Elements filter(NodeFilter nodeFilter); List<FormElement> forms(); }### Answer:
@Test public void after() { Document doc = Jsoup.parse("<p>This <a>is</a> <a>jsoup</a>.</p>"); doc.select("a").after("<span>foo</span>"); assertEquals("<p>This <a>is</a><span>foo</span> <a>jsoup</a><span>foo</span>.</p>", TextUtil.stripNewlines(doc.body().html())); } |
### Question:
Utils { public static String implode(String separator, List<String> elements){ StringBuffer s = new StringBuffer(); for(int i = 0; i < elements.size(); i++){ if(i > 0){ s.append(" "); } s.append(elements.get(i)); } return s.toString(); } static List<String> merge(List<String> first, List<String> second); static List<String> prepend(String first, List<String> list); static String normalize(String path); static String implode(String separator, List<String> elements); static boolean isRelative(String path); }### Answer:
@Test public void testImplode() { final String separator = "Bar"; final List<String> elements = new ArrayList<String>(); assertEquals("", Utils.implode(separator, elements)); elements.add("foo"); elements.add("bar"); assertEquals("foo bar", Utils.implode(separator, elements)); } |
### Question:
Utils { public static boolean isRelative(String path) { return !path.startsWith("/") && !path.startsWith("file:") && !path.matches("^[a-zA-Z]:\\\\.*"); } static List<String> merge(List<String> first, List<String> second); static List<String> prepend(String first, List<String> list); static String normalize(String path); static String implode(String separator, List<String> elements); static boolean isRelative(String path); }### Answer:
@Test public void testIsRelative() { assertTrue(Utils.isRelative("foo/bar")); assertFalse(Utils.isRelative("/foo/bar")); assertFalse(Utils.isRelative("file:foo/bar")); assertFalse(Utils.isRelative("C:\\SYSTEM")); } |
### Question:
Utils { public static List<String> merge(List<String> first, List<String> second) { ArrayList<String> result = new ArrayList<String>(first); result.addAll(second); return result; } static List<String> merge(List<String> first, List<String> second); static List<String> prepend(String first, List<String> list); static String normalize(String path); static String implode(String separator, List<String> elements); static boolean isRelative(String path); }### Answer:
@Test public void testMerge() { assertEquals( Arrays.asList("foo", "bar"), Utils.merge(Arrays.asList("foo"), Arrays.asList("bar")) ); } |
### Question:
Utils { public static List<String> prepend(String first, List<String> list){ return merge(Arrays.asList(first), list); } static List<String> merge(List<String> first, List<String> second); static List<String> prepend(String first, List<String> list); static String normalize(String path); static String implode(String separator, List<String> elements); static boolean isRelative(String path); }### Answer:
@Test public void testPrepend() { assertEquals( Arrays.asList("foo", "bar"), Utils.prepend("foo", Arrays.asList("bar")) ); } |
### Question:
ProductService implements IProductService { public Product findById(Long id) { Span childSpan = tracer.buildSpan("findById").start(); childSpan.setTag("layer", "Service"); logger.debug("Entering ProductService.findById()"); Product p = repository.findById(id); childSpan.finish(); return p; } Product findById(Long id); }### Answer:
@Test public void findByIdExistingTest() { Product p = service.findById(1L); assertThat(p.getId(), equalTo(1L)); assertThat(p.getName(), equalTo("Test")); assertThat(p.getDescription(), equalTo("Test Product")); }
@Test public void findByIdNonExistingTest() { Product p = service.findById(2L); assertThat(p, is(nullValue())); } |
### Question:
OrdersService { public Order getById(Long id) { Span span = tracer.buildSpan("getById").start(); log.debug("Entering OrdersService.getById()"); Order o = orderRepository.getOrderById(id); if (o != null) { o.setCustomer(customerRepository.getCustomerById(o.getCustomer().getId())); o.setItems(inventoryRepository.getProductDetails(o.getItems())); } span.finish(); return o; } Order getById(Long id); }### Answer:
@Test public void getByIdWithNonExistingOrderTest() { Mockito.when(orderRepository.getOrderById(new Long(1))) .thenReturn(null); Order found = ordersService.getById(new Long(1)); assertThat(found).isNull(); }
@Test public void getByIdWithExistingOrderTest() { Order o = new Order(); o.setId(new Long(1)); o.setDate(new GregorianCalendar(2018, 5, 30).getTime()); Product p = new Product(); p.setId(new Long(1)); Customer c = new Customer(); c.setId(new Long(1)); OrderItem i = new OrderItem(); i.setPrice(new BigDecimal(30)); i.setQuantity(3); i.setProduct(p); List<OrderItem> items = new ArrayList<OrderItem>(); items.add(item); List<OrderItem> detaileditems = new ArrayList<OrderItem>(); detaileditems.add((OrderItem)SerializationUtils.clone(item)); o.setItems(items); o.setCustomer(c); Mockito.when(orderRepository.getOrderById(new Long(1))) .thenReturn(o); Mockito.when(customerRepository.getCustomerById(new Long(1))) .thenReturn((Customer)SerializationUtils.clone(customer)); Mockito.when(inventoryRepository.getProductDetails(items)) .thenReturn(detaileditems); Order found = ordersService.getById(new Long(1)); assertThat(found).isEqualTo(order); } |
### Question:
OrdersController { @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public Order getById(@PathVariable("id") Long id) { Order o; Span span = tracer.buildSpan("getById").start(); try{ log.debug("Entering OrderController.getById()"); o = orderService.getById(id); if (o == null) { throw new ResourceNotFoundException("Requested order doesn't exist"); } log.debug("Returning element: " + o); } finally { span.finish(); } return o; } @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) Order getById(@PathVariable("id") Long id); }### Answer:
@Test public void getByIdExisting() { Mockito.when(service.getById(new Long (1))) .thenReturn(order); when().get(new Long(1).toString()) .then() .statusCode(200) .body("id", is(1)) .body("date", is("30-05-2018")) .body("customer.id", is(1)) .body("customer.name", is("Test Customer")) .body("customer.surname", is("Test Customer")) .body("customer.username", is("testcustomer")) .body("customer.zipCode", is("28080")) .body("customer.city", is("Madrid")) .body("customer.country", is("Spain")) .body("customer.address", is("Test Address")) .body("items.size()", is(1)) .body("items.get(0).quantity", is(3)) .body("items.get(0).price", is(30)) .body("items.get(0).product.id", is(1)) .body("items.get(0).product.name", is("Test Product")) .body("items.get(0).product.description", is("Test Description")); }
@Test public void getByIdNonExisting() { Mockito.when(service.getById(new Long (1))) .thenReturn(null); when().get(new Long(1).toString()) .then() .statusCode(404); } |
### Question:
CustomerRepository { @HystrixCommand(commandKey = "Customers", fallbackMethod = "getFallbackCustomer", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) public Customer getCustomerById(Long id) { Span span = tracer.buildSpan("getCustomerById").start(); log.debug("Entering OrdersService.getCustomerById()"); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(customersServiceURL) .pathSegment( "{customer}"); Customer c = restTemplate.getForObject( builder.buildAndExpand(id).toUriString(), Customer.class); if (c == null) { throw new RuntimeException(); } log.debug(c.toString()); span.finish(); return c; } @HystrixCommand(commandKey = "Customers", fallbackMethod = "getFallbackCustomer", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) Customer getCustomerById(Long id); Customer getFallbackCustomer(Long id, Throwable e); }### Answer:
@Test public void getCustomerByIdExistingTest() { Mockito.when(restTemplate.getForObject("http: .thenReturn((Customer)SerializationUtils.clone(customer)); Customer found = repository.getCustomerById(new Long(1)); assertThat(found).isEqualTo(customer); }
@Test(expected = RuntimeException.class) public void getCustomerByIdNonExistingTest() { Mockito.when(restTemplate.getForObject("http: .thenReturn(null); repository.getCustomerById(new Long(1)); } |
### Question:
CustomerRepository { public Customer getFallbackCustomer(Long id, Throwable e) { log.warn("Failed to obtain Customer, " + e.getMessage() + " for customer with id " + id); Customer c = new Customer(); c.setId(id); c.setUsername("Unknown"); c.setName("Unknown"); c.setSurname("Unknown"); c.setAddress("Unknown"); c.setCity("Unknown"); c.setCountry("Unknown"); c.setZipCode("Unknown"); return c; } @HystrixCommand(commandKey = "Customers", fallbackMethod = "getFallbackCustomer", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) Customer getCustomerById(Long id); Customer getFallbackCustomer(Long id, Throwable e); }### Answer:
@Test public void getFallbackCustomerTest() { Customer c = new Customer(); c.setId(new Long(1)); c.setUsername("Unknown"); c.setName("Unknown"); c.setSurname("Unknown"); c.setAddress("Unknown"); c.setCity("Unknown"); c.setCountry("Unknown"); c.setZipCode("Unknown"); Customer found = repository.getFallbackCustomer(new Long(1), new Exception()); assertThat(found).isEqualTo(c); } |
### Question:
OrderRepository { @HystrixCommand(commandKey = "Orders", fallbackMethod = "getFallbackOrder", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) public Order getOrderById(Long id) { Span span = tracer.buildSpan("getOrderById").start(); log.debug("Entering OrderRepository.getOrderById()"); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(ordersServiceURL) .pathSegment( "{order}"); Order o = restTemplate.getForObject( builder.buildAndExpand(id).toUriString(), Order.class); if (o == null) log.debug("Obtained null order"); else log.debug(o.toString()); span.finish(); return o; } @HystrixCommand(commandKey = "Orders", fallbackMethod = "getFallbackOrder", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) Order getOrderById(Long id); Order getFallbackOrder(Long id, Throwable e); }### Answer:
@Test public void getOrderByIdExistingTest() { Mockito.when(restTemplate.getForObject("http: .thenReturn((Order)SerializationUtils.clone(order)); Order found = repository.getOrderById(new Long(1)); assertThat(found).isEqualTo(order); }
@Test public void getOrderByIdNonExistingTest() { Mockito.when(restTemplate.getForObject("http: .thenReturn(null); Order found = repository.getOrderById(new Long(1)); assertThat(found).isNull(); } |
### Question:
OrderRepository { public Order getFallbackOrder(Long id, Throwable e) { log.warn("Failed to obtain Order, " + e.getMessage() + " for order with id " + id); return null; } @HystrixCommand(commandKey = "Orders", fallbackMethod = "getFallbackOrder", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000") }) Order getOrderById(Long id); Order getFallbackOrder(Long id, Throwable e); }### Answer:
@Test public void getFallbackCustomerTest() { assertThat(repository.getFallbackOrder(new Long(1), new Exception())).isNull(); } |
### Question:
CustomerService implements ICustomerService { public Customer findById(Long id) { Span childSpan = tracer.buildSpan("findById").start(); childSpan.setTag("layer", "Service"); logger.debug("Entering CustomerService.findById()"); Customer c = repository.findById(id); childSpan.finish(); return c; } Customer findById(Long id); }### Answer:
@Test public void findByIdExistingTest() { Customer c = service.findById(1L); assertThat(c.getId(), equalTo(1L)); assertThat(c.getUsername(), equalTo("mockusername")); assertThat(c.getName(), equalTo("Test User Mock")); assertThat(c.getSurname(), equalTo("Test Surname Mock")); assertThat(c.getAddress(), equalTo("Test Address Mock")); assertThat(c.getZipCode(), equalTo("MOCKZIP")); assertThat(c.getCity(), equalTo("Test City Mock")); assertThat(c.getCountry(), equalTo("Test Country Mock")); }
@Test public void findByIdNonExistingTest() { Customer c = service.findById(2L); assertThat(c, is(nullValue())); } |
### Question:
OrderService { public Order findById(Long id) { Span span = tracer.buildSpan("findById").start(); log.debug("Entering OrderService.findById()"); Optional<Order> o = repository.findById(id); try { Order order = o.get(); order.getItems().size(); log.debug("Returning element: " + o); return order; } catch (NoSuchElementException nsee) { log.debug("No element found, returning null"); return null; } finally { span.finish(); } } Order findById(Long id); }### Answer:
@Test public void findByIdExistingTest() { OrderItem item = new OrderItem(); item.setId(new Long(1)); item.setPrice(new BigDecimal(30)); item.setProductUID(new Long (1)); item.setQuantity(3); List<OrderItem> items = new ArrayList<OrderItem>(); items.add(item); Order o = new Order(); o.setId(new Long(1)); o.setCustomerUID(new Long(1)); o.setDate(new GregorianCalendar(2018, 5, 30).getTime()); o.setItems(items); Order shallowOrder= new Order(); shallowOrder.setId(new Long(1)); item.setOrder(shallowOrder); Mockito.when(repository.findById(new Long (1))) .thenReturn(Optional.of(SerializationUtils.clone(o))); Order found = service.findById(new Long(1)); assertThat(found).isEqualTo(o); }
@Test public void findByIdNonExistingTest() { Mockito.when(repository.findById(new Long (1))) .thenReturn(Optional.empty()); Order found = service.findById(new Long(1)); assertThat(found).isNull(); } |
### Question:
Order implements Serializable { public BigDecimal getTotalAmmount() { if (items != null) { Function<OrderItem, BigDecimal> totalMapper = item -> item.getPrice().multiply(new BigDecimal(item.getQuantity())); return items.stream() .map(totalMapper) .reduce(BigDecimal.ZERO, BigDecimal::add); } else { return new BigDecimal(0); } } BigDecimal getTotalAmmount(); @JsonProperty("customer") Customer getCustomer(); @JsonProperty("customerUID") @JsonDeserialize(using = CustomerDeserializer.class) void setCustomer(Customer customer); }### Answer:
@Test public void getTotalAmmountItemsNotNullTest() { Order o = new Order(); OrderItem i1 = new OrderItem(); i1.setPrice(new BigDecimal(20)); i1.setQuantity(1); OrderItem i2 = new OrderItem(); i2.setPrice(new BigDecimal(30)); i2.setQuantity(2); List<OrderItem> items = new ArrayList<OrderItem>(); items.add(i1); items.add(i2); o.setItems(items); assertThat(o.getTotalAmmount()).isEqualTo(new BigDecimal(80)); }
@Test public void getTotalAmmountItemsNullTest() { Order o = new Order(); assertThat(o.getTotalAmmount()).isEqualTo(new BigDecimal(0)); }
@Test public void getTotalAmmountItemsEmptyTest() { Order o = new Order(); List<OrderItem> items = new ArrayList<OrderItem>(); o.setItems(items); assertThat(o.getTotalAmmount()).isEqualTo(new BigDecimal(0)); } |
### Question:
BatchPredictorExample implements Predictor<Integer, Float> { @Override public CompletionStage<List<Prediction<Integer, Float>>> predict( final ScheduledExecutorService scheduler, final Duration timeout, final Integer... input) { return predictorBuilder.predictor().predict(scheduler, timeout, input); } BatchPredictorExample(); @Override CompletionStage<List<Prediction<Integer, Float>>> predict(
final ScheduledExecutorService scheduler, final Duration timeout, final Integer... input); }### Answer:
@SuppressWarnings("unchecked") @Test public void testCustomMetrics() throws InterruptedException, ExecutionException, TimeoutException { final BatchPredictorExample example = new BatchPredictorExample(); final Integer[] batch = new Integer[] {3, 1, -4, -42, 42, -10}; final List<Float> predictions = example .predict(batch) .toCompletableFuture() .join() .stream() .map(Prediction::value) .collect(Collectors.toList()); final List<Float> expected = Arrays.stream(batch).map(v -> (float) v / 10 * 2).collect(Collectors.toList()); assertThat(predictions, is(expected)); } |
### Question:
CustomMetricsExample implements Predictor<Integer, Float> { @Override public CompletionStage<List<Prediction<Integer, Float>>> predict( final ScheduledExecutorService scheduler, final Duration timeout, final Integer... input) { return predictorBuilder.predictor().predict(scheduler, timeout, input); } CustomMetricsExample(final SemanticMetricRegistry metricRegistry, final MetricId metricId); @Override CompletionStage<List<Prediction<Integer, Float>>> predict(
final ScheduledExecutorService scheduler, final Duration timeout, final Integer... input); }### Answer:
@Test public void testCustomMetrics() throws InterruptedException, ExecutionException, TimeoutException { final SemanticMetricRegistry registry = new SemanticMetricRegistry(); final MetricId metricId = MetricId.build().tagged("service", "my-application"); final CustomMetricsExample example = new CustomMetricsExample(registry, metricId); example.predict(3, 1, -4, -42, 42, -10).toCompletableFuture().join(); registry.getCounters().values().forEach(counter -> Assert.assertEquals(3, counter.getCount())); } |
### Question:
BoundedItemIcon extends BoundedItem implements IBoundedItemIcon { @Override public Icon getIcon() { return icon; } BoundedItemIcon(String label, Coord2d position, Icon icon); BoundedItemIcon(Pair<String,? extends Icon> labelIcon); BoundedItemIcon(String label, Icon icon); BoundedItemIcon(Object o, Icon icon); BoundedItemIcon(Object o, Icon icon, float margin); BoundedItemIcon(Object o, Pair<String,? extends Icon> labelIcon); BoundedItemIcon(Object o, String label, Icon icon); BoundedItemIcon(Object o, String label, Icon icon, float margin); @Override void setIcon(Icon icon); @Override void setIcon(Icon icon, float margin); @Override Icon getIcon(); @Override Coord2d getScale(); @Override void setScale(Coord2d scale); @Override IBoundedItem clone(); }### Answer:
@Test public void testIconItemSize(){ Icon icon = IconSet.ROUTER; int expectedWidth = 151; int expectedHeight = 89; Assert.assertEquals(icon.getIconWidth(), expectedWidth); Assert.assertEquals(icon.getIconHeight(), expectedHeight); IBoundedItemIcon item = new BoundedItemIcon("node", icon); Assert.assertTrue(item.getIcon()==icon); Assert.assertEquals(expectedWidth, item.getRawRectangleBounds().width, 0.001); float expectedRadius = (float)(Math.hypot(expectedWidth+BoundedItemIcon.DEFAULT_SLOT_HEIGHT*2, expectedHeight+BoundedItemIcon.DEFAULT_SLOT_HEIGHT*2)/2); Assert.assertTrue(item.getRadialBounds(Math.PI/2)<=expectedRadius); } |
### Question:
MaxStepCriteria implements IBreakCriteria { @Override public boolean shouldBreak(IHierarchicalNodeLayout layout) { if(layout.getDelegate()==null) return false; if(layout.getDelegate().getCounter()>maxSteps) return true; else return false; } MaxStepCriteria(); MaxStepCriteria(int maxSteps); @Override boolean shouldBreak(IHierarchicalNodeLayout layout); @Override void onBreak(); int getMaxSteps(); }### Answer:
@Test public void testMaxSteps(){ IHierarchicalNodeLayout mockLayout = mockLayoutCounter(3); MaxStepCriteria c = new MaxStepCriteria(2); Assert.assertFalse(c.shouldBreak(mockLayout)); Assert.assertFalse(c.shouldBreak(mockLayout)); Assert.assertFalse(c.shouldBreak(mockLayout)); Assert.assertTrue(c.shouldBreak(mockLayout)); } |
### Question:
TimeMonitor implements ITimeMonitor { public TimeMonitor(Object o) { this(o, o.getClass().getSimpleName(), false); } TimeMonitor(Object o); TimeMonitor(String name); TimeMonitor(Object monitored, String name, boolean enabled); @Override void startMonitor(); @Override void stopMonitor(); @Override List<Pair<Date,Double>> getMeasurements(); @Override Unit getUnit(); @Override String getName(); @Override boolean isEnabled(); @Override void enable(boolean status); @Override Object getMonitored(); @Override Double getMean(); @Override int getSize(); }### Answer:
@Test public void testTimeMonitor() throws InterruptedException { TimeMonitor m = new TimeMonitor("test-monitor"); assertInitializedDisabledWithName(m); double allowedDifferenceBetweenPauseAndMeasure = 0.01; assertMonitorMeasureActualPause(m, allowedDifferenceBetweenPauseAndMeasure); assertDontAddMeasureWhenDisabled(m); assertAddMeasureWhenEnabled(m); } |
### Question:
AbstractLinkProvider implements Serializable { public static AbstractLinkProvider fromParams(final AbstractAllParams<?> all) { switch (all.getVCat().getLinks()) { case Graph: return new VCatLinkProvider(all); case Wiki: return new WikiLinkProvider(all); default: return new EmptyLinkProvider(); } } static AbstractLinkProvider fromParams(final AbstractAllParams<?> all); void addLinkToNode(final Node node, final String title); abstract String provideLink(final String title); }### Answer:
@Test public void testFromParamsWiki() { TestAllParams params = new TestAllParams(); Metadata metadata = new Metadata("articlepath", "server", Collections.emptyMap(), Collections.emptyMap()); params.setMetadata(metadata); params.getVCat().setLinks(Links.Wiki); AbstractLinkProvider instance = AbstractLinkProvider.fromParams(params); assertTrue(instance instanceof WikiLinkProvider); }
@Test public void testFromParamsDefault() { TestAllParams params = new TestAllParams(); params.getVCat().setLinks(Links.None); AbstractLinkProvider instance = AbstractLinkProvider.fromParams(params); assertTrue(instance instanceof EmptyLinkProvider); }
@Test public void testFromParamsGraph() { TestAllParams params = new TestAllParams(); params.getVCat().setLinks(Links.Graph); AbstractLinkProvider instance = AbstractLinkProvider.fromParams(params); assertTrue(instance instanceof VCatLinkProvider); } |
### Question:
EmptyLinkProvider extends AbstractLinkProvider { @Override public String provideLink(final String title) { return null; } @Override String provideLink(final String title); }### Answer:
@Test public void testProviceLink() { assertNull(underTest.provideLink("test")); } |
### Question:
HashHelper { public static String sha256Hex(Serializable object) { if (object instanceof String) { return DigestUtils.sha256Hex(((String) object).getBytes(StandardCharsets.UTF_8)); } else { return DigestUtils.sha256Hex(SerializationUtils.serialize(object)); } } private HashHelper(); static String sha256Hex(Serializable object); }### Answer:
@Test public void testSha256Hex() { Serializable testObject1 = new TestClass(); Serializable testObject2 = new TestClass(); String result1 = HashHelper.sha256Hex(testObject1); String result2 = HashHelper.sha256Hex(testObject2); assertEquals(result2, result1); }
@Test public void testSha256HexString() { String testString = "abcäöü"; String expectedResult = DigestUtils.sha256Hex(testString.getBytes(StandardCharsets.UTF_8)); String result = HashHelper.sha256Hex(testString); assertEquals(expectedResult, result); } |
### Question:
WikiLinkProvider extends AbstractLinkProvider { @Override public String provideLink(final String title) { return pattern.replace("$1", escapeMediawikiTitleForUrl(title)); } WikiLinkProvider(final AbstractAllParams<?> all); @Override String provideLink(final String title); }### Answer:
@Test public void testProvideLink() { TestAllParams params = new TestAllParams(); Metadata metadata = new Metadata("articlepath/$1", "https: Collections.emptyMap()); params.setMetadata(metadata); WikiLinkProvider underTest = new WikiLinkProvider(params); assertEquals( "https: underTest.provideLink("abc:Äöü ßメインページ")); }
@Test public void testProvideLinkProtocolRelative() { TestAllParams params = new TestAllParams(); Metadata metadata = new Metadata("articlepath/$1", " params.setMetadata(metadata); WikiLinkProvider underTest = new WikiLinkProvider(params); assertEquals( "http: underTest.provideLink("abc:Äöü ßメインページ")); } |
### Question:
VCatLinkProvider extends AbstractLinkProvider { public String getRenderUrl() { return this.renderUrl; } protected VCatLinkProvider(final AbstractAllParams<?> all, final String renderUrl); VCatLinkProvider(final AbstractAllParams<?> all); String getRenderUrl(); @Override String provideLink(final String title); }### Answer:
@Test public void testGetRenderUrl() { String renderUrl = "https: TestAllParams params = new TestAllParams(); VCatLinkProvider underTest = new VCatLinkProvider(params, renderUrl); assertEquals(renderUrl, underTest.getRenderUrl()); } |
### Question:
MetadataFileCache extends AbstractFileCache<String> implements IMetadataCache { @Override public synchronized Metadata getMetadata(IWiki wiki) throws CacheException { final String key = wiki.getApiUrl(); if (this.containsKey(key)) { Object metadataObject = null; try { metadataObject = SerializationUtils.deserialize(this.get(key)); if (metadataObject == null) { return null; } else if (metadataObject instanceof Metadata) { return (Metadata) metadataObject; } else { this.remove(key); String message = Messages.getString("MetadataFileCache.Error.Deserialize"); LOGGER.error(message); throw new CacheException(message); } } catch (SerializationException e) { this.remove(key); String message = Messages.getString("MetadataFileCache.Error.Deserialize"); LOGGER.warn(message, e); throw new CacheException(message, e); } } else { return null; } } MetadataFileCache(final File cacheDirectory, final int maxAgeInSeconds); @Override synchronized Metadata getMetadata(IWiki wiki); @Override synchronized void put(IWiki wiki, Metadata metadata); }### Answer:
@Test public void testGetMetadataNull() throws CacheException { TestWiki wiki = new TestWiki(); assertNull(underTest.getMetadata(wiki)); } |
### Question:
AbstractFileCache { public synchronized void clear() { int clearedFiles = 0; for (File file : this.getAllFiles()) { if (file.delete()) { clearedFiles++; } else { LOGGER.warn(String.format(Messages.getString("AbstractFileCache.Warn.CouldNotDeleteClearing"), file.getAbsolutePath())); } } if (clearedFiles > 0) { LOGGER.info(String.format(Messages.getString("AbstractFileCache.Info.Cleared"), clearedFiles)); } } protected AbstractFileCache(File cacheDirectory, String prefix, String suffix, final int maxAgeInSeconds); synchronized void clear(); synchronized boolean containsKey(K key); synchronized byte[] get(K key); synchronized InputStream getAsInputStream(K key); File getCacheDirectory(); File getCacheFile(K key); synchronized void purge(); synchronized void put(K key, byte[] value); synchronized void putFile(K key, File file, boolean move); synchronized void remove(K key); }### Answer:
@Test public void testClear() throws CacheException { byte[] testBytes = "test".getBytes(StandardCharsets.US_ASCII); underTest.put("test", testBytes); underTest.clear(); byte[] resultBytes = underTest.get("test"); assertNull(resultBytes); } |
### Question:
AbstractFileCache { public synchronized void remove(K key) { this.getCacheFile(key).delete(); } protected AbstractFileCache(File cacheDirectory, String prefix, String suffix, final int maxAgeInSeconds); synchronized void clear(); synchronized boolean containsKey(K key); synchronized byte[] get(K key); synchronized InputStream getAsInputStream(K key); File getCacheDirectory(); File getCacheFile(K key); synchronized void purge(); synchronized void put(K key, byte[] value); synchronized void putFile(K key, File file, boolean move); synchronized void remove(K key); }### Answer:
@Test public void testRemove() throws CacheException { byte[] testBytes = "test".getBytes(StandardCharsets.US_ASCII); underTest.put("test", testBytes); underTest.put("test2", testBytes); underTest.remove("test"); assertTrue(underTest.containsKey("test2")); } |
### Question:
AbstractFileCache { public synchronized void purge() { long lastModifiedThreshold = System.currentTimeMillis() - (1000L * this.maxAgeInSeconds); int purgedFiles = 0; for (File file : this.getAllFiles()) { if (file.lastModified() < lastModifiedThreshold) { if (file.delete()) { purgedFiles++; } else { LOGGER.warn(String.format(Messages.getString("AbstractFileCache.Warn.CouldNotDeletePurging"), file.getAbsolutePath())); } } } if (purgedFiles > 0) { LOGGER.info(String.format(Messages.getString("AbstractFileCache.Info.Purged"), purgedFiles)); } } protected AbstractFileCache(File cacheDirectory, String prefix, String suffix, final int maxAgeInSeconds); synchronized void clear(); synchronized boolean containsKey(K key); synchronized byte[] get(K key); synchronized InputStream getAsInputStream(K key); File getCacheDirectory(); File getCacheFile(K key); synchronized void purge(); synchronized void put(K key, byte[] value); synchronized void putFile(K key, File file, boolean move); synchronized void remove(K key); }### Answer:
@Test public void testPurge() throws CacheException, InterruptedException { byte[] testBytes = "test".getBytes(StandardCharsets.US_ASCII); underTest.maxAgeInSeconds = 1; underTest.put("test1", testBytes); underTest.put("test2", testBytes); underTest.purge(); assertTrue(underTest.containsKey("test1")); assertTrue(underTest.containsKey("test2")); Thread.sleep(1500); underTest.put("test3", testBytes); underTest.purge(); assertFalse(underTest.containsKey("test1")); assertFalse(underTest.containsKey("test2")); assertTrue(underTest.containsKey("test3")); } |
### Question:
AbstractFileCache { public synchronized boolean containsKey(K key) { return this.getCacheFile(key).exists(); } protected AbstractFileCache(File cacheDirectory, String prefix, String suffix, final int maxAgeInSeconds); synchronized void clear(); synchronized boolean containsKey(K key); synchronized byte[] get(K key); synchronized InputStream getAsInputStream(K key); File getCacheDirectory(); File getCacheFile(K key); synchronized void purge(); synchronized void put(K key, byte[] value); synchronized void putFile(K key, File file, boolean move); synchronized void remove(K key); }### Answer:
@Test public void testContainsKey() throws CacheException { byte[] testBytes = "test".getBytes(StandardCharsets.US_ASCII); underTest.put("test", testBytes); assertTrue(underTest.containsKey("test")); } |
### Question:
AbstractFileCache { public synchronized InputStream getAsInputStream(K key) throws CacheException { if (this.containsKey(key)) { try { return new FileInputStream(this.getCacheFile(key)); } catch (FileNotFoundException e) { String message = Messages.getString("AbstractFileCache.Exception.FileNotFoundShouldNotHappen"); LOGGER.error(message, e); throw new CacheException(message, e); } } else { return null; } } protected AbstractFileCache(File cacheDirectory, String prefix, String suffix, final int maxAgeInSeconds); synchronized void clear(); synchronized boolean containsKey(K key); synchronized byte[] get(K key); synchronized InputStream getAsInputStream(K key); File getCacheDirectory(); File getCacheFile(K key); synchronized void purge(); synchronized void put(K key, byte[] value); synchronized void putFile(K key, File file, boolean move); synchronized void remove(K key); }### Answer:
@Test public void testGetAsInputStream() throws CacheException, IOException { byte[] testBytes = "test".getBytes(StandardCharsets.US_ASCII); underTest.put("test", testBytes); try (InputStream input = underTest.getAsInputStream("test")) { for (int i = 0; i < testBytes.length; i++) { assertEquals(input.read(), testBytes[i]); } assertEquals(-1, input.read()); } }
@Test public void testGetAsInputStreamNull() throws CacheException, IOException { assertNull(underTest.getAsInputStream("test")); } |
### Question:
AbstractFileCache { public synchronized void putFile(K key, File file, boolean move) throws CacheException { File cacheFile = this.getCacheFile(key); cacheFile.delete(); if (move) { try { FileUtils.moveFile(file, cacheFile); } catch (IOException e) { throw new CacheException(Messages.getString("AbstractFileCache.Exception.MoveFailed"), e); } } else { try { FileUtils.copyFile(file, cacheFile); } catch (IOException e) { throw new CacheException(Messages.getString("AbstractFileCache.Exception.MoveFailed"), e); } } } protected AbstractFileCache(File cacheDirectory, String prefix, String suffix, final int maxAgeInSeconds); synchronized void clear(); synchronized boolean containsKey(K key); synchronized byte[] get(K key); synchronized InputStream getAsInputStream(K key); File getCacheDirectory(); File getCacheFile(K key); synchronized void purge(); synchronized void put(K key, byte[] value); synchronized void putFile(K key, File file, boolean move); synchronized void remove(K key); }### Answer:
@Test public void testPutFile() throws CacheException, IOException { byte[] testBytes = "test".getBytes(StandardCharsets.US_ASCII); Path tempFile = null; try { tempFile = Files.createTempFile("AbstractFileCacheTest-testPutFileMove", ""); try (OutputStream outputStream = Files.newOutputStream(tempFile)) { outputStream.write(testBytes); } underTest.putFile("test", tempFile.toFile(), false); byte[] resultBytes = underTest.get("test"); assertTrue(Files.exists(tempFile)); assertArrayEquals(testBytes, resultBytes); } finally { if (tempFile != null) { Files.deleteIfExists(tempFile); } } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.