src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
PathSet implements Set<Path> { public boolean containsAncestor(Path path) { for (Path p : this) { if (p.isAncestorOf(path)) { return true; } } return false; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); } | @Test public void containsAncestor() { assertTrue(data.remove(new Path("/"))); assertTrue(data.containsAncestor(new Path("/foo/baz"))); assertTrue(data.containsAncestor(new Path("/bar/baz"))); assertTrue(!data.containsAncestor(new Path("/foo"))); assertTrue(!data.containsAncestor(new Path("/baz"))); } |
Path implements Iterable<String>, Serializable { public boolean isDescendantOf(Path other) { if (other.isRoot()) { if (isRoot()) { return false; } else if (isAbsolute()) { return true; } else { return false; } } else { return path.startsWith(other.path + SEPARATOR) && path.length() > other.path.length(); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void isDescendantOf() { assertDescendant(new Path("/"), new Path("/foo")); assertDescendant(new Path("/"), new Path("/foo/bar")); assertDescendant(new Path("/foo"), new Path("/foo/bar")); assertNotDescendant(new Path("/foo"), new Path("/bar/foo")); assertNotDescendant(new Path("/foo"), new Path("/")); assertNotDescendant(new Path("/"), new Path("relative")); assertDescendant(new Path("foo/bar"), new Path("foo/bar/baz")); assertNotDescendant(new Path("foo/bar"), new Path("bar")); assertNotDescendant(new Path("/"), new Path("/")); assertNotDescendant(new Path("/foo"), new Path("/foo")); } |
Path implements Iterable<String>, Serializable { public boolean isRoot() { return path.equals(SEPARATOR); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void isRoot() { assertTrue(new Path("/").isRoot()); assertTrue(!new Path("foo").isRoot()); assertTrue(!new Path("/foo").isRoot()); } |
Path implements Iterable<String>, Serializable { public Iterator<String> iterator() { return new Iterator<String>() { int idx = 0; public boolean hasNext() { return idx < size(); } public String next() { return part(idx++); } public void remove() { throw new UnsupportedOperationException("Path parts iterator is read only"); } }; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test @SuppressWarnings("unused") public void iterator() { Path path = new Path("/foo/bar/baz"); Set<String> parts = new HashSet<String>(Arrays.asList(new String[]{"foo", "bar", "baz"})); for (String part : path) { assertTrue(parts.remove(part)); } assertTrue(parts.isEmpty()); for (String part : new Path("/")) { fail(); } } |
Path implements Iterable<String>, Serializable { public Path parent() { if (isRoot()) { return null; } else { return new Path(path + "/.."); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void parent() { assertTrue(new Path("/").parent() == null); assertEquals(new Path("/foo").parent(), new Path("/")); assertEquals(new Path("/foo/bar").parent(), new Path("/foo")); assertEquals(new Path("foo").parent(), new Path(".")); assertEquals(new Path("foo/bar").parent(), new Path("foo")); assertEquals(new Path(".").parent(), new Path("..")); assertEquals(new Path("../foo").parent(), new Path("..")); assertEquals(new Path("..").parent(), new Path("../..")); } |
Path implements Iterable<String>, Serializable { public String part(int index) { if (index < 0) { throw new IndexOutOfBoundsException(); } int start = isAbsolute() ? 1 : 0; for (int i = 0; i < index; i++) { start = path.indexOf(SEPARATOR, start); if (start < 0) { throw new IndexOutOfBoundsException(); } start++; } int end = path.indexOf(SEPARATOR, start); if (end < 0) { end = path.length(); } return path.substring(start, end); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void part() { Path path = new Path("/foo/bar/baz"); assertEquals("foo", path.part(0)); assertEquals("bar", path.part(1)); assertEquals("baz", path.part(2)); path = new Path("foo/bar/baz"); assertEquals("foo", path.part(0)); assertEquals("bar", path.part(1)); assertEquals("baz", path.part(2)); } |
Path implements Iterable<String>, Serializable { public int size() { if (isRoot()) { return 0; } int size = 0; int pos = 0; while (pos >= 0) { size++; pos = path.indexOf(SEPARATOR, pos + 1); } return size; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void size() { assertEquals(new Path("/").size(), 0); assertEquals(new Path("/foo").size(), 1); assertEquals(new Path("/foo/bar").size(), 2); assertEquals(new Path("/foo/bar/baz").size(), 3); } |
Path implements Iterable<String>, Serializable { public Path subpath(int idx) { if (idx <= 0) { throw new IndexOutOfBoundsException(); } final int size = size(); final boolean abs = isAbsolute(); int chunks = (abs) ? size + 1 : size; if (idx > chunks) { throw new IndexOutOfBoundsException(); } if (idx == chunks) { return this; } int iterations = ((abs) ? idx - 1 : idx); int end = 1; for (int i = 0; i < iterations; i++) { end = path.indexOf(SEPARATOR, end + 1); } if (end == 0) { return new Path("/"); } String newPath = path.substring(0, end); return new Path(newPath); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void subpath() { Path path = new Path("/foo/bar/baz"); assertEquals(new Path("/foo/bar/baz"), path.subpath(4)); assertEquals(new Path("/foo/bar"), path.subpath(3)); assertEquals(new Path("/foo"), path.subpath(2)); assertEquals(new Path("/"), path.subpath(1)); try { path.subpath(5); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(0); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(-1); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } path = new Path("foo/bar/baz"); assertEquals(new Path("foo/bar/baz"), path.subpath(3)); assertEquals(new Path("foo/bar"), path.subpath(2)); assertEquals(new Path("foo"), path.subpath(1)); try { path.subpath(4); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(0); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } try { path.subpath(-1); fail("expect index out of bounds exception"); } catch (IndexOutOfBoundsException e) { } } |
Path implements Iterable<String>, Serializable { public Path toRelative(Path ancestor) { if (isRoot()) { throw new IllegalStateException("Cannot make root path relative"); } if (!isDescendantOf(ancestor)) { throw new IllegalArgumentException("Cannot create relative path because this path: " + this + " is not descendant of ancestor argument: " + ancestor); } Path fragment = new Path(path.substring(ancestor.path.length()), false); if (fragment.isAbsolute()) { fragment = fragment.toRelative(new Path("/")); } return fragment; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void toRelative() { try { new Path("/").toRelative(new Path("/")); fail(); } catch (IllegalStateException e) { } try { new Path("/foo/bar").toRelative(new Path("/bar")); fail(); } catch (IllegalArgumentException e) { } assertEquals(new Path("foo"), new Path("/foo").toRelative(new Path("/"))); assertEquals(new Path("bar"), new Path("/foo/bar").toRelative(new Path("/foo"))); assertEquals(new Path("bar"), new Path("foo/bar").toRelative(new Path("foo"))); } |
PathSet implements Set<Path> { public boolean containsParent(Path path) { for (Path p : this) { if (p.isParentOf(path)) { return true; } } return false; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); } | @Test public void containsParent() { assertTrue(!data.containsParent(new Path("/"))); assertTrue(data.containsParent(new Path("/foo"))); assertTrue(data.containsParent(new Path("/foo/baz"))); assertTrue(data.containsParent(new Path("/foo/bar/baz"))); assertTrue(data.containsParent(new Path("/foo/bar/baz/boz"))); assertTrue(!data.containsParent(new Path("/foo/baz/bar"))); } |
PathSet implements Set<Path> { public void removeDescendants(Path path) { Iterator<Path> i = iterator(); while (i.hasNext()) { Path p = i.next(); if (p.isDescendantOf(path)) { i.remove(); } } } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); } | @Test public void removeDescendants() { data.removeDescendants(new Path("/foo")); assertTrue(data.size() == 3); assertTrue(data.contains(new Path("/"))); assertTrue(data.contains(new Path("/bar"))); assertTrue(data.contains(new Path("/foo"))); data.removeDescendants(new Path("/")); assertTrue(data.size() == 1); assertTrue(data.contains(new Path("/"))); } |
PathSet implements Set<Path> { public boolean removeWithDescendants(Path path) { boolean ret = remove(path); removeDescendants(path); return ret; } PathSet(); PathSet(Set<Path> delegate); boolean equals(Object o); int hashCode(); int size(); boolean isEmpty(); boolean contains(Object o); Object[] toArray(); T[] toArray(T[] a); boolean add(Path o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends Path> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c); void clear(); boolean containsAncestor(Path path); boolean containsParent(Path path); boolean removeWithDescendants(Path path); boolean remove(Object o); void removeDescendants(Path path); Iterator<Path> iterator(); } | @Test public void removeWithDescendants() { data.removeWithDescendants(new Path("/foo")); assertTrue(data.size() == 2); assertTrue(data.contains(new Path("/"))); assertTrue(data.contains(new Path("/bar"))); data.removeWithDescendants(new Path("/")); assertTrue(data.isEmpty()); } |
Path implements Iterable<String>, Serializable { public Path append(Path relative) { if (relative == null) { throw new IllegalArgumentException("Argument 'relative' cannot be null"); } if (relative.isAbsolute()) { throw new IllegalArgumentException("Cannot append an absolute path"); } StringBuilder appended = new StringBuilder(path.length() + 1 + relative.path.length()); appended.append(path); if (!path.endsWith(SEPARATOR)) { appended.append("/"); } appended.append(relative.path); return new Path(appended.toString()); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void append() { assertEquals(new Path("/").append(new Path("foo")), new Path("/foo")); assertEquals(new Path("/").append(new Path("foo/bar")), new Path("/foo/bar")); assertEquals(new Path("/foo").append(new Path("bar")), new Path("/foo/bar")); assertEquals(new Path("/foo").append(new Path("../bar")), new Path("/bar")); assertEquals(new Path("/foo").append(new Path("../../bar")), new Path("/bar")); assertEquals(new Path("foo").append(new Path("bar")), new Path("foo/bar")); assertEquals(new Path("foo").append(new Path("../bar")), new Path("bar")); assertEquals(new Path("foo").append(new Path("../../bar")), new Path("../bar")); try { new Path("/foo").append(new Path("/")); fail(); } catch (IllegalArgumentException e) { } } |
Path implements Iterable<String>, Serializable { @Override public String toString() { return path; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void construction() { assertEquals(new Path("/").toString(), "/"); assertEquals(new Path("/foo").toString(), "/foo"); assertEquals(new Path("/foo/").toString(), "/foo"); assertEquals(new Path("/foo/bar").toString(), "/foo/bar"); assertEquals(new Path("/foo/bar/").toString(), "/foo/bar"); assertEquals(new Path("foo").toString(), "foo"); assertEquals(new Path("foo/").toString(), "foo"); assertEquals(new Path("foo/bar").toString(), "foo/bar"); assertEquals(new Path("foo/bar/").toString(), "foo/bar"); try { new Path(""); fail(); } catch (IllegalArgumentException e) { } try { new Path(null); fail(); } catch (IllegalArgumentException e) { } } |
Path implements Iterable<String>, Serializable { public String getName() { if (path.equals(SEPARATOR)) { return path; } else { int last = path.lastIndexOf(SEPARATOR); return path.substring(last + 1); } } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void getName() { assertEquals(new Path("/").getName(), "/"); assertEquals(new Path("/foo").getName(), "foo"); assertEquals(new Path("/foo/bar").getName(), "bar"); assertEquals(new Path("foo").getName(), "foo"); assertEquals(new Path("foo/bar").getName(), "bar"); } |
Path implements Iterable<String>, Serializable { public boolean isAbsolute() { return path.startsWith("/"); } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void isAbsolute() { assertTrue(new Path("/").isAbsolute()); assertTrue(new Path("/foo").isAbsolute()); assertTrue(new Path("/foo/bar").isAbsolute()); assertTrue(!new Path("foo").isAbsolute()); assertTrue(!new Path("foo/bar").isAbsolute()); } |
Path implements Iterable<String>, Serializable { public boolean isCanonical() { int offset = 0; boolean text = false; if (path.equals(".")) { return true; } if (!isRoot() && path.endsWith("/")) { return false; } while (offset < path.length()) { String sub = path.substring(offset); if (sub.equals("/") || sub.equals("")) { break; } if (sub.startsWith("./") || sub.equals(".")) { return false; } boolean up = sub.startsWith("../") || sub.equals(".."); if (text && up) { return false; } if (up == false) { text = true; } int next = sub.indexOf("/"); if (next == -1) { break; } else if (next == 0 && offset != 0) { return false; } else { offset += next + 1; } } return true; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void isCannonical() { assertTrue(new Path("/", false).isCanonical()); assertTrue(new Path("a", false).isCanonical()); assertTrue(new Path("a/b", false).isCanonical()); assertTrue(new Path("a/b/c", false).isCanonical()); assertTrue(new Path("a/..b/c", false).isCanonical()); assertTrue(new Path("a/b/c..", false).isCanonical()); assertTrue(new Path("..", false).isCanonical()); assertTrue(new Path("../", false).isCanonical()); assertTrue(new Path("../..", false).isCanonical()); assertTrue(new Path("../../", false).isCanonical()); assertTrue(new Path("../a", false).isCanonical()); assertTrue(new Path(".", false).isCanonical()); assertTrue(!new Path("./.", false).isCanonical()); assertTrue(!new Path("a assertTrue(!new Path("a/b/c assertTrue(!new Path("/.", false).isCanonical()); assertTrue(!new Path("./a", false).isCanonical()); assertTrue(!new Path("a/.", false).isCanonical()); assertTrue(!new Path("a/./b", false).isCanonical()); assertTrue(!new Path("./a/b/c", false).isCanonical()); assertTrue(!new Path("a/..b/./c", false).isCanonical()); assertTrue(!new Path("a/b/c../.", false).isCanonical()); assertTrue(!new Path("./..", false).isCanonical()); assertTrue(!new Path(".././", false).isCanonical()); assertTrue(!new Path(".././..", false).isCanonical()); assertTrue(!new Path("../.././", false).isCanonical()); assertTrue(!new Path("./../a", false).isCanonical()); assertTrue(!new Path("/..", false).isCanonical()); assertTrue(!new Path("/../..", false).isCanonical()); assertTrue(!new Path("a/..", false).isCanonical()); assertTrue(!new Path("a/../", false).isCanonical()); assertTrue(!new Path("../a/..", false).isCanonical()); assertTrue(!new Path("../../a/..", false).isCanonical()); assertTrue(!new Path("../../../a/..", false).isCanonical()); } |
Path implements Iterable<String>, Serializable { public boolean isChildOf(Path other) { return isDescendantOf(other) && size() == other.size() + 1; } Path(String path); Path(String path, boolean canonize); Path canonical(); boolean isCanonical(); boolean isRoot(); boolean isAbsolute(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); Iterator<String> iterator(); String getName(); boolean isAncestorOf(Path other); boolean isDescendantOf(Path other); boolean isParentOf(Path other); boolean isChildOf(Path other); int size(); Path parent(); String part(int index); Path subpath(int idx); Path toAbsolute(); Path append(Path relative); Path toRelative(Path ancestor); static final Path ROOT; static final Comparator<Path> SMALLEST_FIRST_COMPARATOR; static final Comparator<Path> LARGEST_FIRST_COMPARATOR; } | @Test public void isChildOf() { assertChild(new Path("/"), new Path("/foo")); assertNotChild(new Path("/"), new Path("/foo/bar")); assertChild(new Path("/foo/bar"), new Path("/foo/bar/baz")); assertNotChild(new Path("/foo/bar"), new Path("/foo/baz/bar")); assertNotChild(new Path("/"), new Path("/")); assertNotChild(new Path("/foo"), new Path("/")); } |
PoiList { public List<OsmObject> createAlternateList() { return poiList.subList(1, poiList.size()); } private PoiList(); static synchronized PoiList getInstance(); List<OsmObject> getPoiList(); void setPoiList(List<OsmObject> poiList); List<OsmObject> createAlternateList(); void clearPoiList(); void sortList(final double queryLatitude, final double queryLongitude); String serializePoiList(); void decodePoiList(String json); } | @Test public void createAlternateList() { List<OsmObject> alternateList = PoiList.getInstance().createAlternateList(); assertEquals(0, alternateList.size()); } |
QuestionsPresenter implements QuestionsActivityContract.Presenter { @Override public void assessIntentData(URI uri) { if (uri != null) { try { Map<String, List<String>> list = Utilities.splitQuery(uri); String verifier = list.get(PreferenceList.OAUTH_VERIFIER).get(0); String token = list.get(PreferenceList.OAUTH_TOKEN).get(0); preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, verifier); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, token); view.startOAuth(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } QuestionsPresenter(QuestionsActivityContract.View view, SourceContract.Preferences preferences); @Override void addPoiNameToTextview(); @Override void assessIntentData(URI uri); @Override void savePoiList(); @Override void restorePoiList(); } | @Test public void assessIntentData() { URI uri = null; try { uri = new URI("http: } catch (URISyntaxException e) { e.printStackTrace(); } questionsPresenter.assessIntentData(uri); verify(preferences).setStringPreference("oauth_verifier", "1"); verify(preferences).setStringPreference("oauth_token", "1"); verify(view).startOAuth(); } |
IntroPresenter implements IntroFragmentContract.Presenter { @Override public void getDetails() { String address = getAddress(); view.showDetails(poi.getName(), address, poi.getDrawable()); } IntroPresenter(IntroFragmentContract.View view); @Override void getDetails(); } | @Test public void addPoiToTextview() { introPresenter.getDetails(); verify(view).showDetails("Kitchen", " ", R.drawable.ic_restaurant); } |
OsmLoginPresenter implements OsmLoginFragmentContract.Presenter { @Override public void clickedOsmLoginButton() { preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, ""); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, ""); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN_SECRET, ""); view.startOAuth(); } OsmLoginPresenter(OsmLoginFragmentContract.View view, SourceContract.Preferences preferences); @Override void clickedOsmLoginButton(); } | @Test public void checkPreferencesAreCleared() { presenter.clickedOsmLoginButton(); verify(view).startOAuth(); } |
QuestionPresenter implements QuestionFragmentContract.Presenter { @Override public void getQuestion() { List<QuestionsContract> questions = this.listOfQuestions.getQuestion(); QuestionsContract questionsContract = questions.get(position); int question = questionsContract.getQuestion(); int color = questionsContract.getColor(); int drawable = questionsContract.getIcon(); view.showQuestion(question, poi.getName(), color, drawable); String key = questionsContract.getTag(); String answer = poi.getTag(key); if (answer != null) { view.setPreviousAnswer(answer); } else { view.setPreviousAnswer(""); } } QuestionPresenter(QuestionFragmentContract.View view, int position, SourceContract.Preferences preferences); @Override void getQuestion(); @Override void onAnswerSelected(int id); } | @Test public void getQuestionTest() { questionPresenter.getQuestion(); verify(view).showQuestion(anyInt(), anyString(), anyInt(), anyInt()); }
@Test public void getPreviousAnswerTest() { questionPresenter.getQuestion(); verify(view).setPreviousAnswer(anyString()); } |
QuestionPresenter implements QuestionFragmentContract.Presenter { @Override public void onAnswerSelected(int id) { List<QuestionsContract> questions = this.listOfQuestions.getQuestion(); QuestionsContract questionsContract = questions.get(position); int selectedColor = questionsContract.getColor(); int unselectedColor = R.color.colorPrimary; String answer = null; switch (id) { case R.id.answer_yes: view.setBackgroundColor(selectedColor, unselectedColor, unselectedColor); answer = "yes"; break; case R.id.answer_no: view.setBackgroundColor(unselectedColor, selectedColor, unselectedColor); answer = "no"; break; case R.id.answer_unsure: view.setBackgroundColor(unselectedColor, unselectedColor, selectedColor); answer = "unsure"; break; default: break; } String answerTag = questionsContract.getAnswer(answer); String questionTag = questionsContract.getTag(); addAnswer(questionTag, answerTag); if (position == listOfQuestions.getNoOfQuestions() - 1) { view.createChangesetTags(); new Thread(new Runnable() { @Override public void run() { SourceContract.upload upload = new UploadToOSM(preferences); upload.uploadToOsm(); } }).start(); } } QuestionPresenter(QuestionFragmentContract.View view, int position, SourceContract.Preferences preferences); @Override void getQuestion(); @Override void onAnswerSelected(int id); } | @Test public void yesAnswerSelected() { questionPresenter.onAnswerSelected(R.id.answer_yes); verify(view).setBackgroundColor(anyInt(), anyInt(), anyInt()); }
@Test public void noAnswerSelected() { questionPresenter.onAnswerSelected(R.id.answer_no); verify(view).setBackgroundColor(anyInt(), anyInt(), anyInt()); }
@Test public void unsureAnswerSelected() { questionPresenter.onAnswerSelected(R.id.answer_unsure); Set<String> keySet = Answers.getAnswerMap().keySet(); String key = keySet.toArray(new String[keySet.size()])[0]; String actual_answer = Answers.getAnswerMap().get(key); String expected_answer = ""; verify(view).setBackgroundColor(anyInt(), anyInt(), anyInt()); assertEquals(expected_answer, actual_answer); } |
MainActivityPresenter implements MainActivityContract.Presenter { @Override public void checkIfOauth(URI uri) { if (uri != null) { try { Map<String, List<String>> list = Utilities.splitQuery(uri); String verifier = list.get(PreferenceList.OAUTH_VERIFIER).get(0); String token = list.get(PreferenceList.OAUTH_TOKEN).get(0); preferences.setStringPreference(PreferenceList.OAUTH_VERIFIER, verifier); preferences.setStringPreference(PreferenceList.OAUTH_TOKEN, token); view.startOAuth(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } MainActivityPresenter(MainActivityContract.View view, SourceContract.Preferences preferences); @Override void showIfLoggedIn(); @Override void checkIfOauth(URI uri); void onButtonClicked(); @Override void toggleDebugMode(); @Override String getUserName(); @Override void savePoiList(); @Override void restorePoiList(); } | @Test public void checkIfInOAuthFlow() { URI url = null; try { url = new URI("http: } catch (URISyntaxException e) { e.printStackTrace(); } presenter.checkIfOauth(url); verify(view).startOAuth(); } |
MainActivityPresenter implements MainActivityContract.Presenter { @Override public void showIfLoggedIn() { boolean loggedIn = preferences.getBooleanPreference(PreferenceList.LOGGED_IN_TO_OSM); int message; int button; String userName = getUserName(); if (loggedIn) { if ("".equals(userName)) { message = R.string.logged_in; } else { message = R.string.logged_in_as; } button = R.string.log_out; } else { message = R.string.not_logged_in; button = R.string.authorise_openstreetmap; } view.showIfLoggedIn(message, button, userName); } MainActivityPresenter(MainActivityContract.View view, SourceContract.Preferences preferences); @Override void showIfLoggedIn(); @Override void checkIfOauth(URI uri); void onButtonClicked(); @Override void toggleDebugMode(); @Override String getUserName(); @Override void savePoiList(); @Override void restorePoiList(); } | @Test public void checkIfUsernameIsSetCorrectly() { presenter.showIfLoggedIn(); verify(view).showIfLoggedIn(anyInt(), anyInt(), (String) any()); } |
QueryOverpass implements SourceContract.Overpass { @Override public String getOverpassUri(double latitude, double longitude, float accuracy) { float measuredAccuracy; if (accuracy < 20) { measuredAccuracy = 20; } else if (accuracy > 100) { measuredAccuracy = 100; } else { measuredAccuracy = accuracy; } String overpassLocation = String.format("around:%s,%s,%s", measuredAccuracy, latitude, longitude); String nwr = "%1$s[~\"^(%2$s)$\"~\".\"](%3$s);"; String types = "shop|amenity|leisure|tourism"; String node = String.format(nwr, "node", types, overpassLocation); String way = String.format(nwr, "way", types, overpassLocation); String relation = String.format(nwr, "relation", types, overpassLocation); return String.format("https: } QueryOverpass(Context context); QueryOverpass(); @Override String getOverpassUri(double latitude, double longitude, float accuracy); @Override String queryOverpassApi(String urlString); @Override void processResult(String result); @Override void queryOverpass(double latitude, double longitude, float accuracy); String getType(JSONObject tags); } | @Test public void testGenerateOverpassUri() { double latitude = 53; double longitude = -7; float accuracy = 50; String expected_uri = "https: String uri = queryOverpass.getOverpassUri(latitude, longitude, accuracy); assertEquals(expected_uri, uri); } |
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void findVersion() { String version = BuildConfig.VERSION_NAME; view.setVersion(version); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); } | @Test public void checkVersionNameIsSet() { aboutPresenter.findVersion(); verify(view).setVersion(BuildConfig.VERSION_NAME); } |
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void getLicence() { String uri = "http: view.visitUri(uri); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); } | @Test public void checkLicenceDetailsAreSet() { aboutPresenter.getLicence(); verify(view).visitUri("http: } |
AboutPresenter implements MainActivityContract.AboutPresenter { @Override public void getGitHub() { String uri = "https: view.visitUri(uri); } AboutPresenter(MainActivityContract.AboutView view); @Override void findVersion(); @Override void getLicence(); @Override void getGitHub(); } | @Test public void checkSourceDetailsAreSet() { aboutPresenter.getGitHub(); verify(view).visitUri("https: } |
Utilities { public static Map<String, List<String>> splitQuery(URI url) throws UnsupportedEncodingException { final Map<String, List<String>> query_pairs = new LinkedHashMap<>(); final String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList<String>()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } static Map<String, List<String>> splitQuery(URI url); static float computeDistance(double latitude1, double longitude1, double latitude2, double longitude2); } | @Test public void splitqueryValidUrl() throws URISyntaxException, UnsupportedEncodingException { String uri = "http: URI url = new URI(uri); Map<String, List<String>> map = Utilities.splitQuery(url); assertEquals("[out:json]", map.get("data").get(0)); } |
Utilities { public static float computeDistance(double latitude1, double longitude1, double latitude2, double longitude2) { int MAXITERS = 20; double lat1 = latitude1 * (Math.PI / 180.0); double lat2 = latitude2 * (Math.PI / 180.0); double lon1 = longitude1 * (Math.PI / 180.0); double lon2 = longitude2 * (Math.PI / 180.0); double a = 6378137.0; double b = 6356752.3142; double f = (a - b) / a; double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b); double L = lon2 - lon1; double A = 0.0; double U1 = Math.atan((1.0 - f) * Math.tan(lat1)); double U2 = Math.atan((1.0 - f) * Math.tan(lat2)); double cosU1 = Math.cos(U1); double cosU2 = Math.cos(U2); double sinU1 = Math.sin(U1); double sinU2 = Math.sin(U2); double cosU1cosU2 = cosU1 * cosU2; double sinU1sinU2 = sinU1 * sinU2; double sigma = 0.0; double deltaSigma = 0.0; double cosSqAlpha; double cos2SM; double cosSigma; double sinSigma; double cosLambda; double sinLambda; double lambda = L; for (int iter = 0; iter < MAXITERS; iter++) { double lambdaOrig = lambda; cosLambda = Math.cos(lambda); sinLambda = Math.sin(lambda); double t1 = cosU2 * sinLambda; double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda; double sinSqSigma = t1 * t1 + t2 * t2; sinSigma = Math.sqrt(sinSqSigma); cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; sigma = Math.atan2(sinSigma, cosSigma); double sinAlpha = (sinSigma == 0) ? 0.0 : cosU1cosU2 * sinLambda / sinSigma; cosSqAlpha = 1.0 - sinAlpha * sinAlpha; cos2SM = (cosSqAlpha == 0) ? 0.0 : cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha; double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; A = 1 + (uSquared / 16384.0) * (4096.0 + uSquared * (-768 + uSquared * (320.0 - 175.0 * uSquared))); double B = (uSquared / 1024.0) * (256.0 + uSquared * (-128.0 + uSquared * (74.0 - 47.0 * uSquared))); double C = (f / 16.0) * cosSqAlpha * (4.0 + f * (4.0 - 3.0 * cosSqAlpha)); double cos2SMSq = cos2SM * cos2SM; deltaSigma = B * sinSigma * (cos2SM + (B / 4.0) * (cosSigma * (-1.0 + 2.0 * cos2SMSq) - (B / 6.0) * cos2SM * (-3.0 + 4.0 * sinSigma * sinSigma) * (-3.0 + 4.0 * cos2SMSq))); lambda = L + (1.0 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SM + C * cosSigma * (-1.0 + 2.0 * cos2SM * cos2SM))); double delta = (lambda - lambdaOrig) / lambda; if (Math.abs(delta) < 1.0e-12) { break; } } return (float) (b * A * (sigma - deltaSigma)); } static Map<String, List<String>> splitQuery(URI url); static float computeDistance(double latitude1, double longitude1, double latitude2, double longitude2); } | @Test public void calculateDistance() { double lat1 = 53.1; double lon1 = -7.5; double lat2 = 53.2; double lon2 = -7.4; float distance = Utilities.computeDistance(lat1, lon1, lat2, lon2); assertEquals(12985, distance, 1); } |
QueryOverpass implements SourceContract.Overpass { public String getType(JSONObject tags) throws JSONException { String type = ""; if (tags.has("amenity")) { type = tags.getString("amenity"); } if (tags.has("shop")) { type = tags.getString("shop"); } if (tags.has("tourism")) { type = tags.getString("tourism"); } if (tags.has("leisure")) { type = tags.getString("leisure"); } return type; } QueryOverpass(Context context); QueryOverpass(); @Override String getOverpassUri(double latitude, double longitude, float accuracy); @Override String queryOverpassApi(String urlString); @Override void processResult(String result); @Override void queryOverpass(double latitude, double longitude, float accuracy); String getType(JSONObject tags); } | @Test public void testGetOverpassResultPoiType() throws JSONException { String expected_result = "hairdresser"; JSONObject json = new JSONObject().put("amenity", expected_result); String result = queryOverpass.getType(json); assertEquals(expected_result, result); } |
Answers { public static Map<String, String> getAnswerMap() { getInstance(); return answerMap; } private Answers(); static Map<String, String> getAnswerMap(); static void addAnswer(String question, String answer); static void clearAnswerList(); static void setPoiDetails(OsmObject osmObject); static long getPoiId(); static String getPoiName(); static String getPoiType(); static Map<String, String> getChangesetTags(); static void setChangesetTags(Map<String, String> changesetTags); } | @Test public void getKeyFromTag() { String tag = this.questionObject.getTag(); String expectedValue = this.questionObject.getAnswerYes(); String actualValue = Answers.getAnswerMap().get(tag); assertEquals(expectedValue, actualValue); } |
Answers { public static Map<String, String> getChangesetTags() { getInstance(); return changesetTags; } private Answers(); static Map<String, String> getAnswerMap(); static void addAnswer(String question, String answer); static void clearAnswerList(); static void setPoiDetails(OsmObject osmObject); static long getPoiId(); static String getPoiName(); static String getPoiType(); static Map<String, String> getChangesetTags(); static void setChangesetTags(Map<String, String> changesetTags); } | @Test public void checkChangesetTagsAreSet() { Map<String, String> actualTags = Answers.getChangesetTags(); Map<String, String> expectedTags = new HashMap<>(); expectedTags.put("", ""); assertEquals(expectedTags, actualTags); } |
NotHerePresenter implements NotHereFragmentContract.Presenter { @Override public void getPoiDetails() { String name = poiList.get(0).getName(); view.setTextview(name); view.setAdapter(alternateList); } NotHerePresenter(NotHereFragmentContract.View view); @Override void getPoiDetails(); @Override void onItemClicked(int i); } | @Test public void addPoiToTextview() { notHerePresenter.getPoiDetails(); verify(view).setTextview("Kitchen"); } |
NotHerePresenter implements NotHereFragmentContract.Presenter { @Override public void onItemClicked(int i) { ArrayList<OsmObject> intentList = new ArrayList<>(); intentList.add(0, this.alternateList.get(i)); PoiList.getInstance().setPoiList(intentList); view.startActivity(); } NotHerePresenter(NotHereFragmentContract.View view); @Override void getPoiDetails(); @Override void onItemClicked(int i); } | @Test public void onClick() { notHerePresenter.onItemClicked(0); verify(view).startActivity(); } |
QuestionsPresenter implements QuestionsActivityContract.Presenter { @Override public void addPoiNameToTextview() { List<OsmObject> poiList = PoiList.getInstance().getPoiList(); if (poiList.size() != 0) { String poiType = poiList.get(0).getType(); PoiContract listOfQuestions = PoiTypes.getPoiType(poiType); listOfQuestions.shuffleQuestions(); if (preferences.getBooleanPreference(PreferenceList.LOGGED_IN_TO_OSM)) { view.setViewPager(poiList.get(0), listOfQuestions); if (poiList.size() == 1) { view.makeTextViewInvisible(); } else { view.setTextviewText(poiList.get(0).getName()); } } else { view.startNewActivity(); } } } QuestionsPresenter(QuestionsActivityContract.View view, SourceContract.Preferences preferences); @Override void addPoiNameToTextview(); @Override void assessIntentData(URI uri); @Override void savePoiList(); @Override void restorePoiList(); } | @Test public void addPoiNameToTextViewTestSinglePoiInList() { List<OsmObject> poiList = new ArrayList<>(); poiList.add(new OsmObject(1, "node", "", "restaurant", 1, 1, 1)); PoiList.getInstance().setPoiList(poiList); when(preferences.getBooleanPreference(anyString())).thenReturn(true); questionsPresenter.addPoiNameToTextview(); verify(view).makeTextViewInvisible(); }
@Test public void addPoiNameToTextViewTestMultiplePoiInList() { List<OsmObject> poiList = new ArrayList<>(); poiList.add(new OsmObject(1, "node", "Kitchen", "restaurant", 1, 1, 1)); poiList.add(new OsmObject(1, "node", "", "restaurant", 1, 1, 1)); PoiList.getInstance().setPoiList(poiList); when(preferences.getBooleanPreference(anyString())).thenReturn(true); questionsPresenter.addPoiNameToTextview(); verify(view).setTextviewText("Kitchen"); }
@Test public void addPoiNameToTextViewTestNotLoggedIn() { List<OsmObject> poiList = new ArrayList<>(); poiList.add(new OsmObject(1, "node", "Kitchen", "restaurant", 1, 1, 1)); poiList.add(new OsmObject(1, "node", "", "restaurant", 1, 1, 1)); PoiList.getInstance().setPoiList(poiList); when(preferences.getBooleanPreference(anyString())).thenReturn(false); questionsPresenter.addPoiNameToTextview(); verify(view).startNewActivity(); } |
MigrationRouter { public List<MigrationPair> getMigrationPairOfPNode(int pNodeNo) { return allNodeMigrationPairs.get(pNodeNo); } MigrationRouter(int vNodes, int oldPNodeCount, int newPNodeCount); int getNewPNodeCount(); int getOldPNodeCount(); List<MigrationPair> getMigrationPairOfPNode(int pNodeNo); List<List<MigrationPair>> getAllNodeMigrationPairs(); } | @Test public void testGetMigrationPairOfPNode() { MigrationRouter migrationRouter = new MigrationRouter(10000, 3, 4); System.out.println(migrationRouter.getMigrationPairOfPNode(0)); List<List<MigrationPair>> allNodeMigrationPairs = migrationRouter.getAllNodeMigrationPairs(); Assert.assertTrue( allNodeMigrationPairs.size() == 3); List<MigrationPair> pairs = allNodeMigrationPairs.get( 0 ); for (MigrationPair pair : pairs) { if(pair.getVnode() == 3) { Assert.assertEquals(0, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } if(pair.getVnode() == 9) { Assert.assertEquals(1, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } if(pair.getVnode() == 11) { Assert.assertEquals(2, pair.getSource().intValue()); Assert.assertEquals(3, pair.getTarget().intValue()); } } } |
ConsistentReportServiceImpl implements ConsistentReportService { public List<ConsistentReportDO> queryConsistentReport(Map params) { return consistentReportDao.queryConsistentReport(params); } void setConsistentReportDao(ConsistentReportDao consistentReportDao); Integer saveConsistentReport(ConsistentReportDO consistentReportDO); List<ConsistentReportDO> queryConsistentReport(Map params); int countConsistentReport(Map params); Integer deleteByIds(List<Integer> ids); Integer deleteByGmtCreate(String gmtCreateFrom, String gmtCreateTo); } | @Test public void testQueryConsistentReport() { } |
PNode2VNodeMapping { public List<Integer> getVNodes(int pNode) { return vpmMapping.get( pNode ); } PNode2VNodeMapping(int vNodes, int pNodeCount); List<Integer> getVNodes(int pNode); int getPNodeCount(); List<List<Integer>> getVpmMapping(); } | @Test public void testGetVNodes() { PNode2VNodeMapping mapping = new PNode2VNodeMapping(12, 3); System.out.println( "vNodes: of (12,3): " + mapping); List<Integer> vNodes = mapping.getVNodes(1); System.out.println( "vNodes: of (12,3:1): " + vNodes ); Assert.assertEquals(6, vNodes.get(0).intValue()); Assert.assertEquals(7, vNodes.get(1).intValue()); Assert.assertEquals(8, vNodes.get(2).intValue()); Assert.assertEquals(9, vNodes.get(3).intValue()); } |
PropertiesLoadUtil { public static Properties loadProperties(String propLocation) { Properties properties = null; properties = loadAsFile(propLocation); if( properties != null) return properties; properties = loadAsResource(propLocation); return properties; } static Properties loadProperties(String propLocation); } | @Test public void testProperty() { Properties properties = PropertiesLoadUtil.loadProperties("./test/test/test/testp.properties"); assertEquals("value1", properties.get("key1")); } |
JavaObjectSerializer implements Serializer { public byte[] serialize(Object o, Object arg) { byte[] bvalue = null; if( o == null ) { bvalue = new byte[]{ Byte.valueOf( (byte) 0 )}; return bvalue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject( o ); bvalue = baos.toByteArray(); return bvalue; } catch (IOException e) { throw new RuntimeException("Fail to serialize object: " + o +", cause: " + e, e); }finally { try { baos.close(); } catch (IOException e) { } } } Object deserialize(byte[] bvalue, Object deserializeTarget); byte[] serialize(Object o, Object arg); } | @Test public void testSerializeNull() { Serializer serializer = new JavaObjectSerializer(); byte[] bvalue = serializer.serialize(null, null); char c = (char) Byte.valueOf( (byte)0 ).byteValue(); byte s = "0".getBytes()[0] ; System.out.println("asc 0: " + s +", c: " + c); }
@Test public void testSerialize() { Serializer serializer = new JavaObjectSerializer(); String stringObj = "key001"; byte[] bvalue = serializer.serialize(stringObj, null); Assert.assertTrue("string serialize result", bvalue != null); } |
JavaObjectSerializer implements Serializer { public Object deserialize(byte[] bvalue, Object deserializeTarget) { if( bvalue == null) return null; ByteArrayInputStream bais = new ByteArrayInputStream( bvalue ); try { ObjectInputStream ois = new ObjectInputStream(bais); Object obj = ois.readObject(); return obj; } catch (Exception e) { throw new RuntimeException("Fail to deserialize object, byte value:" + bvalue +", cause: " + e, e); }finally { try { bais.close(); } catch (IOException e) { } } } Object deserialize(byte[] bvalue, Object deserializeTarget); byte[] serialize(Object o, Object arg); } | @Test public void testDeserialize() { Serializer serializer = new JavaObjectSerializer(); String stringObj = "key001"; byte[] bvalue = serializer.serialize(stringObj, null); String result = (String) serializer.deserialize(bvalue, null); Assert.assertEquals("string serialize result",stringObj, result); } |
StorageManager { protected void loadStorage(StorageConfig config) { driver.init(config); storage = driver.createStorage(); } StorageManager(); Storage getStorage(); StorageType getStorageType(); void registStorage(Class<?> storageDriverClass); } | @Test public void testLoadStorage() { StorageManager manager = new StorageManager(); } |
MigrationVirtualNodeFinder { public String getTargetNodeOfVirtualNode(int vnode) { return index.get( vnode ); } MigrationVirtualNodeFinder(List<MigrationRoutePair> migrationRoutePairs); String getTargetNodeOfVirtualNode(int vnode); } | @Test public void testGetTargetNodeOfVirtualNode() { List<MigrationRoutePair> migrationRoutePairs = new ArrayList<MigrationRoutePair>(); for (int i = 0; i < 1000 ; i++) { MigrationRoutePair pair = new MigrationRoutePair(); pair.setVnode( i ); pair.setTargetPhysicalId("127.0.0.1"); migrationRoutePairs.add( pair ); } MigrationVirtualNodeFinder finder = new MigrationVirtualNodeFinder(migrationRoutePairs); String targetNode1 = finder.getTargetNodeOfVirtualNode( 100 ); assertNotNull("targetNode1 found", targetNode1); String targetNode2 = finder.getTargetNodeOfVirtualNode( 1000 + 1 ); assertNull("targetNode2 not found ", targetNode2); } |
ProgressComputer { public int getGrossProgress() { reentrantLock.lock(); try { return grossProgress; }finally { reentrantLock.unlock(); } } ProgressComputer(List<MigrationRoutePair> migrationRoutePairs); synchronized boolean completeOneVNode(String targetNodeId, Integer vnodeId); int getGrossProgress(); int getFinishCount(); int getProgressOfTarget(String tNodeId); } | @Test public void testGetGrossProgress() { List<MigrationRoutePair> migrationRoutePairs = new ArrayList<MigrationRoutePair>(); int t = 1, v = 10000 ; for (int i = 0; i < t; i++) { for (int j = 0; j < v; j++) { MigrationRoutePair pair = new MigrationRoutePair(j , "t"+i ); migrationRoutePairs.add( pair ); } } ProgressComputer progressComputer = new ProgressComputer(migrationRoutePairs); int lastProgress = -1; for (int i = 0; i < v ; i++) { boolean need = progressComputer.completeOneVNode( "t0", 0); int progress = progressComputer.getGrossProgress(); lastProgress = progress; } assertEquals("Progress=100", 100,lastProgress); } |
ConsistentReportServiceImpl implements ConsistentReportService { public Integer saveConsistentReport(ConsistentReportDO consistentReportDO) { return consistentReportDao.insert(consistentReportDO); } void setConsistentReportDao(ConsistentReportDao consistentReportDao); Integer saveConsistentReport(ConsistentReportDO consistentReportDO); List<ConsistentReportDO> queryConsistentReport(Map params); int countConsistentReport(Map params); Integer deleteByIds(List<Integer> ids); Integer deleteByGmtCreate(String gmtCreateFrom, String gmtCreateTo); } | @Test public void testSaveConsistentReport() { } |
SimulationTreeTableToModelConverter { public BPMNProcess convertTreeToModel(SushiTree<Object> tree){ this.tree = tree; BPMNStartEvent startEvent = new BPMNStartEvent(createID(), "Start", null); process.addBPMNElement(startEvent); BPMNEndEvent endEvent = new BPMNEndEvent(createID(), "End", null); process.addBPMNElement(endEvent); convertTreeToBPMNTree(); Tuple<AbstractBPMNElement, AbstractBPMNElement> subStartAndEnd = createSubBranch(bpmnTree.getRootElements().get(0)); AbstractBPMNElement.connectElements(startEvent, subStartAndEnd.x); AbstractBPMNElement.connectElements(subStartAndEnd.y, endEvent); return process; } BPMNProcess convertTreeToModel(SushiTree<Object> tree); } | @Test public void testConversion(){ SimulationTreeTableToModelConverter converter = new SimulationTreeTableToModelConverter(); BPMNProcess process = converter.convertTreeToModel(tree); assertTrue("Should be 14, but was " + process.getBPMNElementsWithOutSequenceFlows().size(), process.getBPMNElementsWithOutSequenceFlows().size() == 14); assertNotNull(process.getStartEvent()); BPMNStartEvent startEvent = process.getStartEvent(); assertTrue(startEvent.getSuccessors().size() == 1); assertTrue(startEvent.getSuccessors().iterator().next() instanceof BPMNXORGateway); BPMNXORGateway xor1 = (BPMNXORGateway) startEvent.getSuccessors().iterator().next(); List<AbstractBPMNElement> successors = SetUtil.asList(xor1.getSuccessors()); assertTrue(successors.size() == 2); assertTrue(successors.get(0) instanceof BPMNTask); assertTrue(successors.get(1) instanceof BPMNTask); assertTrue(successors.get(0).getSuccessors().iterator().next() instanceof BPMNXORGateway); BPMNXORGateway xor2 = (BPMNXORGateway) successors.get(0).getSuccessors().iterator().next(); assertTrue(xor2.getSuccessors().size() == 1); assertTrue("Should be BPMNAndGateway, but was " + xor2.getSuccessors().iterator().next(),xor2.getSuccessors().iterator().next() instanceof BPMNAndGateway); BPMNAndGateway and1 = (BPMNAndGateway) xor2.getSuccessors().iterator().next(); assertTrue(and1.getSuccessors().size() == 2); successors = SetUtil.asList(and1.getSuccessors()); for(AbstractBPMNElement successor : successors){ if(successor instanceof BPMNTask){ BPMNTask task = (BPMNTask)successor; if(task.getMonitoringPoints().get(0).getEventType().equals(e1)){ assertTrue(task.getSuccessors().iterator().next() instanceof BPMNTask); } } else { assertTrue(successor instanceof BPMNXORGateway); BPMNXORGateway loopEntry = (BPMNXORGateway) successor; assertTrue(loopEntry.getPredecessors().size() == 2); assertTrue(loopEntry.getSuccessors().size() == 1); assertTrue(loopEntry.getSuccessors().iterator().next() instanceof BPMNTask); BPMNTask loopTask1 = (BPMNTask) loopEntry.getSuccessors().iterator().next(); assertTrue(loopTask1.getSuccessors().size() == 1); assertTrue(loopTask1.getSuccessors().iterator().next() instanceof BPMNTask); BPMNTask loopTask2 = (BPMNTask) loopTask1.getSuccessors().iterator().next(); assertTrue(loopTask2.getSuccessors().size() == 1); assertTrue(loopTask2.getSuccessors().iterator().next() instanceof BPMNXORGateway); BPMNXORGateway loopExit = (BPMNXORGateway) loopTask2.getSuccessors().iterator().next(); assertTrue(loopExit.getSuccessors().size() == 2); for(AbstractBPMNElement loopExitSuccessor : loopExit.getSuccessors()){ if(loopExitSuccessor instanceof BPMNAndGateway){ assertTrue(loopExitSuccessor.getPredecessors().size() == 2); assertTrue(loopExitSuccessor.getSuccessors().size() == 1); assertTrue(loopExitSuccessor.getSuccessors().contains(process.getEndEvent())); } } } } } |
BPMNParser extends AbstractXMLParser { public static BPMNProcess generateProcessFromXML(String filePath) { Document doc = readXMLDocument(filePath); return generateBPMNProcess(doc); } static BPMNProcess generateProcessFromXML(String filePath); } | @Test public void testComplexProcess() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{ BPMNProcess BPMNProcess = BPMNParser.generateProcessFromXML(complexfilePath); assertNotNull(BPMNProcess); assertTrue(BPMNProcess.getBPMNElementsWithOutSequenceFlows().size() == 21); assertTrue(BPMNProcess.getStartEvent().getId().equals("sid-EC585815-8EAC-411C-89C2-553ACA85CF5A")); }
@Test public void testSubProcessImport() { BPMNProcess BPMNProcess = BPMNParser.generateProcessFromXML(subProcessfilePath); assertNotNull(BPMNProcess); assertTrue(BPMNProcess.getBPMNElementsWithOutSequenceFlows().size() == 7); assertTrue(BPMNProcess.hasSubProcesses()); BPMNSubProcess subProcess = BPMNProcess.getSubProcesses().get(0); assertNotNull(subProcess); assertFalse(subProcess.getStartEvent().getSuccessors().isEmpty()); } |
XSDParser extends AbstractXMLParser { public static SushiEventType generateEventTypeFromXSD(String filePath, String eventTypeName) throws XMLParsingException { Document doc = readXMLDocument(filePath); if (doc == null) { throw new XMLParsingException("could not read XSD: " + filePath); } return generateEventType(doc, eventTypeName); } static SushiEventType generateEventTypeFromXSD(String filePath, String eventTypeName); static SushiEventType generateEventType(Document doc, String schemaName); } | @Test public void testXSDParsing() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException{ SushiEventType eventType = null; try { eventType = XSDParser.generateEventTypeFromXSD(filePath, "EventTaxonomy"); } catch (XMLParsingException e) { fail(); } assertNotNull(eventType); } |
XMLParser extends AbstractXMLParser { public static SushiEvent generateEventFromXML(String filePath) throws XMLParsingException { Document doc = readXMLDocument(filePath); return generateEvent(doc, null); } static SushiEvent generateEventFromXML(String filePath); static SushiEvent generateEventFromXML(String filePath, String pathToXSD); static SushiEvent generateEventFromDoc(Document xmlDoc); static Node getFirstChildWithNameFromNode(String name, Node parentNode); static Node getLastChildWithNameFromNode(String name, Node parentNode); static List<Node> getAllChildWithNameFromNode(String name, Node parentNode); } | @Test public void testXMLParsing() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, XMLParsingException{ SushiEventType eventTyp = new SushiEventType("EventTaxonomy"); eventTyp.setXMLName("EventTaxonomy"); eventTyp.setTimestampName("timestamp"); eventTyp.save(); SushiEvent event = XMLParser.generateEventFromXML(filePath); assertNotNull(event); }
@Test public void testHierarchicalTimestampParsing() throws XMLParsingException { SushiEventType eventTyp = new SushiEventType("EventTaxonomy"); eventTyp.setXMLName("EventTaxonomy"); eventTyp.setTimestampName("location.timestamp"); eventTyp.save(); SushiEvent event = XMLParser.generateEventFromXML(filePathToXMLWithHierarchicalTimestamp); assertNotNull(event); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2013, 11, 25, 20, 25, 00); assertTrue("Should be " + cal.getTime() + " but was " + event.getTimestamp(), event.getTimestamp().equals(cal.getTime())); }
@Test public void testNonHierarchicalTimestampParsing() throws XMLParsingException { SushiEventType eventTyp = new SushiEventType("EventTaxonomy"); eventTyp.setXMLName("EventTaxonomy"); eventTyp.setTimestampName("timestamp"); eventTyp.save(); SushiEvent event = XMLParser.generateEventFromXML(filePathToXMLWithHierarchicalTimestamp); assertNotNull(event); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(2013, 11, 24, 20, 25, 00); assertTrue("Should be " + cal.getTime() + " but was " + event.getTimestamp(), event.getTimestamp().equals(cal.getTime())); } |
BPM2XMLToSignavioXMLConverter extends AbstractXMLParser { public String generateSignavioXMLFromBPM2XML(){ SignavioBPMNProcess process = parseBPM2XML(); File file = new File(pathToCoreComponentsFolder + fileNameWithoutExtenxions + ".signavio.xml"); try { FileWriter writer = new FileWriter(file ,false); writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); writer.write(System.getProperty("line.separator")); writer.write("<oryxmodel>"); writer.write(System.getProperty("line.separator")); writer.write("<description></description>"); writer.write(System.getProperty("line.separator")); writer.write("<type>BPMN 2.0</type>"); writer.write(System.getProperty("line.separator")); writer.write("<json-representation><![CDATA["); writer.write(process.generateSignavioXMLString()); writer.write("]]></json-representation>"); writer.write(System.getProperty("line.separator")); writer.write("</oryxmodel>"); writer.flush(); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } return file.getName(); } BPM2XMLToSignavioXMLConverter(String bpm2FilePath); String generateSignavioXMLFromBPM2XML(); SignavioBPMNProcess parseBPM2XML(); } | @Test public void testConversion(){ BPM2XMLToSignavioXMLConverter converter = new BPM2XMLToSignavioXMLConverter(emptyBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(startEventBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(taskBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(endEventBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(edgeBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(simpleBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(testBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(startMessageEventBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(multipleStartEventsBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(xorBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(andBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); converter = new BPM2XMLToSignavioXMLConverter(complexBpmn2FilePath); converter.generateSignavioXMLFromBPM2XML(); } |
BPM2XMLToSignavioXMLConverter extends AbstractXMLParser { public SignavioBPMNProcess parseBPM2XML() { Document doc = readXMLDocument(bpm2FilePath); process = new SignavioBPMNProcess(); Node definitionNode = getDefinitionsElementFromBPM(doc); if(definitionNode != null){ process.addPropertyValue("targetnamespace", definitionNode.getAttributes().getNamedItem("targetNamespace").getNodeValue()); process.addPropertyValue("expressionlanguage", definitionNode.getAttributes().getNamedItem("expressionLanguage").getNodeValue()); process.addPropertyValue("typelanguage", definitionNode.getAttributes().getNamedItem("typeLanguage").getNodeValue()); } NodeList processChilds = getProcessElementsFromBPM(doc); for(int i = 0; i < processChilds.getLength(); i++){ process.addChildShape(getProcessChildFromXML(processChilds.item(i), doc)); } return process; } BPM2XMLToSignavioXMLConverter(String bpm2FilePath); String generateSignavioXMLFromBPM2XML(); SignavioBPMNProcess parseBPM2XML(); } | @Test public void testParsing(){ BPM2XMLToSignavioXMLConverter converter = new BPM2XMLToSignavioXMLConverter(emptyBpmn2FilePath); converter.parseBPM2XML(); } |
Index implements Iterable<IndexItem<A,I>> { public static <A extends Annotation,I> Index<A,I> load(Class<A> annotation, Class<I> instanceType) throws IllegalArgumentException { return load(annotation, instanceType, Thread.currentThread().getContextClassLoader()); } private Index(Class<A> annotation, Class<I> instance, ClassLoader loader); static Index<A,I> load(Class<A> annotation, Class<I> instanceType); static Index<A,I> load(Class<A> annotation, Class<I> instanceType, ClassLoader loader); Iterator<IndexItem<A,I>> iterator(); } | @Test public void staticallyKnownAnnotation() throws Exception { TestUtils.makeSource(src, "impl.C", "import " + Marker.class.getName().replace('$', '.') + ";", "@Marker(stuff=\"hello\")", "public class C {}"); TestUtils.runApt(src, null, clz, new File[] { new File(URI.create(Marker.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm())) }, null); int cnt = 0; for (IndexItem<Marker,Object> item : Index.load(Marker.class, Object.class, loader)) { cnt++; assertEquals("impl.C", ((Class) item.element()).getName()); assertEquals("impl.C", item.instance().getClass().getName()); Marker proxy = item.annotation(); assertEquals(Marker.class, proxy.annotationType()); assertEquals("hello", proxy.stuff()); Marker real1 = Marked1.class.getAnnotation(Marker.class), real2 = Marked2.class.getAnnotation(Marker.class); assertEquals(real1, proxy); assertEquals(proxy, real1); assertEquals(real1.hashCode(), proxy.hashCode()); assertFalse(real2.equals(proxy)); assertFalse(proxy.equals(real2)); } assertEquals(1, cnt); }
@SuppressWarnings("unchecked") @Test public void methodsAndFields() throws Exception { TestUtils.makeSource(src, "x.A", "import java.lang.annotation.*;", "@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})", "@net.java.sezpoz.Indexable", "public @interface A {}"); TestUtils.makeSource(src, "y.C", "public class C {", "@x.A", "public static final Object F = 1;", "@x.A", "public static Object m() {return 2;}", "}"); TestUtils.runApt(src, null, clz, new File[0], null); Class<? extends Annotation> a = loader.loadClass("x.A").asSubclass(Annotation.class); int cnt = 0; for (IndexItem item : Index.load(a, Object.class, loader)) { cnt++; assertEquals("y.C", item.className()); if (item.kind() == ElementType.FIELD) { assertEquals("F", item.memberName()); assertEquals(1, item.instance()); } else { assertEquals(ElementType.METHOD, item.kind()); assertEquals("m", item.memberName()); assertEquals(2, item.instance()); } } assertEquals(2, cnt); }
@Test public void defaultValues() throws Exception { TestUtils.makeSource(src, "x.A", "import java.lang.annotation.*;", "@Retention(RetentionPolicy.RUNTIME)", "@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})", "@net.java.sezpoz.Indexable", "public @interface A {", "int x() default 5;", "}"); TestUtils.makeSource(src, "y.C", "import x.A;", "public class C {", "@A", "public static Void m1() {return null;}", "@A(x=5)", "public static Void m2() {return null;}", "@A(x=17)", "public static Void m3() {return null;}", "}"); TestUtils.runApt(src, null, clz, new File[0], null); Class<? extends Annotation> a = loader.loadClass("x.A").asSubclass(Annotation.class); int cnt = 0; Annotation[] proxyAnns = new Annotation[3]; Annotation[] liveAnns = new Annotation[3]; for (IndexItem item : Index.load(a, Object.class, loader)) { cnt++; assertEquals("y.C", item.className()); Annotation ann = item.annotation(); Method x = a.getMethod("x"); int index; if (item.memberName().equals("m1")) { index = 0; assertEquals(5, x.invoke(ann)); } else if (item.memberName().equals("m2")) { index = 1; assertEquals(5, x.invoke(ann)); } else { assertEquals("m3", item.memberName()); index = 2; assertEquals(17, x.invoke(ann)); } proxyAnns[index] = ann; liveAnns[index] = item.element().getAnnotation(a); assertNotNull(liveAnns[index]); } assertEquals(3, cnt); Set<Annotation> all = new HashSet<Annotation>(); all.addAll(Arrays.asList(proxyAnns)); all.addAll(Arrays.asList(liveAnns)); assertEquals("all annotations are either with x=5 or x=17", 2, all.size()); Map<Annotation,Void> all2 = new IdentityHashMap<Annotation,Void>(); for (Annotation ann : proxyAnns) { all2.put(ann, null); } for (Annotation ann : liveAnns) { all2.put(ann, null); } assertEquals(6, all2.size()); } |
AbstractClient { protected static void init() { keywordSet.add("-" + HOST_ARGS); keywordSet.add("-" + HELP_ARGS); keywordSet.add("-" + PORT_ARGS); keywordSet.add("-" + PASSWORD_ARGS); keywordSet.add("-" + USERNAME_ARGS); keywordSet.add("-" + ISO8601_ARGS); keywordSet.add("-" + MAX_PRINT_ROW_COUNT_ARGS); } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); } | @Test public void testInit() { AbstractClient.init(); String[] keywords = {AbstractClient.HOST_ARGS, AbstractClient.HELP_ARGS, AbstractClient.PORT_ARGS, AbstractClient.PASSWORD_ARGS, AbstractClient.USERNAME_ARGS, AbstractClient.ISO8601_ARGS, AbstractClient.MAX_PRINT_ROW_COUNT_ARGS,}; for (String keyword : keywords) { if (!AbstractClient.keywordSet.contains("-" + keyword)) { System.out.println(keyword); fail(); } } } |
Pair { @Override public String toString() { return "<" + left + "," + right + ">"; } Pair(L l, R r); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); public L left; public R right; } | @Test public void testToString() { Pair<String, Integer> p1 = new Pair<String, Integer>("a", 123123); assertEquals("<a,123123>", p1.toString()); Pair<Float, Double> p2 = new Pair<Float, Double>(32.5f, 123.123d); assertEquals("<32.5,123.123>", p2.toString()); } |
BytesUtils { public static byte[] intToBytes(int i) { return new byte[]{(byte) ((i >> 24) & 0xFF), (byte) ((i >> 16) & 0xFF), (byte) ((i >> 8) & 0xFF), (byte) (i & 0xFF)}; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testIntToBytes() { int b = 123; byte[] bb = BytesUtils.intToBytes(b); int bf = BytesUtils.bytesToInt(bb); assertEquals("testBytesToFloat", b, bf); } |
BytesUtils { public static byte[] floatToBytes(float x) { byte[] b = new byte[4]; int l = Float.floatToIntBits(x); for (int i = 3; i >= 0; i--) { b[i] = new Integer(l).byteValue(); l = l >> 8; } return b; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testFloatToBytes() throws Exception { float b = 25.0f; byte[] bb = BytesUtils.floatToBytes(b); float bf = BytesUtils.bytesToFloat(bb); assertEquals("testBytesToFloat", b, bf, CommonTestConstant.float_min_delta); } |
BytesUtils { public static byte[] boolToBytes(boolean x) { byte[] b = new byte[1]; if (x) { b[0] = 1; } else { b[0] = 0; } return b; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testBoolToBytes() throws Exception { boolean b = true; byte[] bb = BytesUtils.boolToBytes(b); boolean bf = BytesUtils.bytesToBool(bb); assertEquals("testBoolToBytes", b, bf); } |
BytesUtils { public static byte[] longToBytes(long num) { return longToBytes(num, 8); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testlongToBytes() { long lNum = 32143422454243342L; long iNum = 1032423424L; long lSNum = 10; assertEquals(lNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(lNum, 8), 8)); assertEquals(iNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(iNum, 8), 8)); assertEquals(iNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(iNum, 4), 4)); assertEquals(lSNum, BytesUtils.bytesToLong(BytesUtils.longToBytes(lSNum, 1), 1)); } |
BytesUtils { public static long readLong(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(8, in); return BytesUtils.bytesToLong(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void readLongTest() throws IOException { long l = 32143422454243342L; byte[] bs = BytesUtils.longToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readLong(in)); }
@Test public void testReadLong() throws IOException { long l = r.nextLong(); byte[] bs = BytesUtils.longToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readLong(in)); } |
BytesUtils { public static byte[] doubleToBytes(double data) { byte[] bytes = new byte[8]; long value = Double.doubleToLongBits(data); for (int i = 7; i >= 0; i--) { bytes[i] = new Long(value).byteValue(); value = value >> 8; } return bytes; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testDoubleToBytes() { double b1 = 2745687.1253123d; byte[] ret = BytesUtils.doubleToBytes(b1); double rb1 = BytesUtils.bytesToDouble(ret); assertEquals(b1, rb1, CommonTestConstant.float_min_delta); } |
BytesUtils { public static byte[] stringToBytes(String str) { try { return str.getBytes(TSFileConfig.STRING_ENCODING); } catch (UnsupportedEncodingException e) { LOG.error("catch UnsupportedEncodingException {}", str, e); return null; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testStringToBytes() { String b = "lqfkgv12KLDJSL1@#%"; byte[] ret = BytesUtils.stringToBytes(b); String rb1 = BytesUtils.bytesToString(ret); assertTrue(b.equals(rb1)); } |
BytesUtils { public static byte[] concatByteArray(byte[] a, byte[] b) { byte[] c = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testConcatByteArray() { List<byte[]> list = new ArrayList<byte[]>(); float f1 = 12.4f; boolean b1 = true; list.add(BytesUtils.floatToBytes(f1)); list.add(BytesUtils.boolToBytes(b1)); byte[] ret = BytesUtils.concatByteArray(list.get(0), list.get(1)); float rf1 = BytesUtils.bytesToFloat(ret, 0); boolean rb1 = BytesUtils.bytesToBool(ret, 4); assertEquals(f1, rf1, CommonTestConstant.float_min_delta); assertEquals(b1, rb1); } |
BytesUtils { public static byte[] concatByteArrayList(List<byte[]> list) { int size = list.size(); int len = 0; for (byte[] cs : list) { len += cs.length; } byte[] result = new byte[len]; int pos = 0; for (int i = 0; i < size; i++) { int l = list.get(i).length; System.arraycopy(list.get(i), 0, result, pos, l); pos += l; } return result; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testConcatByteArrayList() { List<byte[]> list = new ArrayList<byte[]>(); float f1 = 12.4f; boolean b1 = true; int i1 = 12; list.add(BytesUtils.floatToBytes(f1)); list.add(BytesUtils.boolToBytes(b1)); list.add(BytesUtils.intToBytes(i1)); byte[] ret = BytesUtils.concatByteArrayList(list); float rf1 = BytesUtils.bytesToFloat(ret, 0); boolean rb1 = BytesUtils.bytesToBool(ret, 4); int ri1 = BytesUtils.bytesToInt(ret, 5); assertEquals(f1, rf1, CommonTestConstant.float_min_delta); assertEquals(b1, rb1); assertEquals(i1, ri1); } |
AbstractClient { protected static String checkRequiredArg(String arg, String name, CommandLine commandLine, boolean isRequired, String defaultValue) throws ArgsErrorException { String str = commandLine.getOptionValue(arg); if (str == null) { if (isRequired) { String msg = String .format("%s: Required values for option '%s' not provided", IOTDB_CLI_PREFIX, name); System.out.println(msg); System.out.println("Use -help for more information"); throw new ArgsErrorException(msg); } else if (defaultValue == null) { String msg = String .format("%s: Required values for option '%s' is null.", IOTDB_CLI_PREFIX, name); throw new ArgsErrorException(msg); } else { return defaultValue; } } return str; } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); } | @Test public void testCheckRequiredArg() throws ParseException, ArgsErrorException { Options options = AbstractClient.createOptions(); CommandLineParser parser = new DefaultParser(); String[] args = new String[]{"-u", "user1"}; CommandLine commandLine = parser.parse(options, args); String str = AbstractClient .checkRequiredArg(AbstractClient.USERNAME_ARGS, AbstractClient.USERNAME_NAME, commandLine, true, "root"); assertEquals(str, "user1"); args = new String[]{"-u", "root",}; commandLine = parser.parse(options, args); str = AbstractClient .checkRequiredArg(AbstractClient.HOST_ARGS, AbstractClient.HOST_NAME, commandLine, false, "127.0.0.1"); assertEquals(str, "127.0.0.1"); try { str = AbstractClient .checkRequiredArg(AbstractClient.HOST_ARGS, AbstractClient.HOST_NAME, commandLine, true, "127.0.0.1"); } catch (ArgsErrorException e) { assertEquals(e.getMessage(), "IoTDB: Required values for option 'host' not provided"); } try { str = AbstractClient .checkRequiredArg(AbstractClient.HOST_ARGS, AbstractClient.HOST_NAME, commandLine, false, null); } catch (ArgsErrorException e) { assertEquals(e.getMessage(), "IoTDB: Required values for option 'host' is null."); } } |
BytesUtils { public static byte[] subBytes(byte[] src, int start, int length) { if ((start + length) > src.length) { return null; } if (length <= 0) { return null; } byte[] result = new byte[length]; for (int i = 0; i < length; i++) { result[i] = src[start + i]; } return result; } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testSubBytes() throws IOException { List<byte[]> list = new ArrayList<byte[]>(); float f1 = 12.4f; boolean b1 = true; int i1 = 12; list.add(BytesUtils.floatToBytes(f1)); list.add(BytesUtils.boolToBytes(b1)); list.add(BytesUtils.intToBytes(i1)); byte[] ret = BytesUtils.concatByteArrayList(list); boolean rb1 = BytesUtils.bytesToBool(BytesUtils.subBytes(ret, 4, 1)); int ri1 = BytesUtils.bytesToInt(BytesUtils.subBytes(ret, 5, 4)); assertEquals(b1, rb1); assertEquals(i1, ri1); } |
BytesUtils { public static int getByteN(byte data, int offset) { offset %= 8; if ((data & (1 << (7 - offset))) != 0) { return 1; } else { return 0; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testGetByteN() { byte src = 120; byte dest = 0; for (int i = 0; i < 64; i++) { int a = BytesUtils.getByteN(src, i); dest = BytesUtils.setByteN(dest, i, a); } assertEquals(src, dest); } |
BytesUtils { public static int getLongN(long data, int offset) { offset %= 64; if ((data & (1L << (offset))) != 0) { return 1; } else { return 0; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testGetLongN() { long src = (long) Math.pow(2, 33); long dest = 0; for (int i = 0; i < 64; i++) { int a = BytesUtils.getLongN(src, i); dest = BytesUtils.setLongN(dest, i, a); } assertEquals(src, dest); } |
BytesUtils { public static int getIntN(int data, int offset) { offset %= 32; if ((data & (1 << (offset))) != 0) { return 1; } else { return 0; } } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testGetIntN() { int src = 54243342; int dest = 0; for (int i = 0; i < 32; i++) { int a = BytesUtils.getIntN(src, i); dest = BytesUtils.setIntN(dest, i, a); } assertEquals(src, dest); } |
BytesUtils { public static int readInt(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(4, in); return BytesUtils.bytesToInt(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testReadInt() throws IOException { int l = r.nextInt(); byte[] bs = BytesUtils.intToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readInt(in)); } |
BytesUtils { public static float readFloat(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(4, in); return BytesUtils.bytesToFloat(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testReadFloat() throws IOException { float l = r.nextFloat(); byte[] bs = BytesUtils.floatToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readFloat(in), CommonTestConstant.float_min_delta); } |
BytesUtils { public static double readDouble(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(8, in); return BytesUtils.bytesToDouble(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testReadDouble() throws IOException { double l = r.nextDouble(); byte[] bs = BytesUtils.doubleToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readDouble(in), CommonTestConstant.double_min_delta); } |
BytesUtils { public static boolean readBool(InputStream in) throws IOException { byte[] b = safeReadInputStreamToBytes(1, in); return BytesUtils.bytesToBool(b); } static byte[] intToBytes(int i); static byte[] intToBytes(int i, byte[] desc, int offset); static void intToBytes(int srcNum, byte[] result, int pos, int width); static byte[] intToTwoBytes(int i); static int twoBytesToInt(byte[] ret); static int bytesToInt(byte[] bytes); static int bytesToInt(byte[] bytes, int offset); static int bytesToInt(byte[] result, int pos, int width); static byte[] floatToBytes(float x); static void floatToBytes(float x, byte[] desc, int offset); static float bytesToFloat(byte[] b); static float bytesToFloat(byte[] b, int offset); static byte[] doubleToBytes(double data); static void doubleToBytes(double d, byte[] bytes, int offset); static double bytesToDouble(byte[] bytes); static double bytesToDouble(byte[] bytes, int offset); static byte[] boolToBytes(boolean x); static byte[] boolToBytes(boolean x, byte[] desc, int offset); static boolean bytesToBool(byte[] b); static boolean bytesToBool(byte[] b, int offset); static byte[] longToBytes(long num); static byte[] longToBytes(long num, int len); static byte[] longToBytes(long num, byte[] desc, int offset); static void longToBytes(long srcNum, byte[] result, int pos, int width); static long bytesToLong(byte[] byteNum); static long bytesToLong(byte[] byteNum, int len); static long bytesToLong(byte[] result, int pos, int width); static long bytesToLongFromOffset(byte[] byteNum, int len, int offset); static byte[] stringToBytes(String str); static String bytesToString(byte[] byteStr); static byte[] concatByteArray(byte[] a, byte[] b); static byte[] concatByteArrayList(List<byte[]> list); static byte[] subBytes(byte[] src, int start, int length); static int getIntN(int data, int offset); static int setIntN(int data, int offset, int value); static int getByteN(byte data, int offset); static byte setByteN(byte data, int offset, int value); static int getLongN(long data, int offset); static long setLongN(long data, int offset, int value); static double readDouble(InputStream in); static float readFloat(InputStream in); static boolean readBool(InputStream in); static int readInt(InputStream in); static long readLong(InputStream in); static byte[] safeReadInputStreamToBytes(int count, InputStream in); static byte[] shortToBytes(short number); static short bytesToShort(byte[] b); } | @Test public void testReadBool() throws IOException { boolean l = r.nextBoolean(); byte[] bs = BytesUtils.boolToBytes(l); InputStream in = new ByteArrayInputStream(bs); assertEquals(l, BytesUtils.readBool(in)); } |
StringContainer { public String getSubString(int index) { int realIndex = index >= 0 ? index : count + index; if (realIndex < 0 || realIndex >= count) { throw new IndexOutOfBoundsException( "Index: " + index + ", Real Index: " + realIndex + ", Size: " + count); } if (realIndex < reverseList.size()) { return reverseList.get(reverseList.size() - 1 - realIndex); } else { return sequenceList.get(realIndex - reverseList.size()); } } StringContainer(); StringContainer(String joinSeparator); StringContainer(String[] strings); StringContainer(String[] strings, String joinSeparator); int size(); int length(); ArrayList<String> getSequenceList(); ArrayList<String> getReverseList(); StringContainer addTail(Object... objs); StringContainer addTail(String... strings); StringContainer addTail(StringContainer myContainer); StringContainer addHead(String... strings); StringContainer addHead(StringContainer myContainer); @Override String toString(); String join(String separator); String getSubString(int index); StringContainer getSubStringContainer(int start, int end); @Override int hashCode(); @Override boolean equals(Object sc); boolean equals(StringContainer sc); @Override StringContainer clone(); } | @Test public void testGetSubString() { StringContainer a = new StringContainer(); try { a.getSubString(0); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addHead("a", "bbb", "cc"); assertEquals("a", a.getSubString(0)); assertEquals("cc", a.getSubString(-1)); assertEquals("bbb", a.getSubString(-2)); try { a.getSubString(4); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addTail("dd", "eeee"); assertEquals("a", a.getSubString(0)); assertEquals("cc", a.getSubString(-3)); assertEquals("dd", a.getSubString(3)); assertEquals("eeee", a.getSubString(-1)); try { a.getSubString(9); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } } |
AbstractClient { protected static String[] removePasswordArgs(String[] args) { int index = -1; for (int i = 0; i < args.length; i++) { if (args[i].equals("-" + PASSWORD_ARGS)) { index = i; break; } } if (index >= 0) { if ((index + 1 >= args.length) || (index + 1 < args.length && keywordSet .contains(args[index + 1]))) { return ArrayUtils.remove(args, index); } } return args; } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); } | @Test public void testRemovePasswordArgs() { AbstractClient.init(); String[] input = new String[]{"-h", "127.0.0.1", "-p", "6667", "-u", "root", "-pw", "root"}; String[] res = new String[]{"-h", "127.0.0.1", "-p", "6667", "-u", "root", "-pw", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-h", "127.0.0.1", "-p", "6667", "-pw", "root", "-u", "root"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "-pw", "root", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-h", "127.0.0.1", "-p", "6667", "root", "-u", "root", "-pw"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "root", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-h", "127.0.0.1", "-p", "6667", "-pw", "-u", "root"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{"-pw", "-h", "127.0.0.1", "-p", "6667", "root", "-u", "root"}; res = new String[]{"-h", "127.0.0.1", "-p", "6667", "root", "-u", "root"}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); input = new String[]{}; res = new String[]{}; isTwoStringArrayEqual(res, AbstractClient.removePasswordArgs(input)); } |
StringContainer { public StringContainer getSubStringContainer(int start, int end) { int realStartIndex = start >= 0 ? start : count + start; int realEndIndex = end >= 0 ? end : count + end; if (realStartIndex < 0 || realStartIndex >= count) { throw new IndexOutOfBoundsException( "start Index: " + start + ", Real start Index: " + realStartIndex + ", Size: " + count); } if (realEndIndex < 0 || realEndIndex >= count) { throw new IndexOutOfBoundsException( "end Index: " + end + ", Real end Index: " + realEndIndex + ", Size: " + count); } StringContainer ret = new StringContainer(joinSeparator); if (realStartIndex < reverseList.size()) { for (int i = reverseList.size() - 1 - realStartIndex; i >= Math.max(0, reverseList.size() - 1 - realEndIndex); i--) { ret.addTail(this.reverseList.get(i)); } } if (realEndIndex >= reverseList.size()) { for (int i = Math.max(0, realStartIndex - reverseList.size()); i <= realEndIndex - reverseList.size(); i++) { ret.addTail(this.sequenceList.get(i)); } } return ret; } StringContainer(); StringContainer(String joinSeparator); StringContainer(String[] strings); StringContainer(String[] strings, String joinSeparator); int size(); int length(); ArrayList<String> getSequenceList(); ArrayList<String> getReverseList(); StringContainer addTail(Object... objs); StringContainer addTail(String... strings); StringContainer addTail(StringContainer myContainer); StringContainer addHead(String... strings); StringContainer addHead(StringContainer myContainer); @Override String toString(); String join(String separator); String getSubString(int index); StringContainer getSubStringContainer(int start, int end); @Override int hashCode(); @Override boolean equals(Object sc); boolean equals(StringContainer sc); @Override StringContainer clone(); } | @Test public void testGetSubStringContainer() { StringContainer a = new StringContainer(); try { a.getSubStringContainer(0, 1); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addTail("a", "bbb", "cc"); assertEquals("", a.getSubStringContainer(1, 0).toString()); assertEquals("a", a.getSubStringContainer(0, 0).toString()); assertEquals("bbbcc", a.getSubStringContainer(1, -1).toString()); assertEquals("bbb", a.getSubStringContainer(-2, -2).toString()); try { a.getSubStringContainer(1, 4); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } a.addHead("dd", "eeee"); assertEquals("eeeea", a.getSubStringContainer(1, 2).toString()); assertEquals("eeeea", a.getSubStringContainer(1, -3).toString()); assertEquals("dd", a.getSubStringContainer(0, 0).toString()); assertEquals("cc", a.getSubStringContainer(-1, -1).toString()); assertEquals("ddeeeeabbbcc", a.getSubStringContainer(-5, -1).toString()); try { a.getSubString(9); } catch (Exception e) { assertTrue(e instanceof IndexOutOfBoundsException); } } |
StringContainer { @Override public int hashCode() { final int prime = 31; int result = 1; if (joinSeparator != null) { result = prime * result + joinSeparator.hashCode(); } for (String string : reverseList) { result = prime * result + ((string == null) ? 0 : string.hashCode()); } for (String string : sequenceList) { result = prime * result + ((string == null) ? 0 : string.hashCode()); } return result; } StringContainer(); StringContainer(String joinSeparator); StringContainer(String[] strings); StringContainer(String[] strings, String joinSeparator); int size(); int length(); ArrayList<String> getSequenceList(); ArrayList<String> getReverseList(); StringContainer addTail(Object... objs); StringContainer addTail(String... strings); StringContainer addTail(StringContainer myContainer); StringContainer addHead(String... strings); StringContainer addHead(StringContainer myContainer); @Override String toString(); String join(String separator); String getSubString(int index); StringContainer getSubStringContainer(int start, int end); @Override int hashCode(); @Override boolean equals(Object sc); boolean equals(StringContainer sc); @Override StringContainer clone(); } | @Test public void testHashCode() { StringContainer c1 = new StringContainer(","); c1.addHead("a", "b", "c123"); c1.addTail("a", "12", "c"); c1.addTail("1284736", "b", "c"); StringContainer c2 = new StringContainer("."); c2.addHead("a", "b", "c123"); c2.addTail("a", "12", "c"); c2.addTail("1284736", "b", "c"); StringContainer copyC = c1.clone(); assertEquals(c1.hashCode(), copyC.hashCode()); assertNotEquals(c1.hashCode(), c2.hashCode()); StringContainer c3 = new StringContainer(","); c3.addHead("a", "b", "c123"); assertNotEquals(c1.hashCode(), c3.hashCode()); StringContainer c4 = new StringContainer(","); c4.addTail("a", "b", "c123"); assertNotEquals(c1.hashCode(), c4.hashCode()); } |
MetadataQuerierByFileImpl implements MetadataQuerier { @Override public List<ChunkMetaData> getChunkMetaDataList(Path path) throws IOException { return chunkMetaDataCache.get(path); } MetadataQuerierByFileImpl(TsFileSequenceReader tsFileReader); @Override List<ChunkMetaData> getChunkMetaDataList(Path path); @Override TsFileMetaData getWholeFileMetadata(); @Override void loadChunkMetaDatas(List<Path> paths); } | @Test public void test() throws IOException { fileReader = new TsFileSequenceReader(FILE_PATH); MetadataQuerierByFileImpl metadataQuerierByFile = new MetadataQuerierByFileImpl(fileReader); List<ChunkMetaData> chunkMetaDataList = metadataQuerierByFile .getChunkMetaDataList(new Path("d2.s1")); for (ChunkMetaData chunkMetaData : chunkMetaDataList) { Assert.assertEquals(chunkMetaData.getMeasurementUid(), "s1"); } } |
Path { public boolean startWith(String prefix) { return prefix != null && fullPath.startsWith(prefix); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); } | @Test public void startWith() throws Exception { Path path = new Path("a.b.c"); assertTrue(path.startWith(new Path(""))); assertTrue(path.startWith(new Path("a"))); assertTrue(path.startWith(new Path("a.b.c"))); } |
Path { public static Path mergePath(Path prefix, Path suffix) { StringContainer sc = new StringContainer(SystemConstant.PATH_SEPARATOR); sc.addTail(prefix); sc.addTail(suffix); return new Path(sc); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); } | @Test public void mergePath() throws Exception { Path prefix = new Path("a.b.c"); Path suffix = new Path("d.e"); Path suffix1 = new Path(""); testPath(Path.mergePath(prefix, suffix), "a.b.c.d", "e", "a.b.c.d.e"); testPath(Path.mergePath(prefix, suffix1), "a.b", "c", "a.b.c"); } |
Path { public static Path replace(String srcPrefix, Path descPrefix) { if ("".equals(srcPrefix) || descPrefix.startWith(srcPrefix)) { return descPrefix; } int prefixSize = srcPrefix.split(SystemConstant.PATH_SEPARATER_NO_REGEX).length; String[] descArray = descPrefix.fullPath.split(SystemConstant.PATH_SEPARATER_NO_REGEX); if (descArray.length <= prefixSize) { return new Path(srcPrefix); } StringContainer sc = new StringContainer(SystemConstant.PATH_SEPARATOR); sc.addTail(srcPrefix); for (int i = prefixSize; i < descArray.length; i++) { sc.addTail(descArray[i]); } return new Path(sc); } Path(StringContainer pathSc); Path(String pathSc); Path(String[] pathSc); Path(String device, String measurement); static Path mergePath(Path prefix, Path suffix); static Path addPrefixPath(Path src, String prefix); static Path addPrefixPath(Path src, Path prefix); static Path replace(String srcPrefix, Path descPrefix); static Path replace(Path srcPrefix, Path descPrefix); String getFullPath(); String getDevice(); String getMeasurement(); @Override int hashCode(); @Override boolean equals(Object obj); boolean equals(String obj); @Override String toString(); @Override Path clone(); boolean startWith(String prefix); boolean startWith(Path prefix); } | @Test public void replace() throws Exception { Path src = new Path("a.b.c"); Path rep1 = new Path(""); Path rep2 = new Path("d"); Path rep3 = new Path("d.e.f"); Path rep4 = new Path("d.e.f.g"); testPath(Path.replace(rep1, src), "a.b", "c", "a.b.c"); testPath(Path.replace(rep2, src), "d.b", "c", "d.b.c"); testPath(Path.replace(rep3, src), "d.e", "f", "d.e.f"); testPath(Path.replace(rep4, src), "d.e.f", "g", "d.e.f.g"); } |
ReadOnlyTsFile { public QueryDataSet query(QueryExpression queryExpression) throws IOException { return tsFileExecutor.execute(queryExpression); } ReadOnlyTsFile(TsFileSequenceReader fileReader); QueryDataSet query(QueryExpression queryExpression); void close(); } | @Test public void queryTest() throws IOException { Filter filter = TimeFilter.lt(1480562618100L); Filter filter2 = ValueFilter.gt(new Binary("dog")); Filter filter3 = FilterFactory .and(TimeFilter.gtEq(1480562618000L), TimeFilter.ltEq(1480562618100L)); IExpression IExpression = BinaryExpression .or(BinaryExpression.and(new SingleSeriesExpression(new Path("d1.s1"), filter), new SingleSeriesExpression(new Path("d1.s4"), filter2)), new GlobalTimeExpression(filter3)); QueryExpression queryExpression = QueryExpression.create().addSelectedPath(new Path("d1.s1")) .addSelectedPath(new Path("d1.s4")).setExpression(IExpression); QueryDataSet queryDataSet = tsFile.query(queryExpression); long aimedTimestamp = 1480562618000L; while (queryDataSet.hasNext()) { RowRecord rowRecord = queryDataSet.next(); Assert.assertEquals(aimedTimestamp, rowRecord.getTimestamp()); aimedTimestamp++; } queryExpression = QueryExpression.create().addSelectedPath(new Path("d1.s1")) .addSelectedPath(new Path("d1.s4")); queryDataSet = tsFile.query(queryExpression); aimedTimestamp = 1480562618000L; int count = 0; while (queryDataSet.hasNext()) { RowRecord rowRecord = queryDataSet.next(); Assert.assertEquals(aimedTimestamp, rowRecord.getTimestamp()); aimedTimestamp++; count++; } Assert.assertEquals(rowCount, count); queryExpression = QueryExpression.create().addSelectedPath(new Path("d1.s1")) .addSelectedPath(new Path("d1.s4")) .setExpression(new GlobalTimeExpression(filter3)); queryDataSet = tsFile.query(queryExpression); aimedTimestamp = 1480562618000L; count = 0; while (queryDataSet.hasNext()) { RowRecord rowRecord = queryDataSet.next(); Assert.assertEquals(aimedTimestamp, rowRecord.getTimestamp()); aimedTimestamp++; count++; } Assert.assertEquals(101, count); } |
IoTDBDatabaseMetadata implements DatabaseMetaData { public String getMetadataInJson() throws SQLException { try { return getMetadataInJsonFunc(); } catch (TException e) { boolean flag = connection.reconnect(); this.client = connection.client; if (flag) { try { return getMetadataInJsonFunc(); } catch (TException e2) { throw new SQLException("Failed to fetch all metadata in json " + "after reconnecting. Please check the server status."); } } else { throw new SQLException("Failed to reconnect to the server " + "when fetching all metadata in json. Please check the server status."); } } } IoTDBDatabaseMetadata(IoTDBConnection connection, TSIService.Iface client); @Override ResultSet getColumns(String catalog, String schemaPattern, String columnPattern,
String devicePattern); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> iface); @Override boolean allProceduresAreCallable(); @Override boolean allTablesAreSelectable(); @Override boolean autoCommitFailureClosesAllResultSets(); @Override boolean dataDefinitionCausesTransactionCommit(); @Override boolean dataDefinitionIgnoredInTransactions(); @Override boolean deletesAreDetected(int arg0); @Override boolean doesMaxRowSizeIncludeBlobs(); @Override boolean generatedKeyAlwaysReturned(); @Override ResultSet getAttributes(String arg0, String arg1, String arg2, String arg3); @Override ResultSet getBestRowIdentifier(String arg0, String arg1, String arg2, int arg3,
boolean arg4); @Override String getCatalogSeparator(); @Override String getCatalogTerm(); @Override ResultSet getCatalogs(); @Override ResultSet getClientInfoProperties(); @Override ResultSet getColumnPrivileges(String arg0, String arg1, String arg2,
String arg3); @Override Connection getConnection(); @Override ResultSet getCrossReference(String arg0, String arg1, String arg2, String arg3,
String arg4, String arg5); @Override int getDatabaseMajorVersion(); @Override int getDatabaseMinorVersion(); @Override String getDatabaseProductName(); @Override String getDatabaseProductVersion(); @Override int getDefaultTransactionIsolation(); @Override int getDriverMajorVersion(); @Override int getDriverMinorVersion(); @Override String getDriverName(); @Override String getDriverVersion(); @Override ResultSet getExportedKeys(String arg0, String arg1, String arg2); @Override String getExtraNameCharacters(); @Override ResultSet getFunctionColumns(String arg0, String arg1, String arg2, String arg3); @Override ResultSet getFunctions(String arg0, String arg1, String arg2); @Override String getIdentifierQuoteString(); @Override ResultSet getImportedKeys(String arg0, String arg1, String arg2); @Override ResultSet getIndexInfo(String arg0, String arg1, String arg2, boolean arg3, boolean arg4); @Override int getJDBCMajorVersion(); @Override int getJDBCMinorVersion(); @Override int getMaxBinaryLiteralLength(); @Override int getMaxCatalogNameLength(); @Override int getMaxCharLiteralLength(); @Override int getMaxColumnNameLength(); @Override int getMaxColumnsInGroupBy(); @Override int getMaxColumnsInIndex(); @Override int getMaxColumnsInOrderBy(); @Override int getMaxColumnsInSelect(); @Override int getMaxColumnsInTable(); @Override int getMaxConnections(); @Override int getMaxCursorNameLength(); @Override int getMaxIndexLength(); @Override int getMaxProcedureNameLength(); @Override int getMaxRowSize(); @Override int getMaxSchemaNameLength(); @Override int getMaxStatementLength(); @Override int getMaxStatements(); @Override int getMaxTableNameLength(); @Override int getMaxTablesInSelect(); @Override int getMaxUserNameLength(); @Override String getNumericFunctions(); @Override ResultSet getPrimaryKeys(String arg0, String arg1, String arg2); @Override ResultSet getProcedureColumns(String arg0, String arg1, String arg2, String arg3); @Override String getProcedureTerm(); @Override ResultSet getProcedures(String arg0, String arg1, String arg2); @Override ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern,
String columnNamePattern); @Override int getResultSetHoldability(); @Override RowIdLifetime getRowIdLifetime(); @Override String getSQLKeywords(); @Override int getSQLStateType(); @Override String getSchemaTerm(); @Override ResultSet getSchemas(); @Override ResultSet getSchemas(String catalog, String schemaPattern); @Override String getSearchStringEscape(); @Override String getStringFunctions(); @Override ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern); @Override ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern); @Override String getSystemFunctions(); @Override ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern); @Override ResultSet getTableTypes(); @Override ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,
String[] types); @Override String getTimeDateFunctions(); @Override ResultSet getTypeInfo(); @Override ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern,
int[] types); @Override String getURL(); @Override String getUserName(); @Override ResultSet getVersionColumns(String catalog, String schema, String table); @Override boolean insertsAreDetected(int type); @Override boolean isCatalogAtStart(); @Override boolean isReadOnly(); @Override boolean locatorsUpdateCopy(); @Override boolean nullPlusNonNullIsNull(); @Override boolean nullsAreSortedAtEnd(); @Override boolean nullsAreSortedAtStart(); @Override boolean nullsAreSortedHigh(); @Override boolean nullsAreSortedLow(); @Override boolean othersDeletesAreVisible(int type); @Override boolean othersInsertsAreVisible(int type); @Override boolean othersUpdatesAreVisible(int type); @Override boolean ownDeletesAreVisible(int type); @Override boolean ownInsertsAreVisible(int type); @Override boolean ownUpdatesAreVisible(int type); @Override boolean storesLowerCaseIdentifiers(); @Override boolean storesLowerCaseQuotedIdentifiers(); @Override boolean storesMixedCaseIdentifiers(); @Override boolean storesMixedCaseQuotedIdentifiers(); @Override boolean storesUpperCaseIdentifiers(); @Override boolean storesUpperCaseQuotedIdentifiers(); @Override boolean supportsANSI92EntryLevelSQL(); @Override boolean supportsANSI92FullSQL(); @Override boolean supportsANSI92IntermediateSQL(); @Override boolean supportsAlterTableWithAddColumn(); @Override boolean supportsAlterTableWithDropColumn(); @Override boolean supportsBatchUpdates(); @Override boolean supportsCatalogsInDataManipulation(); @Override boolean supportsCatalogsInIndexDefinitions(); @Override boolean supportsCatalogsInPrivilegeDefinitions(); @Override boolean supportsCatalogsInProcedureCalls(); @Override boolean supportsCatalogsInTableDefinitions(); @Override boolean supportsColumnAliasing(); @Override boolean supportsConvert(); @Override boolean supportsConvert(int fromType, int toType); @Override boolean supportsCoreSQLGrammar(); @Override boolean supportsCorrelatedSubqueries(); @Override boolean supportsDataDefinitionAndDataManipulationTransactions(); @Override boolean supportsDataManipulationTransactionsOnly(); @Override boolean supportsDifferentTableCorrelationNames(); @Override boolean supportsExpressionsInOrderBy(); @Override boolean supportsExtendedSQLGrammar(); @Override boolean supportsFullOuterJoins(); @Override boolean supportsGetGeneratedKeys(); @Override boolean supportsGroupBy(); @Override boolean supportsGroupByBeyondSelect(); @Override boolean supportsGroupByUnrelated(); @Override boolean supportsIntegrityEnhancementFacility(); @Override boolean supportsLikeEscapeClause(); @Override boolean supportsLimitedOuterJoins(); @Override boolean supportsMinimumSQLGrammar(); @Override boolean supportsMixedCaseIdentifiers(); @Override boolean supportsMixedCaseQuotedIdentifiers(); @Override boolean supportsMultipleOpenResults(); @Override boolean supportsMultipleResultSets(); @Override boolean supportsMultipleTransactions(); @Override boolean supportsNamedParameters(); @Override boolean supportsNonNullableColumns(); @Override boolean supportsOpenCursorsAcrossCommit(); @Override boolean supportsOpenCursorsAcrossRollback(); @Override boolean supportsOpenStatementsAcrossCommit(); @Override boolean supportsOpenStatementsAcrossRollback(); @Override boolean supportsOrderByUnrelated(); @Override boolean supportsOuterJoins(); @Override boolean supportsPositionedDelete(); @Override boolean supportsPositionedUpdate(); @Override boolean supportsResultSetConcurrency(int type, int concurrency); @Override boolean supportsResultSetHoldability(int holdability); @Override boolean supportsResultSetType(int type); @Override boolean supportsSavepoints(); @Override boolean supportsSchemasInDataManipulation(); @Override boolean supportsSchemasInIndexDefinitions(); @Override boolean supportsSchemasInPrivilegeDefinitions(); @Override boolean supportsSchemasInProcedureCalls(); @Override boolean supportsSchemasInTableDefinitions(); @Override boolean supportsSelectForUpdate(); @Override boolean supportsStatementPooling(); @Override boolean supportsStoredFunctionsUsingCallSyntax(); @Override boolean supportsStoredProcedures(); @Override boolean supportsSubqueriesInComparisons(); @Override boolean supportsSubqueriesInExists(); @Override boolean supportsSubqueriesInIns(); @Override boolean supportsSubqueriesInQuantifieds(); @Override boolean supportsTableCorrelationNames(); @Override boolean supportsTransactionIsolationLevel(int level); @Override boolean supportsTransactions(); @Override boolean supportsUnion(); @Override boolean supportsUnionAll(); @Override boolean updatesAreDetected(int type); @Override boolean usesLocalFilePerTable(); @Override boolean usesLocalFiles(); @Deprecated @Override String toString(); String getMetadataInJson(); } | @SuppressWarnings("resource") @Test public void ShowTimeseriesInJson() throws Exception { String metadataInJson = "=== Timeseries Tree ===\n" + "\n" + "root:{\n" + " vehicle:{\n" + " d0:{\n" + " s0:{\n" + " DataType: INT32,\n" + " Encoding: RLE,\n" + " args: {},\n" + " StorageGroup: root.vehicle \n" + " },\n" + " s1:{\n" + " DataType: INT64,\n" + " Encoding: RLE,\n" + " args: {},\n" + " StorageGroup: root.vehicle \n" + " },\n" + " s2:{\n" + " DataType: FLOAT,\n" + " Encoding: RLE,\n" + " args: {},\n" + " StorageGroup: root.vehicle \n" + " }\n" + " }\n" + " }\n" + "}"; when(fetchMetadataResp.getMetadataInJson()).thenReturn(metadataInJson); String res = ((IoTDBDatabaseMetadata) databaseMetaData).getMetadataInJson(); assertEquals(metadataInJson, res); } |
IoTDBPrepareStatement extends IoTDBStatement implements PreparedStatement { @Override public boolean execute() throws SQLException { return super.execute(createCompleteSql(sql, parameters)); } IoTDBPrepareStatement(IoTDBConnection connection, Iface client,
TS_SessionHandle sessionHandle, String sql,
ZoneId zoneId); @Override void addBatch(); @Override void clearParameters(); @Override boolean execute(); @Override ResultSet executeQuery(); @Override int executeUpdate(); @Override ResultSetMetaData getMetaData(); @Override ParameterMetaData getParameterMetaData(); @Override void setArray(int parameterIndex, Array x); @Override void setAsciiStream(int parameterIndex, InputStream x); @Override void setAsciiStream(int parameterIndex, InputStream x, int length); @Override void setAsciiStream(int parameterIndex, InputStream x, long length); @Override void setBigDecimal(int parameterIndex, BigDecimal x); @Override void setBinaryStream(int parameterIndex, InputStream x); @Override void setBinaryStream(int parameterIndex, InputStream x, int length); @Override void setBinaryStream(int parameterIndex, InputStream x, long length); @Override void setBlob(int parameterIndex, Blob x); @Override void setBlob(int parameterIndex, InputStream inputStream); @Override void setBlob(int parameterIndex, InputStream inputStream, long length); @Override void setBoolean(int parameterIndex, boolean x); @Override void setByte(int parameterIndex, byte x); @Override void setBytes(int parameterIndex, byte[] x); @Override void setCharacterStream(int parameterIndex, Reader reader); @Override void setCharacterStream(int parameterIndex, Reader reader, int length); @Override void setCharacterStream(int parameterIndex, Reader reader, long length); @Override void setClob(int parameterIndex, Clob x); @Override void setClob(int parameterIndex, Reader reader); @Override void setClob(int parameterIndex, Reader reader, long length); @Override void setDate(int parameterIndex, Date x); @Override void setDate(int parameterIndex, Date x, Calendar cal); @Override void setDouble(int parameterIndex, double x); @Override void setFloat(int parameterIndex, float x); @Override void setInt(int parameterIndex, int x); @Override void setLong(int parameterIndex, long x); @Override void setNCharacterStream(int parameterIndex, Reader value); @Override void setNCharacterStream(int parameterIndex, Reader value, long length); @Override void setNClob(int parameterIndex, NClob value); @Override void setNClob(int parameterIndex, Reader reader); @Override void setNClob(int parameterIndex, Reader reader, long length); @Override void setNString(int parameterIndex, String value); @Override void setNull(int parameterIndex, int sqlType); @Override void setNull(int parameterIndex, int sqlType, String typeName); @Override void setObject(int parameterIndex, Object x); @Override void setObject(int parameterIndex, Object x, int targetSqlType); @Override void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength); @Override void setRef(int parameterIndex, Ref x); @Override void setRowId(int parameterIndex, RowId x); @Override void setSQLXML(int parameterIndex, SQLXML xmlObject); @Override void setShort(int parameterIndex, short x); @Override void setString(int parameterIndex, String x); @Override void setTime(int parameterIndex, Time x); @Override void setTime(int parameterIndex, Time x, Calendar cal); @Override void setTimestamp(int parameterIndex, Timestamp x); @Override void setTimestamp(int parameterIndex, Timestamp x, Calendar cal); @Override void setURL(int parameterIndex, URL x); @Override void setUnicodeStream(int parameterIndex, InputStream x, int length); } | @SuppressWarnings("resource") @Test public void testNonParameterized() throws Exception { String sql = "SELECT status, temperature FROM root.ln.wf01.wt01 WHERE temperature < 24 and time > 2017-11-1 0:13:00"; IoTDBPrepareStatement ps = new IoTDBPrepareStatement(connection, client, sessHandle, sql, zoneId); ps.execute(); ArgumentCaptor<TSExecuteStatementReq> argument = ArgumentCaptor .forClass(TSExecuteStatementReq.class); verify(client).executeStatement(argument.capture()); assertEquals( "SELECT status, temperature FROM root.ln.wf01.wt01 WHERE temperature < 24 and time > 2017-11-1 0:13:00", argument.getValue().getStatement()); }
@SuppressWarnings("resource") @Test(expected = SQLException.class) public void unsetArgument() throws SQLException { String sql = "SELECT status, temperature FROM root.ln.wf01.wt01 WHERE temperature < 24 and time > ?"; IoTDBPrepareStatement ps = new IoTDBPrepareStatement(connection, client, sessHandle, sql, zoneId); ps.execute(); } |
AbstractClient { protected static OperationResult handleInputInputCmd(String cmd, IoTDBConnection connection) { String specialCmd = cmd.toLowerCase().trim(); if (specialCmd.equals(QUIT_COMMAND) || specialCmd.equals(EXIT_COMMAND)) { System.out.println(specialCmd + " normally"); return OperationResult.RETURN_OPER; } if (specialCmd.equals(HELP)) { System.out.println(String.format(" <your-sql>\t\t\t execute your sql statment")); System.out .println(String .format(" %s\t\t show how many timeseries are in iotdb", SHOW_METADATA_COMMAND)); System.out .println(String.format(" %s=xxx\t eg. long, default, ISO8601, yyyy-MM-dd HH:mm:ss.", SET_TIMESTAMP_DISPLAY)); System.out.println(String.format(" %s\t show time display type", SHOW_TIMESTAMP_DISPLAY)); System.out.println(String.format(" %s=xxx\t\t eg. +08:00, Asia/Shanghai.", SET_TIME_ZONE)); System.out.println(String.format(" %s\t\t show cli time zone", SHOW_TIMEZONE)); System.out.println( String.format(" %s=xxx\t\t set fetch size when querying data from server.", SET_FETCH_SIZE)); System.out.println(String.format(" %s\t\t show fetch size", SHOW_FETCH_SIZE)); System.out.println( String.format(" %s=xxx\t eg. set max lines for cli to ouput, -1 equals to unlimited.", SET_MAX_DISPLAY_NUM)); return OperationResult.CONTINUE_OPER; } if (specialCmd.equals(SHOW_METADATA_COMMAND)) { try { System.out.println(((IoTDBDatabaseMetadata) connection.getMetaData()).getMetadataInJson()); } catch (SQLException e) { System.out.println("Failed to show timeseries because: " + e.getMessage()); } return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(SET_TIMESTAMP_DISPLAY)) { String[] values = specialCmd.split("="); if (values.length != 2) { System.out.println(String.format("Time display format error, please input like %s=ISO8601", SET_TIMESTAMP_DISPLAY)); return OperationResult.CONTINUE_OPER; } try { setTimeFormat(cmd.split("=")[1]); } catch (Exception e) { System.out.println(String.format("time display format error, %s", e.getMessage())); return OperationResult.CONTINUE_OPER; } System.out.println("Time display type has set to " + cmd.split("=")[1].trim()); return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(SET_TIME_ZONE)) { String[] values = specialCmd.split("="); if (values.length != 2) { System.out.println( String.format("Time zone format error, please input like %s=+08:00", SET_TIME_ZONE)); return OperationResult.CONTINUE_OPER; } try { connection.setTimeZone(cmd.split("=")[1].trim()); } catch (Exception e) { System.out.println(String.format("Time zone format error, %s", e.getMessage())); return OperationResult.CONTINUE_OPER; } System.out.println("Time zone has set to " + values[1].trim()); return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(SET_FETCH_SIZE)) { String[] values = specialCmd.split("="); if (values.length != 2) { System.out .println(String .format("Fetch size format error, please input like %s=10000", SET_FETCH_SIZE)); return OperationResult.CONTINUE_OPER; } try { setFetchSize(cmd.split("=")[1]); } catch (Exception e) { System.out.println(String.format("Fetch size format error, %s", e.getMessage())); return OperationResult.CONTINUE_OPER; } System.out.println("Fetch size has set to " + values[1].trim()); return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(SET_MAX_DISPLAY_NUM)) { String[] values = specialCmd.split("="); if (values.length != 2) { System.out .println(String.format("Max display number format error, please input like %s = 10000", SET_MAX_DISPLAY_NUM)); return OperationResult.CONTINUE_OPER; } try { setMaxDisplayNumber(cmd.split("=")[1]); } catch (Exception e) { System.out.println(String.format("Max display number format error, %s", e.getMessage())); return OperationResult.CONTINUE_OPER; } System.out.println("Max display number has set to " + values[1].trim()); return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(SHOW_TIMEZONE)) { try { System.out.println("Current time zone: " + connection.getTimeZone()); } catch (Exception e) { System.out.println("Cannot get time zone from server side because: " + e.getMessage()); } return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(SHOW_TIMESTAMP_DISPLAY)) { System.out.println("Current time format: " + timeFormat); return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(SHOW_FETCH_SIZE)) { System.out.println("Current fetch size: " + fetchSize); return OperationResult.CONTINUE_OPER; } if (specialCmd.startsWith(IMPORT_CMD)) { String[] values = specialCmd.split(" "); if (values.length != 2) { System.out.println(String.format( "Please input like: import /User/myfile. " + "Noted that your file path cannot contain any space character)")); return OperationResult.CONTINUE_OPER; } try { System.out.println(cmd.split(" ")[1]); ImportCsv.importCsvFromFile(host, port, username, password, cmd.split(" ")[1], connection.getTimeZone()); } catch (SQLException e) { System.out.println( String .format("Failed to import from %s because %s", cmd.split(" ")[1], e.getMessage())); } catch (TException e) { System.out.println("Cannot connect to server"); } return OperationResult.CONTINUE_OPER; } Statement statement = null; long startTime = System.currentTimeMillis(); try { ZoneId zoneId = ZoneId.of(connection.getTimeZone()); statement = connection.createStatement(); statement.setFetchSize(fetchSize); boolean hasResultSet = statement.execute(cmd.trim()); if (hasResultSet) { ResultSet resultSet = statement.getResultSet(); output(resultSet, printToConsole, cmd.trim(), zoneId); } System.out.println("Execute successfully. Type `help` to get more information."); } catch (Exception e) { System.out.println("Msg: " + e.getMessage()); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { System.out.println("Cannot close statement because: " + e.getMessage()); } } } long costTime = System.currentTimeMillis() - startTime; System.out.println(String.format("It costs %.3fs", costTime / 1000.0)); return OperationResult.NO_OPER; } static void output(ResultSet res, boolean printToConsole, String statement, ZoneId zoneId); } | @Test public void testHandleInputInputCmd() { assertEquals(AbstractClient.handleInputInputCmd(AbstractClient.EXIT_COMMAND, connection), OperationResult.RETURN_OPER); assertEquals(AbstractClient.handleInputInputCmd(AbstractClient.QUIT_COMMAND, connection), OperationResult.RETURN_OPER); assertEquals( AbstractClient.handleInputInputCmd(AbstractClient.SHOW_METADATA_COMMAND, connection), OperationResult.CONTINUE_OPER); assertEquals(AbstractClient .handleInputInputCmd(String.format("%s=", AbstractClient.SET_TIMESTAMP_DISPLAY), connection), OperationResult.CONTINUE_OPER); assertEquals(AbstractClient .handleInputInputCmd(String.format("%s=xxx", AbstractClient.SET_TIMESTAMP_DISPLAY), connection), OperationResult.CONTINUE_OPER); assertEquals(AbstractClient .handleInputInputCmd(String.format("%s=default", AbstractClient.SET_TIMESTAMP_DISPLAY), connection), OperationResult.CONTINUE_OPER); testSetTimeFormat(); assertEquals( AbstractClient.handleInputInputCmd(String.format("%s=", AbstractClient.SET_MAX_DISPLAY_NUM), connection), OperationResult.CONTINUE_OPER); assertEquals(AbstractClient .handleInputInputCmd(String.format("%s=xxx", AbstractClient.SET_MAX_DISPLAY_NUM), connection), OperationResult.CONTINUE_OPER); assertEquals(AbstractClient .handleInputInputCmd(String.format("%s=1", AbstractClient.SET_MAX_DISPLAY_NUM), connection), OperationResult.CONTINUE_OPER); testSetMaxDisplayNumber(); assertEquals(AbstractClient.handleInputInputCmd(AbstractClient.SHOW_TIMEZONE, connection), OperationResult.CONTINUE_OPER); assertEquals( AbstractClient.handleInputInputCmd(AbstractClient.SHOW_TIMESTAMP_DISPLAY, connection), OperationResult.CONTINUE_OPER); assertEquals(AbstractClient.handleInputInputCmd(AbstractClient.SHOW_FETCH_SIZE, connection), OperationResult.CONTINUE_OPER); assertEquals(AbstractClient .handleInputInputCmd(String.format("%s=", AbstractClient.SET_TIME_ZONE), connection), OperationResult.CONTINUE_OPER); assertEquals( AbstractClient.handleInputInputCmd(String.format("%s=+08:00", AbstractClient.SET_TIME_ZONE), connection), OperationResult.CONTINUE_OPER); assertEquals( AbstractClient .handleInputInputCmd(String.format("%s=", AbstractClient.SET_FETCH_SIZE), connection), OperationResult.CONTINUE_OPER); assertEquals( AbstractClient.handleInputInputCmd(String.format("%s=111", AbstractClient.SET_FETCH_SIZE), connection), OperationResult.CONTINUE_OPER); } |
IoTDBStatement implements Statement { @Override public boolean execute(String sql) throws SQLException { checkConnection("execute"); isClosed = false; try { return executeSQL(sql); } catch (TException e) { boolean flag = connection.reconnect(); reInit(); if (flag) { try { return executeSQL(sql); } catch (TException e2) { throw new SQLException( String.format("Fail to execute %s after reconnecting. please check server status", sql)); } } else { throw new SQLException(String .format("Fail to reconnect to server when executing %s. please check server status", sql)); } } } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); } | @SuppressWarnings("resource") @Test(expected = SQLException.class) public void testExecuteSQL1() throws SQLException { IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, zoneID); stmt.execute("show timeseries"); } |
IoTDBStatement implements Statement { @Override public int getFetchSize() throws SQLException { checkConnection("getFetchSize"); return fetchSize; } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); } | @SuppressWarnings("resource") @Test public void testSetFetchSize3() throws SQLException { final int fetchSize = 10000; IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, fetchSize, zoneID); assertEquals(fetchSize, stmt.getFetchSize()); } |
IoTDBStatement implements Statement { @Override public void setFetchSize(int fetchSize) throws SQLException { checkConnection("setFetchSize"); if (fetchSize < 0) { throw new SQLException(String.format("fetchSize %d must be >= 0!", fetchSize)); } this.fetchSize = fetchSize == 0 ? Config.fetchSize : fetchSize; } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); } | @SuppressWarnings("resource") @Test(expected = SQLException.class) public void testSetFetchSize4() throws SQLException { IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, zoneID); stmt.setFetchSize(-1); } |
IoTDBStatement implements Statement { @Override public void setMaxRows(int num) throws SQLException { checkConnection("setMaxRows"); if (num < 0) { throw new SQLException(String.format("maxRows %d must be >= 0!", num)); } this.maxRows = num; } IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
int fetchSize, ZoneId zoneId); IoTDBStatement(IoTDBConnection connection, TSIService.Iface client,
TS_SessionHandle sessionHandle,
ZoneId zoneId); @Override boolean isWrapperFor(Class<?> iface); @Override T unwrap(Class<T> iface); @Override void addBatch(String sql); @Override void cancel(); @Override void clearBatch(); @Override void clearWarnings(); @Override void close(); @Override void closeOnCompletion(); @Override boolean execute(String sql); @Override boolean execute(String arg0, int arg1); @Override boolean execute(String arg0, int[] arg1); @Override boolean execute(String arg0, String[] arg1); @Override int[] executeBatch(); @Override ResultSet executeQuery(String sql); @Override int executeUpdate(String sql); @Override int executeUpdate(String arg0, int arg1); @Override int executeUpdate(String arg0, int[] arg1); @Override int executeUpdate(String arg0, String[] arg1); @Override Connection getConnection(); @Override int getFetchDirection(); @Override void setFetchDirection(int direction); @Override int getFetchSize(); @Override void setFetchSize(int fetchSize); @Override ResultSet getGeneratedKeys(); @Override int getMaxFieldSize(); @Override void setMaxFieldSize(int arg0); @Override int getMaxRows(); @Override void setMaxRows(int num); @Override boolean getMoreResults(); @Override boolean getMoreResults(int arg0); @Override int getQueryTimeout(); @Override void setQueryTimeout(int seconds); @Override ResultSet getResultSet(); @Override int getResultSetConcurrency(); @Override int getResultSetHoldability(); @Override int getResultSetType(); @Override int getUpdateCount(); @Override SQLWarning getWarnings(); @Override boolean isCloseOnCompletion(); @Override boolean isClosed(); @Override boolean isPoolable(); @Override void setPoolable(boolean arg0); @Override void setCursorName(String arg0); @Override void setEscapeProcessing(boolean enable); } | @SuppressWarnings("resource") @Test(expected = SQLException.class) public void testSetMaxRows2() throws SQLException { IoTDBStatement stmt = new IoTDBStatement(connection, client, sessHandle, zoneID); stmt.setMaxRows(-1); } |
IoTDBMetadataResultMetadata implements ResultSetMetaData { @Override public int getColumnCount() throws SQLException { if (showLabels == null || showLabels.length == 0) { throw new SQLException("No column exists"); } return showLabels.length; } IoTDBMetadataResultMetadata(String[] showLabels); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); } | @Test public void testGetColumnCount() throws SQLException { boolean flag = false; try { metadata = new IoTDBMetadataResultMetadata(null); assertEquals((long) metadata.getColumnCount(), 0); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { String[] nullArray = {}; metadata = new IoTDBMetadataResultMetadata(nullArray); assertEquals((long) metadata.getColumnCount(), 0); } catch (Exception e) { flag = true; } assertEquals(flag, true); metadata = new IoTDBMetadataResultMetadata(cols); assertEquals((long) metadata.getColumnCount(), cols.length); } |
IoTDBMetadataResultMetadata implements ResultSetMetaData { @Override public String getColumnName(int column) throws SQLException { return getColumnLabel(column); } IoTDBMetadataResultMetadata(String[] showLabels); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); } | @Test public void testGetColumnName() throws SQLException { boolean flag = false; metadata = new IoTDBMetadataResultMetadata(null); try { metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); try { String[] nullArray = {}; metadata = new IoTDBMetadataResultMetadata(nullArray); metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); metadata = new IoTDBMetadataResultMetadata(cols); try { metadata.getColumnName(0); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { metadata.getColumnName(cols.length + 1); } catch (Exception e) { flag = true; } assertEquals(flag, true); for (int i = 1; i <= cols.length; i++) { assertEquals(metadata.getColumnName(i), cols[i - 1]); } } |
IoTDBResultMetadata implements ResultSetMetaData { @Override public int getColumnCount() throws SQLException { if (columnInfoList == null || columnInfoList.size() == 0) { throw new SQLException("No column exists"); } return columnInfoList.size(); } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); } | @Test public void testGetColumnCount() throws SQLException { metadata = new IoTDBResultMetadata(null, null, null); boolean flag = false; try { metadata.getColumnCount(); } catch (Exception e) { flag = true; } assertEquals(flag, true); List<String> columnInfoList = new ArrayList<>(); flag = false; try { metadata = new IoTDBResultMetadata(columnInfoList, null, null); metadata.getColumnCount(); } catch (Exception e) { flag = true; } assertEquals(flag, true); columnInfoList.add("root.a.b.c"); assertEquals(metadata.getColumnCount(), 1); } |
IoTDBResultMetadata implements ResultSetMetaData { @Override public String getColumnName(int column) throws SQLException { return getColumnLabel(column); } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); } | @Test public void testGetColumnName() throws SQLException { metadata = new IoTDBResultMetadata(null, null, null); boolean flag = false; try { metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); List<String> columnInfoList = new ArrayList<>(); metadata = new IoTDBResultMetadata(columnInfoList, null, null); flag = false; try { metadata.getColumnName(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); String[] colums = {"root.a.b.c1", "root.a.b.c2", "root.a.b.c3"}; metadata = new IoTDBResultMetadata(Arrays.asList(colums), null, null); flag = false; try { metadata.getColumnName(colums.length + 1); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { metadata.getColumnName(0); } catch (Exception e) { flag = true; } assertEquals(flag, true); for (int i = 1; i <= colums.length; i++) { assertEquals(metadata.getColumnLabel(i), colums[i - 1]); } } |
IoTDBResultMetadata implements ResultSetMetaData { @Override public int getColumnType(int column) throws SQLException { if (columnInfoList == null || columnInfoList.size() == 0) { throw new SQLException("No column exists"); } if (column > columnInfoList.size()) { throw new SQLException(String.format("column %d does not exist", column)); } if (column <= 0) { throw new SQLException(String.format("column index should start from 1", column)); } if (column == 1) { return Types.TIMESTAMP; } String columnType = columnTypeList.get(column - 2); switch (columnType.toUpperCase()) { case "BOOLEAN": return Types.BOOLEAN; case "INT32": return Types.INTEGER; case "INT64": return Types.BIGINT; case "FLOAT": return Types.FLOAT; case "DOUBLE": return Types.DOUBLE; case "TEXT": return Types.VARCHAR; default: break; } return 0; } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); } | @Test public void testGetColumnType() throws SQLException { metadata = new IoTDBResultMetadata(null, null, null); boolean flag = false; try { metadata.getColumnType(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); List<String> columnInfoList = new ArrayList<>(); metadata = new IoTDBResultMetadata(columnInfoList, null, null); flag = false; try { metadata.getColumnType(1); } catch (Exception e) { flag = true; } assertEquals(flag, true); String[] columns = {"timestamp", "root.a.b.boolean", "root.a.b.int32", "root.a.b.int64", "root.a.b.float", "root.a.b.double", "root.a.b.text"}; String[] typesString = {"BOOLEAN", "INT32", "INT64", "FLOAT", "DOUBLE", "TEXT"}; int[] types = {Types.BOOLEAN, Types.INTEGER, Types.BIGINT, Types.FLOAT, Types.DOUBLE, Types.VARCHAR}; metadata = new IoTDBResultMetadata(Arrays.asList(columns), null, Arrays.asList(typesString)); flag = false; try { metadata.getColumnType(columns.length + 1); } catch (Exception e) { flag = true; } assertEquals(flag, true); flag = false; try { metadata.getColumnType(0); } catch (Exception e) { flag = true; } assertEquals(flag, true); assertEquals(metadata.getColumnType(1), Types.TIMESTAMP); for (int i = 1; i <= types.length; i++) { assertEquals(metadata.getColumnType(i + 1), types[i - 1]); } } |
IoTDBResultMetadata implements ResultSetMetaData { @Override public String getColumnTypeName(int arg0) throws SQLException { return operationType; } IoTDBResultMetadata(List<String> columnInfoList, String operationType,
List<String> columnTypeList); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override String getCatalogName(int arg0); @Override String getColumnClassName(int arg0); @Override int getColumnCount(); @Override int getColumnDisplaySize(int arg0); @Override String getColumnLabel(int column); @Override String getColumnName(int column); @Override int getColumnType(int column); @Override String getColumnTypeName(int arg0); @Override int getPrecision(int arg0); @Override int getScale(int arg0); @Override String getSchemaName(int arg0); @Override String getTableName(int arg0); @Override boolean isAutoIncrement(int arg0); @Override boolean isCaseSensitive(int arg0); @Override boolean isCurrency(int arg0); @Override boolean isDefinitelyWritable(int arg0); @Override int isNullable(int arg0); @Override boolean isReadOnly(int arg0); @Override boolean isSearchable(int arg0); @Override boolean isSigned(int arg0); @Override boolean isWritable(int arg0); } | @Test public void testGetColumnTypeName() throws SQLException { String operationType = "sum"; metadata = new IoTDBResultMetadata(null, operationType, null); assertEquals(metadata.getColumnTypeName(1), operationType); } |
FloatDecoder extends Decoder { @Override public float readFloat(ByteBuffer buffer) { readMaxPointValue(buffer); int value = decoder.readInt(buffer); double result = value / maxPointValue; return (float) result; } FloatDecoder(TSEncoding encodingType, TSDataType dataType); @Override float readFloat(ByteBuffer buffer); @Override double readDouble(ByteBuffer buffer); @Override boolean hasNext(ByteBuffer buffer); @Override Binary readBinary(ByteBuffer buffer); @Override boolean readBoolean(ByteBuffer buffer); @Override short readShort(ByteBuffer buffer); @Override int readInt(ByteBuffer buffer); @Override long readLong(ByteBuffer buffer); @Override void reset(); } | @Test public void test() throws Exception { float value = 7.101f; Encoder encoder = new FloatEncoder(TSEncoding.RLE, TSDataType.FLOAT, 3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.encode(value, baos); encoder.flush(baos); encoder.encode(value + 2, baos); encoder.flush(baos); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Decoder decoder1 = new FloatDecoder(TSEncoding.RLE, TSDataType.FLOAT); Decoder decoder2 = new FloatDecoder(TSEncoding.RLE, TSDataType.FLOAT); float value1_ = decoder1.readFloat(buffer); float value2_ = decoder2.readFloat(buffer); assertEquals(value, value1_, delta); assertEquals(value + 2, value2_, delta); LOGGER.debug("{} LOGGER.debug("{} } |
IoTDBConnection implements Connection { public void setTimeZone(String zoneId) throws TException, IoTDBSQLException { TSSetTimeZoneReq req = new TSSetTimeZoneReq(zoneId); TSSetTimeZoneResp resp = client.setTimeZone(req); Utils.verifySuccess(resp.getStatus()); this.zoneId = ZoneId.of(zoneId); } IoTDBConnection(); IoTDBConnection(String url, Properties info); static TSIService.Iface newSynchronizedClient(TSIService.Iface client); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override void abort(Executor arg0); @Override void clearWarnings(); @Override void close(); @Override void commit(); @Override Array createArrayOf(String arg0, Object[] arg1); @Override Blob createBlob(); @Override Clob createClob(); @Override NClob createNClob(); @Override SQLXML createSQLXML(); @Override Statement createStatement(); @Override Statement createStatement(int resultSetType, int resultSetConcurrency); @Override Statement createStatement(int arg0, int arg1, int arg2); @Override Struct createStruct(String arg0, Object[] arg1); @Override boolean getAutoCommit(); @Override void setAutoCommit(boolean arg0); @Override String getCatalog(); @Override void setCatalog(String arg0); @Override Properties getClientInfo(); @Override void setClientInfo(Properties arg0); @Override String getClientInfo(String arg0); @Override int getHoldability(); @Override void setHoldability(int arg0); @Override DatabaseMetaData getMetaData(); @Override int getNetworkTimeout(); @Override String getSchema(); @Override void setSchema(String arg0); @Override int getTransactionIsolation(); @Override void setTransactionIsolation(int arg0); @Override Map<String, Class<?>> getTypeMap(); @Override void setTypeMap(Map<String, Class<?>> arg0); @Override SQLWarning getWarnings(); @Override boolean isClosed(); @Override boolean isReadOnly(); @Override void setReadOnly(boolean arg0); @Override boolean isValid(int arg0); @Override String nativeSQL(String arg0); @Override CallableStatement prepareCall(String arg0); @Override CallableStatement prepareCall(String arg0, int arg1, int arg2); @Override CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3); @Override PreparedStatement prepareStatement(String sql); @Override PreparedStatement prepareStatement(String sql, int autoGeneratedKeys); @Override PreparedStatement prepareStatement(String sql, int[] columnIndexes); @Override PreparedStatement prepareStatement(String sql, String[] columnNames); @Override PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency); @Override PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability); @Override void releaseSavepoint(Savepoint arg0); @Override void rollback(); @Override void rollback(Savepoint arg0); @Override void setClientInfo(String arg0, String arg1); @Override void setNetworkTimeout(Executor arg0, int arg1); @Override Savepoint setSavepoint(); @Override Savepoint setSavepoint(String arg0); boolean reconnect(); String getTimeZone(); void setTimeZone(String zoneId); ServerProperties getServerProperties(); TSProtocolVersion getProtocol(); void setProtocol(TSProtocolVersion protocol); public TSIService.Iface client; public TS_SessionHandle sessionHandle; } | @Test public void testSetTimeZone() throws TException, IoTDBSQLException { String timeZone = "Asia/Shanghai"; when(client.setTimeZone(any(TSSetTimeZoneReq.class))) .thenReturn(new TSSetTimeZoneResp(Status_SUCCESS)); connection.client = client; connection.setTimeZone(timeZone); assertEquals(connection.getTimeZone(), timeZone); } |
IoTDBConnection implements Connection { public String getTimeZone() throws TException, IoTDBSQLException { if (zoneId != null) { return zoneId.toString(); } TSGetTimeZoneResp resp = client.getTimeZone(); Utils.verifySuccess(resp.getStatus()); return resp.getTimeZone(); } IoTDBConnection(); IoTDBConnection(String url, Properties info); static TSIService.Iface newSynchronizedClient(TSIService.Iface client); @Override boolean isWrapperFor(Class<?> arg0); @Override T unwrap(Class<T> arg0); @Override void abort(Executor arg0); @Override void clearWarnings(); @Override void close(); @Override void commit(); @Override Array createArrayOf(String arg0, Object[] arg1); @Override Blob createBlob(); @Override Clob createClob(); @Override NClob createNClob(); @Override SQLXML createSQLXML(); @Override Statement createStatement(); @Override Statement createStatement(int resultSetType, int resultSetConcurrency); @Override Statement createStatement(int arg0, int arg1, int arg2); @Override Struct createStruct(String arg0, Object[] arg1); @Override boolean getAutoCommit(); @Override void setAutoCommit(boolean arg0); @Override String getCatalog(); @Override void setCatalog(String arg0); @Override Properties getClientInfo(); @Override void setClientInfo(Properties arg0); @Override String getClientInfo(String arg0); @Override int getHoldability(); @Override void setHoldability(int arg0); @Override DatabaseMetaData getMetaData(); @Override int getNetworkTimeout(); @Override String getSchema(); @Override void setSchema(String arg0); @Override int getTransactionIsolation(); @Override void setTransactionIsolation(int arg0); @Override Map<String, Class<?>> getTypeMap(); @Override void setTypeMap(Map<String, Class<?>> arg0); @Override SQLWarning getWarnings(); @Override boolean isClosed(); @Override boolean isReadOnly(); @Override void setReadOnly(boolean arg0); @Override boolean isValid(int arg0); @Override String nativeSQL(String arg0); @Override CallableStatement prepareCall(String arg0); @Override CallableStatement prepareCall(String arg0, int arg1, int arg2); @Override CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3); @Override PreparedStatement prepareStatement(String sql); @Override PreparedStatement prepareStatement(String sql, int autoGeneratedKeys); @Override PreparedStatement prepareStatement(String sql, int[] columnIndexes); @Override PreparedStatement prepareStatement(String sql, String[] columnNames); @Override PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency); @Override PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability); @Override void releaseSavepoint(Savepoint arg0); @Override void rollback(); @Override void rollback(Savepoint arg0); @Override void setClientInfo(String arg0, String arg1); @Override void setNetworkTimeout(Executor arg0, int arg1); @Override Savepoint setSavepoint(); @Override Savepoint setSavepoint(String arg0); boolean reconnect(); String getTimeZone(); void setTimeZone(String zoneId); ServerProperties getServerProperties(); TSProtocolVersion getProtocol(); void setProtocol(TSProtocolVersion protocol); public TSIService.Iface client; public TS_SessionHandle sessionHandle; } | @Test public void testGetTimeZone() throws IoTDBSQLException, TException { String timeZone = "GMT+:08:00"; when(client.getTimeZone()).thenReturn(new TSGetTimeZoneResp(Status_SUCCESS, timeZone)); connection.client = client; assertEquals(connection.getTimeZone(), timeZone); } |
Subsets and Splits