repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/M.java
// public static <K, V> E<K, V> e(K k, V v) {
// return new E(k, v);
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/M.java
// public static M m() {
// return m(new LinkedHashMap<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/S.java
// public static <T> Set<T> set(T... ts) {
// return C.toSet(ts);
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
| import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.M.e;
import static ch.codebulb.lambdaomega.M.m;
import static ch.codebulb.lambdaomega.S.set;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test; | package ch.codebulb.lambdaomega;
/**
* Test cases for the {@link M} implementation for {@link SequentialI}.
*/
public class MBaseSequentialTest {
@Test
public void testConvert() {
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet());
assertEquals(m("a", 0).i("b", 1).i("c", 2).m, m("a", 0).i("b", 1).i("c", 2).toMap());
}
@Test
public void testCollection() {
assertEquals(0, m().size());
assertEquals(3, m("a", 0).i("b", 1).i("c", 2).size());
assertTrue(m().isEmpty());
assertFalse(m("a", 0).i("b", 1).i("c", 2).isEmpty());
assertEquals(set(), m("a", 0).i("b", 1).i("c", 2).clear());
}
@Test
public void testAdd() {
// Add individual elements
assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).Add(e("c", 2)).m);
assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).a(e("c", 2)).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).add(e("c", 2)));
assertEquals(EXPECTED_MAP, m(Number.class).Add(e("a", 0), e("b", 1), e("c", 2)).m);
assertEquals(EXPECTED_MAP, m(Number.class).a(e("a", 0), e("b", 1), e("c", 2)).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).add(e("a", 0), e("b", 1), e("c", 2)));
// Add all entries
assertEquals(EXPECTED_MAP, m(Number.class).AddAll(list(e("a", 0), e("b", 1), e("c", 2))).m);
assertEquals(EXPECTED_MAP, m(Number.class).A(list(e("a", 0), e("b", 1), e("c", 2))).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).addAll(list(e("a", 0), e("b", 1), e("c", 2))));
assertEquals(EXPECTED_MAP, m(Number.class).AddAll(list(e("a", 0), e("b", 1)), list(e("c", 2))).m);
assertEquals(EXPECTED_MAP, m(Number.class).A(list(e("a", 0), e("b", 1)), list(e("c", 2))).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).addAll(list(e("a", 0), e("b", 1)), list(e("c", 2))));
// Add all L entries | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/M.java
// public static <K, V> E<K, V> e(K k, V v) {
// return new E(k, v);
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/M.java
// public static M m() {
// return m(new LinkedHashMap<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/S.java
// public static <T> Set<T> set(T... ts) {
// return C.toSet(ts);
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
// Path: src/test/java/ch/codebulb/lambdaomega/MBaseSequentialTest.java
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.M.e;
import static ch.codebulb.lambdaomega.M.m;
import static ch.codebulb.lambdaomega.S.set;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_MAP;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
package ch.codebulb.lambdaomega;
/**
* Test cases for the {@link M} implementation for {@link SequentialI}.
*/
public class MBaseSequentialTest {
@Test
public void testConvert() {
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).i("c", 2).toSet());
assertEquals(m("a", 0).i("b", 1).i("c", 2).m, m("a", 0).i("b", 1).i("c", 2).toMap());
}
@Test
public void testCollection() {
assertEquals(0, m().size());
assertEquals(3, m("a", 0).i("b", 1).i("c", 2).size());
assertTrue(m().isEmpty());
assertFalse(m("a", 0).i("b", 1).i("c", 2).isEmpty());
assertEquals(set(), m("a", 0).i("b", 1).i("c", 2).clear());
}
@Test
public void testAdd() {
// Add individual elements
assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).Add(e("c", 2)).m);
assertEquals(EXPECTED_MAP, m("a", 0).i("b", 1).a(e("c", 2)).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m("a", 0).i("b", 1).add(e("c", 2)));
assertEquals(EXPECTED_MAP, m(Number.class).Add(e("a", 0), e("b", 1), e("c", 2)).m);
assertEquals(EXPECTED_MAP, m(Number.class).a(e("a", 0), e("b", 1), e("c", 2)).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).add(e("a", 0), e("b", 1), e("c", 2)));
// Add all entries
assertEquals(EXPECTED_MAP, m(Number.class).AddAll(list(e("a", 0), e("b", 1), e("c", 2))).m);
assertEquals(EXPECTED_MAP, m(Number.class).A(list(e("a", 0), e("b", 1), e("c", 2))).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).addAll(list(e("a", 0), e("b", 1), e("c", 2))));
assertEquals(EXPECTED_MAP, m(Number.class).AddAll(list(e("a", 0), e("b", 1)), list(e("c", 2))).m);
assertEquals(EXPECTED_MAP, m(Number.class).A(list(e("a", 0), e("b", 1)), list(e("c", 2))).m);
assertEquals(set(e("a", 0), e("b", 1), e("c", 2)), m(Number.class).addAll(list(e("a", 0), e("b", 1)), list(e("c", 2))));
// Add all L entries | assertEquals(EXPECTED_MAP, m(Number.class).AddAll(l(e("a", 0), e("b", 1), e("c", 2))).m); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/LBaseTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test; | package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() { | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() { | L.TEST_DISABLE_HELPER_MAP_CONVERSION = true; |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/LBaseTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test; | package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() { | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() { | assertTrue(l().equals(l())); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/LBaseTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test; | package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2))); | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2))); | assertTrue(list(0, 1, 2).equals(l(0, 1, 2).l)); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/LBaseTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test; | package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2)));
assertTrue(list(0, 1, 2).equals(l(0, 1, 2).l));
| // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2)));
assertTrue(list(0, 1, 2).equals(l(0, 1, 2).l));
| assertEquals("L[0, 1, 2]", "L" + EXPECTED_LIST.toString(), l(0, 1, 2).toString()); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/LBaseTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test; | package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2)));
assertTrue(list(0, 1, 2).equals(l(0, 1, 2).l));
| // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2)));
assertTrue(list(0, 1, 2).equals(l(0, 1, 2).l));
| assertEquals("L[0, 1, 2]", "L" + EXPECTED_LIST.toString(), l(0, 1, 2).toString()); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/LBaseTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test; | package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2)));
assertTrue(list(0, 1, 2).equals(l(0, 1, 2).l));
assertEquals("L[0, 1, 2]", "L" + EXPECTED_LIST.toString(), l(0, 1, 2).toString());
}
@Test
public void testStream() {
assertFalse(l().stream().isParallel());
assertFalse(l().Seq().stream().isParallel());
assertTrue(l().Par().stream().isParallel());
}
@Test
public void testWithDefault() { | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
package ch.codebulb.lambdaomega;
/**
* Basic test cases for {@link L}.
*/
public class LBaseTest {
@BeforeClass
public static void beforeClass() {
L.TEST_DISABLE_HELPER_MAP_CONVERSION = true;
}
@Test
public void testObject() {
assertTrue(l().equals(l()));
assertTrue(l(0, 1, 2).equals(l(0, 1, 2)));
assertFalse(l(9, 1, 2).equals(l(0, 1, 2)));
assertTrue(list(0, 1, 2).equals(l(0, 1, 2).l));
assertEquals("L[0, 1, 2]", "L" + EXPECTED_LIST.toString(), l(0, 1, 2).toString());
}
@Test
public void testStream() {
assertFalse(l().stream().isParallel());
assertFalse(l().Seq().stream().isParallel());
assertTrue(l().Par().stream().isParallel());
}
@Test
public void testWithDefault() { | I<Integer, List<Integer>> listWithDefault = l(list(5), list(6), list(7)).WithDefault(it -> list(it * 2)); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/LBaseTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test; | @Test
public void testWithDefault() {
I<Integer, List<Integer>> listWithDefault = l(list(5), list(6), list(7)).WithDefault(it -> list(it * 2));
assertEquals(list(5), listWithDefault.get(0));
assertEquals(list(10), listWithDefault.get(5));
listWithDefault.get(0).add(9);
// keep previously created element
assertEquals(list(5, 9), listWithDefault.get(0));
listWithDefault.get(5).add(9);
// return a newly created element
assertEquals(list(10), listWithDefault.get(5));
}
@Test
public void testLiteralConstruction() {
assertEquals(L.class, l().getClass());
assertEquals(new ArrayList<Integer>(), l().l);
assertEquals(new ArrayList<Integer>(), l().toList());
assertEquals(new ArrayList<Integer>(), l().to(ArrayList.class));
assertEquals(new ArrayList<Integer>(), list());
assertEquals(EXPECTED_LIST, l(0, 1, 2).l);
assertEquals(EXPECTED_LIST, list(0, 1, 2));
assertEquals(EXPECTED_LIST, L(EXPECTED_LIST).l);
assertEquals(EXPECTED_LIST, l(new Integer[]{0, 1, 2}).l);
assertEquals(EXPECTED_LIST, l(Integer.class).a(0, 1, 2).l);
| // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> L(Stream<T> stream) {
// return new L(stream.collect(Collectors.toList()));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> L<T> l() {
// return new L<>(new ArrayList<>());
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/LBaseTest.java
import static ch.codebulb.lambdaomega.L.L;
import static ch.codebulb.lambdaomega.L.l;
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.EXPECTED_NESTED_LIST;
import static ch.codebulb.lambdaomega.TestUtil.assertEquals;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
@Test
public void testWithDefault() {
I<Integer, List<Integer>> listWithDefault = l(list(5), list(6), list(7)).WithDefault(it -> list(it * 2));
assertEquals(list(5), listWithDefault.get(0));
assertEquals(list(10), listWithDefault.get(5));
listWithDefault.get(0).add(9);
// keep previously created element
assertEquals(list(5, 9), listWithDefault.get(0));
listWithDefault.get(5).add(9);
// return a newly created element
assertEquals(list(10), listWithDefault.get(5));
}
@Test
public void testLiteralConstruction() {
assertEquals(L.class, l().getClass());
assertEquals(new ArrayList<Integer>(), l().l);
assertEquals(new ArrayList<Integer>(), l().toList());
assertEquals(new ArrayList<Integer>(), l().to(ArrayList.class));
assertEquals(new ArrayList<Integer>(), list());
assertEquals(EXPECTED_LIST, l(0, 1, 2).l);
assertEquals(EXPECTED_LIST, list(0, 1, 2));
assertEquals(EXPECTED_LIST, L(EXPECTED_LIST).l);
assertEquals(EXPECTED_LIST, l(new Integer[]{0, 1, 2}).l);
assertEquals(EXPECTED_LIST, l(Integer.class).a(0, 1, 2).l);
| assertEquals(EXPECTED_NESTED_LIST, l(l(0, 1, 2).l, l(0, 1, 2).l).l); |
codebulb/LambdaOmega | src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java | // Path: src/main/java/ch/codebulb/lambdaomega/U.java
// public class U {
// private U() {}
//
// /**
// * Prints the object provided to the standard output.
// */
// public static void println(Object out) {
// System.out.println(out);
// }
//
// /**
// * Creates a {@link Choice}.
// */
// public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) {
// return new Choice<>(predicate, function);
// }
//
// /**
// * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>.
// */
// public static <T> boolean any(Predicate<T> predicate, T... candidates) {
// return C.toStream(candidates).anyMatch(predicate);
// }
//
// /**
// * Represents a simple choice tree. This structure can be used as an alternative to
// * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/>
// *
// * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class.
// * It's best practice to statically import this function in client code.
// *
// * @param <T> the return type
// */
// public static class Choice<T> {
// private final L<V2<Boolean, Supplier<T>>> choices;
//
// Choice(boolean predicate, Supplier<T> function) {
// choices = l(v(predicate, function));
// }
//
// /**
// * Adds an "or" joined option.
// */
// public Choice<T> Or(boolean predicate, Supplier<T> function) {
// choices.a(v(predicate, function));
// return this;
// }
//
// /**
// * Returns the result of the first "or" option which evaluates to <code>true</code> or the default value provided if there is no valid option.
// */
// public T or(T defaultValue) {
// V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true);
// return choice != null ? choice.get1().get() : defaultValue;
// }
//
// /**
// * Returns the result of the first "or" option which evaluates to <code>true</code> or <code>null</code> if there is no valid option.
// */
// public T orNull() {
// return or(null);
// }
//
// /**
// * Returns the result of the first "or" option which evaluates to <code>true</code> or throws a {@link NoValidChoiceException} if there is no valid option.
// */
// public T orThrow() throws NoValidChoiceException {
// V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true);
// if (choice != null) {
// return choice.get1().get();
// }
// else {
// throw new NoValidChoiceException();
// }
// }
//
// /**
// * Signals that none of the {@link Choice}s provided resolved to <code>true</code>.
// */
// public static class NoValidChoiceException extends Exception {
//
// }
// }
// }
| import ch.codebulb.lambdaomega.U; | package ch.codebulb.lambdaomega.abstractions;
/**
* Base class for all instantiable classes. Provides miscellaneous instance util functionality.
* It's a design goal to keep this class very slim.
*/
public abstract class OmegaObject {
/**
* Prints itself to the standard output.
*/
public void println() { | // Path: src/main/java/ch/codebulb/lambdaomega/U.java
// public class U {
// private U() {}
//
// /**
// * Prints the object provided to the standard output.
// */
// public static void println(Object out) {
// System.out.println(out);
// }
//
// /**
// * Creates a {@link Choice}.
// */
// public static <T> Choice<T> Choose(boolean predicate, Supplier<T> function) {
// return new Choice<>(predicate, function);
// }
//
// /**
// * Returns <code>true</code> if the <code>predicate</code> provided is <code>true</code> for at least one of the <code>candidates</code>.
// */
// public static <T> boolean any(Predicate<T> predicate, T... candidates) {
// return C.toStream(candidates).anyMatch(predicate);
// }
//
// /**
// * Represents a simple choice tree. This structure can be used as an alternative to
// * an <code>if</code> / <code>else if</code> / <code>else</code> structure with optionally enforced choice.<p/>
// *
// * The constructor of this class is not visible; use the convenience {@link U#Choose(boolean, Supplier)} method to create a new instance of this class.
// * It's best practice to statically import this function in client code.
// *
// * @param <T> the return type
// */
// public static class Choice<T> {
// private final L<V2<Boolean, Supplier<T>>> choices;
//
// Choice(boolean predicate, Supplier<T> function) {
// choices = l(v(predicate, function));
// }
//
// /**
// * Adds an "or" joined option.
// */
// public Choice<T> Or(boolean predicate, Supplier<T> function) {
// choices.a(v(predicate, function));
// return this;
// }
//
// /**
// * Returns the result of the first "or" option which evaluates to <code>true</code> or the default value provided if there is no valid option.
// */
// public T or(T defaultValue) {
// V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true);
// return choice != null ? choice.get1().get() : defaultValue;
// }
//
// /**
// * Returns the result of the first "or" option which evaluates to <code>true</code> or <code>null</code> if there is no valid option.
// */
// public T orNull() {
// return or(null);
// }
//
// /**
// * Returns the result of the first "or" option which evaluates to <code>true</code> or throws a {@link NoValidChoiceException} if there is no valid option.
// */
// public T orThrow() throws NoValidChoiceException {
// V2<Boolean, Supplier<T>> choice = choices.find(it -> it.get0() == true);
// if (choice != null) {
// return choice.get1().get();
// }
// else {
// throw new NoValidChoiceException();
// }
// }
//
// /**
// * Signals that none of the {@link Choice}s provided resolved to <code>true</code>.
// */
// public static class NoValidChoiceException extends Exception {
//
// }
// }
// }
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/OmegaObject.java
import ch.codebulb.lambdaomega.U;
package ch.codebulb.lambdaomega.abstractions;
/**
* Base class for all instantiable classes. Provides miscellaneous instance util functionality.
* It's a design goal to keep this class very slim.
*/
public abstract class OmegaObject {
/**
* Prints itself to the standard output.
*/
public void println() { | U.println(this); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/VTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// class TestUtil {
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
// static {
// EXPECTED_LIST.add(0);
// EXPECTED_LIST.add(1);
// EXPECTED_LIST.add(2);
// }
//
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
// static {
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>();
// static {
// EXPECTED_MAP.put("a", 0);
// EXPECTED_MAP.put("b", 1);
// EXPECTED_MAP.put("c", 2);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>();
// static {
// EXPECTED_MAP_2_ELEMENTS.put("a", 0);
// EXPECTED_MAP_2_ELEMENTS.put("b", 1);
// }
//
// public static final Set<Integer> EXPECTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_SET.add(0);
// EXPECTED_SET.add(1);
// EXPECTED_SET.add(2);
// }
//
// public static final Set<Set<Integer>> EXPECTED_NESTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_NESTED_SET.add(EXPECTED_SET);
//
// Set<Integer> set2 = new LinkedHashSet<>();
// set2.add(3);
// set2.add(4);
// set2.add(5);
// EXPECTED_NESTED_SET.add(set2);
// }
//
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/V2.java
// public static <X, Y> V2<X, Y> v(X x, Y y) {
// return new V2(x, y);
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.*;
import static ch.codebulb.lambdaomega.V2.v;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test; | package ch.codebulb.lambdaomega;
public class VTest {
@Test
public void testBasics() { | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// class TestUtil {
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
// static {
// EXPECTED_LIST.add(0);
// EXPECTED_LIST.add(1);
// EXPECTED_LIST.add(2);
// }
//
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
// static {
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>();
// static {
// EXPECTED_MAP.put("a", 0);
// EXPECTED_MAP.put("b", 1);
// EXPECTED_MAP.put("c", 2);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>();
// static {
// EXPECTED_MAP_2_ELEMENTS.put("a", 0);
// EXPECTED_MAP_2_ELEMENTS.put("b", 1);
// }
//
// public static final Set<Integer> EXPECTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_SET.add(0);
// EXPECTED_SET.add(1);
// EXPECTED_SET.add(2);
// }
//
// public static final Set<Set<Integer>> EXPECTED_NESTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_NESTED_SET.add(EXPECTED_SET);
//
// Set<Integer> set2 = new LinkedHashSet<>();
// set2.add(3);
// set2.add(4);
// set2.add(5);
// EXPECTED_NESTED_SET.add(set2);
// }
//
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/V2.java
// public static <X, Y> V2<X, Y> v(X x, Y y) {
// return new V2(x, y);
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/VTest.java
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.*;
import static ch.codebulb.lambdaomega.V2.v;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
package ch.codebulb.lambdaomega;
public class VTest {
@Test
public void testBasics() { | assertTrue(v(0, "a").equals(v(0, "a"))); |
codebulb/LambdaOmega | src/test/java/ch/codebulb/lambdaomega/VTest.java | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// class TestUtil {
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
// static {
// EXPECTED_LIST.add(0);
// EXPECTED_LIST.add(1);
// EXPECTED_LIST.add(2);
// }
//
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
// static {
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>();
// static {
// EXPECTED_MAP.put("a", 0);
// EXPECTED_MAP.put("b", 1);
// EXPECTED_MAP.put("c", 2);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>();
// static {
// EXPECTED_MAP_2_ELEMENTS.put("a", 0);
// EXPECTED_MAP_2_ELEMENTS.put("b", 1);
// }
//
// public static final Set<Integer> EXPECTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_SET.add(0);
// EXPECTED_SET.add(1);
// EXPECTED_SET.add(2);
// }
//
// public static final Set<Set<Integer>> EXPECTED_NESTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_NESTED_SET.add(EXPECTED_SET);
//
// Set<Integer> set2 = new LinkedHashSet<>();
// set2.add(3);
// set2.add(4);
// set2.add(5);
// EXPECTED_NESTED_SET.add(set2);
// }
//
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/V2.java
// public static <X, Y> V2<X, Y> v(X x, Y y) {
// return new V2(x, y);
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
| import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.*;
import static ch.codebulb.lambdaomega.V2.v;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test; | package ch.codebulb.lambdaomega;
public class VTest {
@Test
public void testBasics() {
assertTrue(v(0, "a").equals(v(0, "a")));
assertFalse(v(1, "a").equals(v(0, "a")));
assertFalse(v(0, "b").equals(v(0, "a")));
assertEquals("(0, a)", v(0, "a").toString());
}
@Test
public void testConvert() { | // Path: src/main/java/ch/codebulb/lambdaomega/L.java
// public static <T> List<T> list(T... ts) {
// return l(ts).l;
// }
//
// Path: src/test/java/ch/codebulb/lambdaomega/TestUtil.java
// class TestUtil {
// public static final List<Integer> EXPECTED_LIST = new ArrayList<>();
// static {
// EXPECTED_LIST.add(0);
// EXPECTED_LIST.add(1);
// EXPECTED_LIST.add(2);
// }
//
// public static final List<List<Integer>> EXPECTED_NESTED_LIST = new ArrayList<>();
// static {
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// EXPECTED_NESTED_LIST.add(EXPECTED_LIST);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP = new LinkedHashMap<>();
// static {
// EXPECTED_MAP.put("a", 0);
// EXPECTED_MAP.put("b", 1);
// EXPECTED_MAP.put("c", 2);
// }
//
// public static final Map<String, Integer> EXPECTED_MAP_2_ELEMENTS = new LinkedHashMap<>();
// static {
// EXPECTED_MAP_2_ELEMENTS.put("a", 0);
// EXPECTED_MAP_2_ELEMENTS.put("b", 1);
// }
//
// public static final Set<Integer> EXPECTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_SET.add(0);
// EXPECTED_SET.add(1);
// EXPECTED_SET.add(2);
// }
//
// public static final Set<Set<Integer>> EXPECTED_NESTED_SET = new LinkedHashSet<>();
// static {
// EXPECTED_NESTED_SET.add(EXPECTED_SET);
//
// Set<Integer> set2 = new LinkedHashSet<>();
// set2.add(3);
// set2.add(4);
// set2.add(5);
// EXPECTED_NESTED_SET.add(set2);
// }
//
// public static <T> void assertEquals(T expected, T... actual) {
// Arrays.stream(actual).forEach(it -> Assert.assertEquals(expected, it));
// }
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/V2.java
// public static <X, Y> V2<X, Y> v(X x, Y y) {
// return new V2(x, y);
// }
//
// Path: src/main/java/ch/codebulb/lambdaomega/abstractions/I.java
// public interface I<K, V> {
// // We have to allow derived return values because we need that in V2
// /**
// * Invokes Map#get(Object) or invokes the function set by {@link #WithDefault(Function)} with the <code>key</code> provided,
// * if it would return <code>null</code> or the key is invalid.
// */
// public <VN extends V> VN get(K key);
//
// /**
// * @see #get(Object)
// */
// public default List<V> get(K... keys) {
// return C.toStream(keys).map(it -> this.<V> get(it)).collect(Collectors.toList());
// }
//
// /**
// * @see #get(Object)
// */
// public default List<V> getAll(Collection<K>... keys) {
// return C.toStream(keys).map(c -> C.toStream(c).map(it -> this.<V> get(it)).collect(Collectors.toList()))
// .flatMap(Collection::stream).collect(Collectors.toList());
// }
//
// // We have to allow derived return values because we need that in V2
// /**
// * @see Map#getOrDefault(Object, Object)
// */
// public <VN extends V> VN getOrDefault(K key, VN defaultValue);
//
// /**
// * Sets the function for creating a default value as an alternative to an otherwise unsuccessful {@link #get(Object)} invocation.
// *
// * @param defaultValue the new default value
// * @return <code>this (modified)</code>
// */
// public ReadonlyIndexedI<K, V> WithDefault(Function<K, V> defaultValue);
//
// /**
// * @see #get(Object)
// */
// public default L<V> g(K... keys) {
// return Get(keys);
// }
//
// /**
// * @see #get(Object)
// */
// public default V g(K key) {
// return get(key);
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> Get(K... keys) {
// return L(get(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> GetAll(Collection<K>... keys) {
// return L(getAll(keys));
// }
//
// /**
// * @see #get(Object)
// */
// public default L<V> G(Collection<K>... keys) {
// return L(getAll(keys));
// }
// }
// Path: src/test/java/ch/codebulb/lambdaomega/VTest.java
import static ch.codebulb.lambdaomega.L.list;
import static ch.codebulb.lambdaomega.TestUtil.*;
import static ch.codebulb.lambdaomega.V2.v;
import ch.codebulb.lambdaomega.abstractions.I;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
package ch.codebulb.lambdaomega;
public class VTest {
@Test
public void testBasics() {
assertTrue(v(0, "a").equals(v(0, "a")));
assertFalse(v(1, "a").equals(v(0, "a")));
assertFalse(v(0, "b").equals(v(0, "a")));
assertEquals("(0, a)", v(0, "a").toString());
}
@Test
public void testConvert() { | assertEquals(list(v(0, "a"), v(1, "b"), v(1, "z")), v(0, "a").a(1, "b").a(1, "z").l); |
Archistar/archistar-smc | src/test/java/at/archistar/crypto/mac/BCShortenedMacTest.java | // Path: src/main/java/at/archistar/crypto/informationchecking/CevallosUSRSS.java
// public class CevallosUSRSS extends RabinBenOrRSS {
//
// /**
// * security constant for computing the tag length; means 128 bit
// */
// public static final int E = 128;
//
// private final MacHelper mac;
//
// private final int n;
//
// /**
// * Constructor.
// */
// public CevallosUSRSS(int n, int k, MacHelper mac, RandomSource rng) throws WeakSecurityException {
// super(k, mac, rng);
//
// this.n = n;
//
// if (!((k - 1) * 3 >= n) && ((k - 1) * 2 < n)) {
// throw new WeakSecurityException("this scheme only works when n/3 <= t < n/2 (where t = k-1)");
// }
//
// this.mac = mac;
// }
//
// /**
// * Computes the required MAC-tag-length to achieve a security of <i>e</i> bits.
// *
// * @param m the length of the message in bit (TODO: this should be the blocklength)
// * @param t amount of "defective" shares
// * @param e the security constant in bit
// * @return the amount of bytes the MAC-tags should have
// */
// public static int computeTagLength(int m, int t, int e) {
// int tagLengthBit = log2(t + 1) + log2(m) + 2 / (t + 1) * e + log2(e);
// return tagLengthBit / 8;
// }
//
// /**
// * Computes the integer logarithm base 2 of a given number.
// *
// * @param n the int to compute the logarithm for
// * @return the integer logarithm (whole number -> floor()) of the given number
// */
// private static int log2(int n) {
// if (n <= 0) {
// throw new IllegalArgumentException();
// }
//
// return 31 - Integer.numberOfLeadingZeros(n);
// }
//
// private int getAcceptedCount(InformationCheckingShare s1, InformationCheckingShare[] shares, boolean[][] accepts) {
//
// int counter = 0;
//
// for (InformationCheckingShare s2 : shares) {
// byte[] data = s1.getYValues();
// byte[] mac1 = s1.getMacs().get(s2.getId());
// byte[] mac2 = s2.getMacKeys().get(s1.getId());
//
// accepts[s1.getId()][s2.getId()] = mac.verifyMAC(data, mac1, mac2);
// if (accepts[s1.getId()][s2.getId()]) {
// counter++;
// }
// }
//
// return counter;
// }
//
// @Override
// public Map<Boolean, List<InformationCheckingShare>> checkShares(InformationCheckingShare[] cshares) {
//
// Queue<Integer> queue = new LinkedList<>();
// List<InformationCheckingShare> valid = new LinkedList<>();
//
// // accepts[i][j] = true means participant j accepts i
// boolean[][] accepts = new boolean[n + 1][n + 1];
// int a[] = new int[n + 1];
//
// for (InformationCheckingShare s1 : cshares) {
//
// a[s1.getId()] += getAcceptedCount(s1, cshares, accepts);
//
// if (a[s1.getId()] < k) {
// queue.add((int) s1.getId());
// } else {
// valid.add(s1);
// }
// }
//
// while (valid.size() >= k && !queue.isEmpty()) {
// int s1id = queue.poll();
// for (Iterator<InformationCheckingShare> it = valid.iterator(); it.hasNext(); ) {
// InformationCheckingShare s2 = it.next();
// if (accepts[s2.getId()][s1id]) {
// a[s2.getId()]--;
// if (a[s2.getId()] < k) {
// queue.add((int) s2.getId());
// it.remove();
// }
// }
// }
// }
//
// Map<Boolean, List<InformationCheckingShare>> res = new HashMap<>();
// res.put(Boolean.TRUE, valid);
// res.put(Boolean.FALSE, queue.stream().map(i -> cshares[i]).collect(Collectors.toList()));
//
// return res;
// }
//
// @Override
// public String toString() {
// return "Cevallos(" + k + "/" + n + ", " + mac + ")";
// }
// }
| import at.archistar.crypto.informationchecking.CevallosUSRSS;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Test; | package at.archistar.crypto.mac;
public class BCShortenedMacTest {
@Test
public void testHashVerifyCycle() throws NoSuchAlgorithmException, InvalidKeyException {
byte[] data = new byte[1024];
byte[] key = new byte[128];
| // Path: src/main/java/at/archistar/crypto/informationchecking/CevallosUSRSS.java
// public class CevallosUSRSS extends RabinBenOrRSS {
//
// /**
// * security constant for computing the tag length; means 128 bit
// */
// public static final int E = 128;
//
// private final MacHelper mac;
//
// private final int n;
//
// /**
// * Constructor.
// */
// public CevallosUSRSS(int n, int k, MacHelper mac, RandomSource rng) throws WeakSecurityException {
// super(k, mac, rng);
//
// this.n = n;
//
// if (!((k - 1) * 3 >= n) && ((k - 1) * 2 < n)) {
// throw new WeakSecurityException("this scheme only works when n/3 <= t < n/2 (where t = k-1)");
// }
//
// this.mac = mac;
// }
//
// /**
// * Computes the required MAC-tag-length to achieve a security of <i>e</i> bits.
// *
// * @param m the length of the message in bit (TODO: this should be the blocklength)
// * @param t amount of "defective" shares
// * @param e the security constant in bit
// * @return the amount of bytes the MAC-tags should have
// */
// public static int computeTagLength(int m, int t, int e) {
// int tagLengthBit = log2(t + 1) + log2(m) + 2 / (t + 1) * e + log2(e);
// return tagLengthBit / 8;
// }
//
// /**
// * Computes the integer logarithm base 2 of a given number.
// *
// * @param n the int to compute the logarithm for
// * @return the integer logarithm (whole number -> floor()) of the given number
// */
// private static int log2(int n) {
// if (n <= 0) {
// throw new IllegalArgumentException();
// }
//
// return 31 - Integer.numberOfLeadingZeros(n);
// }
//
// private int getAcceptedCount(InformationCheckingShare s1, InformationCheckingShare[] shares, boolean[][] accepts) {
//
// int counter = 0;
//
// for (InformationCheckingShare s2 : shares) {
// byte[] data = s1.getYValues();
// byte[] mac1 = s1.getMacs().get(s2.getId());
// byte[] mac2 = s2.getMacKeys().get(s1.getId());
//
// accepts[s1.getId()][s2.getId()] = mac.verifyMAC(data, mac1, mac2);
// if (accepts[s1.getId()][s2.getId()]) {
// counter++;
// }
// }
//
// return counter;
// }
//
// @Override
// public Map<Boolean, List<InformationCheckingShare>> checkShares(InformationCheckingShare[] cshares) {
//
// Queue<Integer> queue = new LinkedList<>();
// List<InformationCheckingShare> valid = new LinkedList<>();
//
// // accepts[i][j] = true means participant j accepts i
// boolean[][] accepts = new boolean[n + 1][n + 1];
// int a[] = new int[n + 1];
//
// for (InformationCheckingShare s1 : cshares) {
//
// a[s1.getId()] += getAcceptedCount(s1, cshares, accepts);
//
// if (a[s1.getId()] < k) {
// queue.add((int) s1.getId());
// } else {
// valid.add(s1);
// }
// }
//
// while (valid.size() >= k && !queue.isEmpty()) {
// int s1id = queue.poll();
// for (Iterator<InformationCheckingShare> it = valid.iterator(); it.hasNext(); ) {
// InformationCheckingShare s2 = it.next();
// if (accepts[s2.getId()][s1id]) {
// a[s2.getId()]--;
// if (a[s2.getId()] < k) {
// queue.add((int) s2.getId());
// it.remove();
// }
// }
// }
// }
//
// Map<Boolean, List<InformationCheckingShare>> res = new HashMap<>();
// res.put(Boolean.TRUE, valid);
// res.put(Boolean.FALSE, queue.stream().map(i -> cshares[i]).collect(Collectors.toList()));
//
// return res;
// }
//
// @Override
// public String toString() {
// return "Cevallos(" + k + "/" + n + ", " + mac + ")";
// }
// }
// Path: src/test/java/at/archistar/crypto/mac/BCShortenedMacTest.java
import at.archistar.crypto.informationchecking.CevallosUSRSS;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Test;
package at.archistar.crypto.mac;
public class BCShortenedMacTest {
@Test
public void testHashVerifyCycle() throws NoSuchAlgorithmException, InvalidKeyException {
byte[] data = new byte[1024];
byte[] key = new byte[128];
| MacHelper mac = new BCShortenedMacHelper(new BCPoly1305MacHelper(), CevallosUSRSS.computeTagLength(data.length, 1, CevallosUSRSS.E)); |
Archistar/archistar-smc | src/main/java/at/archistar/crypto/secretsharing/BaseSecretSharing.java | // Path: src/main/java/at/archistar/crypto/data/Share.java
// public interface Share extends Comparable<Share> {
//
// /** on-disk version of the share */
// int VERSION = 5;
//
// static void writeMap(DataOutputStream sout, Map<Byte, byte[]> map) throws IOException {
// sout.writeInt(map.size());
// for (Map.Entry<Byte, byte[]> e : map.entrySet()) {
// Byte key = e.getKey();
// byte[] value = e.getValue();
//
// sout.writeByte(key);
// sout.writeInt(value.length);
// sout.write(value);
// }
// }
//
// /**
// * @return the share's X-value (same as id)
// */
// int getX();
//
// /**
// * @return the share's id (same as x-value)
// */
// byte getId();
//
// /**
// * @return the share's main body (y-values)
// */
// @SuppressFBWarnings("EI_EXPOSE_REP")
// byte[] getYValues();
//
// /**
// * This returns a serialized form of the content (plus IC info) of the share.
// *
// * @return the share's byte[] representation containing all information
// * @throws IOException
// */
// byte[] getSerializedData() throws IOException;
//
// /**
// * This returns a Map of the metadata that are common to all share types;
// * the idea is that the getMetaData()-implementations in all the share types
// * first get this Map and then add their own special keys
// *
// * @return the metadata that are common to all shares
// */
// default HashMap<String, String> getCommonMetaData() {
// HashMap<String, String> res = new HashMap<>();
// res.put("archistar-share-type", getShareType());
// res.put("archistar-version", Integer.toString(VERSION));
// res.put("archistar-id", Byte.toString(getId()));
// res.put("archistar-length", Integer.toString(getYValues().length));
// return res;
// }
//
// /**
// * @return the (internal) metadata of a share necessary for reconstruction
// */
// HashMap<String, String> getMetaData();
//
// /**
// * compare two shares
// *
// * @param t the share to be compared
// * @return +/-1 if different, 0 if same
// */
// @Override
// default int compareTo(Share t) {
//
// try {
// if (Arrays.equals(getSerializedData(), t.getSerializedData())) {
// return 0;
// } else {
// return t.getId()- getId();
// }
// } catch (IOException ex) {
// return t.getId() - getId();
// }
// }
//
// /**
// * @return a String representation of the type of the share
// */
// String getShareType();
//
// /**
// * @return the length of the original file
// */
// int getOriginalLength();
// }
| import at.archistar.crypto.data.Share;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream; | package at.archistar.crypto.secretsharing;
/**
* <p>This is the abstract base class for all Secret-Sharing algorithms.</p>
*
* <p><i>Secret Sharing</i> means splitting up some secret (for example a message) in <i>n</i> pieces such that any number of
* at least <i>k</i> pieces can reconstruct the secret, but <i>k - 1</i> pieces yield absolutely no information about the
* secret.</p>
*
* For detailed information, see:
* <a href="http://en.wikipedia.org/wiki/Secret_sharing">http://en.wikipedia.org/wiki/Secret_sharing</a>
*/
abstract class BaseSecretSharing implements SecretSharing {
/** number of shares */
protected final int n;
/** minimum number of valid shares required for reconstruction */
protected final int k;
/**
* Constructor (can and should only be called from sub-classes)
*
* @param n the number of shares to create
* @param k the minimum number of valid shares required for reconstruction
* @throws WeakSecurityException if the scheme is not secure for the given parameters
*/
protected BaseSecretSharing(int n, int k) throws WeakSecurityException {
checkSecurity(n, k); // validate security
this.n = n;
this.k = k;
}
/**
* Checks if this Secret-Sharing scheme is secure enough for the given parameters.<br>
* (throws a WeakSecurityException if this is the case)
*
* @param n the number of shares to create
* @param k the minimum number of valid shares required for reconstruction
* @throws WeakSecurityException thrown if the Secret-Sharing scheme is not secure enough
*/
protected static void checkSecurity(int n, int k) throws WeakSecurityException { // n is there in case we want to override this
if (k < 2) {
throw new WeakSecurityException("Parameter \"k\" has to be at least 2");
}
}
/**
* Checks if there are enough shares for reconstruction.<br>
* <i>(This method assumes all shares to be valid!)</i>
*
* @param n the number of shares to reconstruct from
* @param k the minimum number of valid shares required for reconstruction
* @return true if there are enough shares; false otherwise
*/
protected static boolean validateShareCount(int n, int k) {
return n >= k; // base implementation; necessary condition for every Secret-Sharing scheme
}
/**
* Returns the ids of the shares missing from the given set
*
* @param shares the given shares
* @return the ids of the missing shares
*/ | // Path: src/main/java/at/archistar/crypto/data/Share.java
// public interface Share extends Comparable<Share> {
//
// /** on-disk version of the share */
// int VERSION = 5;
//
// static void writeMap(DataOutputStream sout, Map<Byte, byte[]> map) throws IOException {
// sout.writeInt(map.size());
// for (Map.Entry<Byte, byte[]> e : map.entrySet()) {
// Byte key = e.getKey();
// byte[] value = e.getValue();
//
// sout.writeByte(key);
// sout.writeInt(value.length);
// sout.write(value);
// }
// }
//
// /**
// * @return the share's X-value (same as id)
// */
// int getX();
//
// /**
// * @return the share's id (same as x-value)
// */
// byte getId();
//
// /**
// * @return the share's main body (y-values)
// */
// @SuppressFBWarnings("EI_EXPOSE_REP")
// byte[] getYValues();
//
// /**
// * This returns a serialized form of the content (plus IC info) of the share.
// *
// * @return the share's byte[] representation containing all information
// * @throws IOException
// */
// byte[] getSerializedData() throws IOException;
//
// /**
// * This returns a Map of the metadata that are common to all share types;
// * the idea is that the getMetaData()-implementations in all the share types
// * first get this Map and then add their own special keys
// *
// * @return the metadata that are common to all shares
// */
// default HashMap<String, String> getCommonMetaData() {
// HashMap<String, String> res = new HashMap<>();
// res.put("archistar-share-type", getShareType());
// res.put("archistar-version", Integer.toString(VERSION));
// res.put("archistar-id", Byte.toString(getId()));
// res.put("archistar-length", Integer.toString(getYValues().length));
// return res;
// }
//
// /**
// * @return the (internal) metadata of a share necessary for reconstruction
// */
// HashMap<String, String> getMetaData();
//
// /**
// * compare two shares
// *
// * @param t the share to be compared
// * @return +/-1 if different, 0 if same
// */
// @Override
// default int compareTo(Share t) {
//
// try {
// if (Arrays.equals(getSerializedData(), t.getSerializedData())) {
// return 0;
// } else {
// return t.getId()- getId();
// }
// } catch (IOException ex) {
// return t.getId() - getId();
// }
// }
//
// /**
// * @return a String representation of the type of the share
// */
// String getShareType();
//
// /**
// * @return the length of the original file
// */
// int getOriginalLength();
// }
// Path: src/main/java/at/archistar/crypto/secretsharing/BaseSecretSharing.java
import at.archistar.crypto.data.Share;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
package at.archistar.crypto.secretsharing;
/**
* <p>This is the abstract base class for all Secret-Sharing algorithms.</p>
*
* <p><i>Secret Sharing</i> means splitting up some secret (for example a message) in <i>n</i> pieces such that any number of
* at least <i>k</i> pieces can reconstruct the secret, but <i>k - 1</i> pieces yield absolutely no information about the
* secret.</p>
*
* For detailed information, see:
* <a href="http://en.wikipedia.org/wiki/Secret_sharing">http://en.wikipedia.org/wiki/Secret_sharing</a>
*/
abstract class BaseSecretSharing implements SecretSharing {
/** number of shares */
protected final int n;
/** minimum number of valid shares required for reconstruction */
protected final int k;
/**
* Constructor (can and should only be called from sub-classes)
*
* @param n the number of shares to create
* @param k the minimum number of valid shares required for reconstruction
* @throws WeakSecurityException if the scheme is not secure for the given parameters
*/
protected BaseSecretSharing(int n, int k) throws WeakSecurityException {
checkSecurity(n, k); // validate security
this.n = n;
this.k = k;
}
/**
* Checks if this Secret-Sharing scheme is secure enough for the given parameters.<br>
* (throws a WeakSecurityException if this is the case)
*
* @param n the number of shares to create
* @param k the minimum number of valid shares required for reconstruction
* @throws WeakSecurityException thrown if the Secret-Sharing scheme is not secure enough
*/
protected static void checkSecurity(int n, int k) throws WeakSecurityException { // n is there in case we want to override this
if (k < 2) {
throw new WeakSecurityException("Parameter \"k\" has to be at least 2");
}
}
/**
* Checks if there are enough shares for reconstruction.<br>
* <i>(This method assumes all shares to be valid!)</i>
*
* @param n the number of shares to reconstruct from
* @param k the minimum number of valid shares required for reconstruction
* @return true if there are enough shares; false otherwise
*/
protected static boolean validateShareCount(int n, int k) {
return n >= k; // base implementation; necessary condition for every Secret-Sharing scheme
}
/**
* Returns the ids of the shares missing from the given set
*
* @param shares the given shares
* @return the ids of the missing shares
*/ | byte[] determineMissingShares(Share[] shares) { |
Archistar/archistar-smc | src/test/java/at/archistar/crypto/secretsharing/BasicSecretSharingTest.java | // Path: src/test/java/at/archistar/TestHelper.java
// public class TestHelper {
//
// /** test size for slow-running tests */
// public static final int REDUCED_TEST_SIZE = 4 * 1024 * 1024;
//
// /** test size for normal tests */
// public static final int TEST_SIZE = 10 * REDUCED_TEST_SIZE;
//
// /**
// * create test data
// *
// * @param elementSize fragment size in byte, this will create an array with
// * elements sized "elementsSize" and a total size of TEST_SIZE
// * @return test data
// */
// public static byte[][] createArray(int elementSize) {
// return createArray(TEST_SIZE, elementSize);
// }
//
// /**
// * create test data
// *
// * @param size overall test data size
// * @param elementSize fragment size in byte, this will create an array with
// * elements sized "elementsSize" and a total size of "size"
// * @return test data
// */
// public static byte[][] createArray(int size, int elementSize) {
// byte[][] result = new byte[size / elementSize][elementSize];
//
// for (int i = 0; i < size / elementSize; i++) {
// for (int j = 0; j < elementSize; j++) {
// result[i][j] = 1;
// }
// }
//
// return result;
// }
//
// /**
// * drop the array element at the specified index
// *
// * @param shares the array to drop from
// * @param i the index of the element to drop
// * @return a new array without the element at the specified index
// */
// public static Share[] dropElementAt(Share[] shares, int i) {
// Share[] res = new Share[shares.length - 1];
// int pos = 0;
// for (int x = 0; x < shares.length; x++) {
// if (x != i) {
// res[pos++] = shares[x];
// }
// }
// return res;
// }
// }
//
// Path: src/main/java/at/archistar/crypto/data/Share.java
// public interface Share extends Comparable<Share> {
//
// /** on-disk version of the share */
// int VERSION = 5;
//
// static void writeMap(DataOutputStream sout, Map<Byte, byte[]> map) throws IOException {
// sout.writeInt(map.size());
// for (Map.Entry<Byte, byte[]> e : map.entrySet()) {
// Byte key = e.getKey();
// byte[] value = e.getValue();
//
// sout.writeByte(key);
// sout.writeInt(value.length);
// sout.write(value);
// }
// }
//
// /**
// * @return the share's X-value (same as id)
// */
// int getX();
//
// /**
// * @return the share's id (same as x-value)
// */
// byte getId();
//
// /**
// * @return the share's main body (y-values)
// */
// @SuppressFBWarnings("EI_EXPOSE_REP")
// byte[] getYValues();
//
// /**
// * This returns a serialized form of the content (plus IC info) of the share.
// *
// * @return the share's byte[] representation containing all information
// * @throws IOException
// */
// byte[] getSerializedData() throws IOException;
//
// /**
// * This returns a Map of the metadata that are common to all share types;
// * the idea is that the getMetaData()-implementations in all the share types
// * first get this Map and then add their own special keys
// *
// * @return the metadata that are common to all shares
// */
// default HashMap<String, String> getCommonMetaData() {
// HashMap<String, String> res = new HashMap<>();
// res.put("archistar-share-type", getShareType());
// res.put("archistar-version", Integer.toString(VERSION));
// res.put("archistar-id", Byte.toString(getId()));
// res.put("archistar-length", Integer.toString(getYValues().length));
// return res;
// }
//
// /**
// * @return the (internal) metadata of a share necessary for reconstruction
// */
// HashMap<String, String> getMetaData();
//
// /**
// * compare two shares
// *
// * @param t the share to be compared
// * @return +/-1 if different, 0 if same
// */
// @Override
// default int compareTo(Share t) {
//
// try {
// if (Arrays.equals(getSerializedData(), t.getSerializedData())) {
// return 0;
// } else {
// return t.getId()- getId();
// }
// } catch (IOException ex) {
// return t.getId() - getId();
// }
// }
//
// /**
// * @return a String representation of the type of the share
// */
// String getShareType();
//
// /**
// * @return the length of the original file
// */
// int getOriginalLength();
// }
| import at.archistar.TestHelper;
import at.archistar.crypto.data.BrokenShare;
import at.archistar.crypto.data.Share;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;
import org.fest.assertions.core.Condition;
import org.junit.Test; | package at.archistar.crypto.secretsharing;
/**
* all secret-sharing algorithms should at least provide this functionality
*/
public abstract class BasicSecretSharingTest {
protected BaseSecretSharing algorithm;
protected final byte data[] = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
protected final int n;
protected final int k;
public BasicSecretSharingTest(int n, int k) {
this.n = n;
this.k = k;
}
@Test
public void itReconstructsTheData() throws ReconstructionException { | // Path: src/test/java/at/archistar/TestHelper.java
// public class TestHelper {
//
// /** test size for slow-running tests */
// public static final int REDUCED_TEST_SIZE = 4 * 1024 * 1024;
//
// /** test size for normal tests */
// public static final int TEST_SIZE = 10 * REDUCED_TEST_SIZE;
//
// /**
// * create test data
// *
// * @param elementSize fragment size in byte, this will create an array with
// * elements sized "elementsSize" and a total size of TEST_SIZE
// * @return test data
// */
// public static byte[][] createArray(int elementSize) {
// return createArray(TEST_SIZE, elementSize);
// }
//
// /**
// * create test data
// *
// * @param size overall test data size
// * @param elementSize fragment size in byte, this will create an array with
// * elements sized "elementsSize" and a total size of "size"
// * @return test data
// */
// public static byte[][] createArray(int size, int elementSize) {
// byte[][] result = new byte[size / elementSize][elementSize];
//
// for (int i = 0; i < size / elementSize; i++) {
// for (int j = 0; j < elementSize; j++) {
// result[i][j] = 1;
// }
// }
//
// return result;
// }
//
// /**
// * drop the array element at the specified index
// *
// * @param shares the array to drop from
// * @param i the index of the element to drop
// * @return a new array without the element at the specified index
// */
// public static Share[] dropElementAt(Share[] shares, int i) {
// Share[] res = new Share[shares.length - 1];
// int pos = 0;
// for (int x = 0; x < shares.length; x++) {
// if (x != i) {
// res[pos++] = shares[x];
// }
// }
// return res;
// }
// }
//
// Path: src/main/java/at/archistar/crypto/data/Share.java
// public interface Share extends Comparable<Share> {
//
// /** on-disk version of the share */
// int VERSION = 5;
//
// static void writeMap(DataOutputStream sout, Map<Byte, byte[]> map) throws IOException {
// sout.writeInt(map.size());
// for (Map.Entry<Byte, byte[]> e : map.entrySet()) {
// Byte key = e.getKey();
// byte[] value = e.getValue();
//
// sout.writeByte(key);
// sout.writeInt(value.length);
// sout.write(value);
// }
// }
//
// /**
// * @return the share's X-value (same as id)
// */
// int getX();
//
// /**
// * @return the share's id (same as x-value)
// */
// byte getId();
//
// /**
// * @return the share's main body (y-values)
// */
// @SuppressFBWarnings("EI_EXPOSE_REP")
// byte[] getYValues();
//
// /**
// * This returns a serialized form of the content (plus IC info) of the share.
// *
// * @return the share's byte[] representation containing all information
// * @throws IOException
// */
// byte[] getSerializedData() throws IOException;
//
// /**
// * This returns a Map of the metadata that are common to all share types;
// * the idea is that the getMetaData()-implementations in all the share types
// * first get this Map and then add their own special keys
// *
// * @return the metadata that are common to all shares
// */
// default HashMap<String, String> getCommonMetaData() {
// HashMap<String, String> res = new HashMap<>();
// res.put("archistar-share-type", getShareType());
// res.put("archistar-version", Integer.toString(VERSION));
// res.put("archistar-id", Byte.toString(getId()));
// res.put("archistar-length", Integer.toString(getYValues().length));
// return res;
// }
//
// /**
// * @return the (internal) metadata of a share necessary for reconstruction
// */
// HashMap<String, String> getMetaData();
//
// /**
// * compare two shares
// *
// * @param t the share to be compared
// * @return +/-1 if different, 0 if same
// */
// @Override
// default int compareTo(Share t) {
//
// try {
// if (Arrays.equals(getSerializedData(), t.getSerializedData())) {
// return 0;
// } else {
// return t.getId()- getId();
// }
// } catch (IOException ex) {
// return t.getId() - getId();
// }
// }
//
// /**
// * @return a String representation of the type of the share
// */
// String getShareType();
//
// /**
// * @return the length of the original file
// */
// int getOriginalLength();
// }
// Path: src/test/java/at/archistar/crypto/secretsharing/BasicSecretSharingTest.java
import at.archistar.TestHelper;
import at.archistar.crypto.data.BrokenShare;
import at.archistar.crypto.data.Share;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;
import org.fest.assertions.core.Condition;
import org.junit.Test;
package at.archistar.crypto.secretsharing;
/**
* all secret-sharing algorithms should at least provide this functionality
*/
public abstract class BasicSecretSharingTest {
protected BaseSecretSharing algorithm;
protected final byte data[] = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
protected final int n;
protected final int k;
public BasicSecretSharingTest(int n, int k) {
this.n = n;
this.k = k;
}
@Test
public void itReconstructsTheData() throws ReconstructionException { | Share shares[] = algorithm.share(data); |
Archistar/archistar-smc | src/test/java/at/archistar/crypto/math/TestGF256Algebra.java | // Path: src/main/java/at/archistar/crypto/math/gf256/GF256.java
// public class GF256 {
// private static final int GEN_POLY = 0x11D; // a generator polynomial of GF(256)
//
// /**
// * lookup-tables for faster operations. This is public so that I can use
// * it for performance tests
// */
// @SuppressFBWarnings("MS_PKGPROTECT")
// public static final int[] LOG_TABLE = new int[256]; // = log_g(index) (log base g)
//
// /**
// * lookup-tables for faster operations. This is public so that I can use
// * it for performance tests
// */
// @SuppressFBWarnings("MS_PKGPROTECT")
// public static final int[] ALOG_TABLE = new int[1025]; // = pow(g, index); 512 * 2 + 1
//
// /*
// * initialize the lookup tables
// * basis for writing this code: http://catid.mechafetus.com/news/news.php?view=295
// */
// static {
// LOG_TABLE[0] = 512;
// ALOG_TABLE[0] = 1;
//
// for (int i = 1; i < 255; i++) {
// int next = ALOG_TABLE[i - 1] * 2;
// if (next >= 256) {
// next ^= GEN_POLY;
// }
//
// ALOG_TABLE[i] = next;
// LOG_TABLE[ALOG_TABLE[i]] = i;
// }
//
// ALOG_TABLE[255] = ALOG_TABLE[0];
// LOG_TABLE[ALOG_TABLE[255]] = 255;
//
// for (int i = 256; i < 510; i++) { // 2 * 255
// ALOG_TABLE[i] = ALOG_TABLE[i % 255];
// }
//
// ALOG_TABLE[510] = 1; // 2 * 255
//
// for (int i = 511; i < 1020; i++) { // 2 * 255 + 1; 4 * 255
// ALOG_TABLE[i] = 0;
// }
// }
//
// /* arithmetic operations */
//
// /**
// * Performs an addition of two numbers in GF(256). (a + b)
// *
// * @param a number in range 0 - 255
// * @param b number in range 0 - 255
// * @return the result of <i>a + b</i> in GF(256) (will be in range 0 - 255)
// */
// public static int add(int a, int b) {
// return a ^ b;
// }
//
// /**
// * Performs a subtraction of two numbers in GF(256). (a - b)<br>
// * <b>NOTE:</b> addition and subtraction are the same in GF(256)
// *
// * @param a number in range 0 - 255
// * @param b number in range 0 - 255
// * @return the result of <i>a - b</i> in GF(256) (will be in range 0 - 255)
// */
// public static int sub(int a, int b) {
// return a ^ b;
// }
//
// /**
// * Performs a multiplication of two numbers in GF(256). (a × b)
// *
// * @param a number in range 0 - 255
// * @param b number in range 0 - 255
// * @return the result of <i>a × b</i> in GF(256) (will be in range 0 - 255)
// */
// public static int mult(int a, int b) {
// return ALOG_TABLE[LOG_TABLE[a] + LOG_TABLE[b]];
// }
//
// /**
// * Performs an exponentiation of two numbers in GF(256). (a<sup>p</sup>)
// *
// * @param a number in range 0 - 255
// * @param p the exponent; a number in range 0 - 255
// * @return the result of <i>a<sup>p</sup></i> in GF(256) (will be in range 0 - 255)
// */
// public static int pow(int a, int p) {
// // The use of 512 for LOG[0] and the all-zero last half of ALOG cleverly
// // avoids testing 0 in mult, but can't survive arbitrary p*...%255 here.
// if (0 == a && 0 != p) {
// return 0;
// }
// return ALOG_TABLE[p * LOG_TABLE[a] % 255];
// }
//
// /**
// * Computes the inverse of a number in GF(256). (a<sup>-1</sup>)
// *
// * @param a number in range 0 - 255
// * @return the inverse of a <i>(a<sup>-1</sup>)</i> in GF(256) (will be in range 0 - 255)
// */
// public static int inverse(int a) {
// return ALOG_TABLE[255 - (LOG_TABLE[a] % 255)];
// }
//
// public static int div(int a, int b) {
// if (b == 0) { // a / 0
// throw new ArithmeticException("Division by 0");
// }
//
// return ALOG_TABLE[LOG_TABLE[a] + 255 - LOG_TABLE[b]];
// }
//
// public static int evaluateAt(int coeffs[], int x) {
// int degree = coeffs.length - 1;
//
// /* @author flexiprovider */
// int result = coeffs[degree];
// for (int i = degree - 1; i >= 0; i--) {
// result = add(mult(result, x), coeffs[i]);
// }
// return result;
// }
//
// public static int getFieldSize() {
// return 256;
// }
// }
| import at.archistar.crypto.math.gf256.GF256;
import org.bouncycastle.pqc.math.linearalgebra.GF2mField;
import java.util.Set;
import java.util.HashSet;
import java.util.BitSet;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test; | package at.archistar.crypto.math;
public class TestGF256Algebra {
private final Field<Integer> gf256Abstract;
private static Field<Integer> gf256ACache; | // Path: src/main/java/at/archistar/crypto/math/gf256/GF256.java
// public class GF256 {
// private static final int GEN_POLY = 0x11D; // a generator polynomial of GF(256)
//
// /**
// * lookup-tables for faster operations. This is public so that I can use
// * it for performance tests
// */
// @SuppressFBWarnings("MS_PKGPROTECT")
// public static final int[] LOG_TABLE = new int[256]; // = log_g(index) (log base g)
//
// /**
// * lookup-tables for faster operations. This is public so that I can use
// * it for performance tests
// */
// @SuppressFBWarnings("MS_PKGPROTECT")
// public static final int[] ALOG_TABLE = new int[1025]; // = pow(g, index); 512 * 2 + 1
//
// /*
// * initialize the lookup tables
// * basis for writing this code: http://catid.mechafetus.com/news/news.php?view=295
// */
// static {
// LOG_TABLE[0] = 512;
// ALOG_TABLE[0] = 1;
//
// for (int i = 1; i < 255; i++) {
// int next = ALOG_TABLE[i - 1] * 2;
// if (next >= 256) {
// next ^= GEN_POLY;
// }
//
// ALOG_TABLE[i] = next;
// LOG_TABLE[ALOG_TABLE[i]] = i;
// }
//
// ALOG_TABLE[255] = ALOG_TABLE[0];
// LOG_TABLE[ALOG_TABLE[255]] = 255;
//
// for (int i = 256; i < 510; i++) { // 2 * 255
// ALOG_TABLE[i] = ALOG_TABLE[i % 255];
// }
//
// ALOG_TABLE[510] = 1; // 2 * 255
//
// for (int i = 511; i < 1020; i++) { // 2 * 255 + 1; 4 * 255
// ALOG_TABLE[i] = 0;
// }
// }
//
// /* arithmetic operations */
//
// /**
// * Performs an addition of two numbers in GF(256). (a + b)
// *
// * @param a number in range 0 - 255
// * @param b number in range 0 - 255
// * @return the result of <i>a + b</i> in GF(256) (will be in range 0 - 255)
// */
// public static int add(int a, int b) {
// return a ^ b;
// }
//
// /**
// * Performs a subtraction of two numbers in GF(256). (a - b)<br>
// * <b>NOTE:</b> addition and subtraction are the same in GF(256)
// *
// * @param a number in range 0 - 255
// * @param b number in range 0 - 255
// * @return the result of <i>a - b</i> in GF(256) (will be in range 0 - 255)
// */
// public static int sub(int a, int b) {
// return a ^ b;
// }
//
// /**
// * Performs a multiplication of two numbers in GF(256). (a × b)
// *
// * @param a number in range 0 - 255
// * @param b number in range 0 - 255
// * @return the result of <i>a × b</i> in GF(256) (will be in range 0 - 255)
// */
// public static int mult(int a, int b) {
// return ALOG_TABLE[LOG_TABLE[a] + LOG_TABLE[b]];
// }
//
// /**
// * Performs an exponentiation of two numbers in GF(256). (a<sup>p</sup>)
// *
// * @param a number in range 0 - 255
// * @param p the exponent; a number in range 0 - 255
// * @return the result of <i>a<sup>p</sup></i> in GF(256) (will be in range 0 - 255)
// */
// public static int pow(int a, int p) {
// // The use of 512 for LOG[0] and the all-zero last half of ALOG cleverly
// // avoids testing 0 in mult, but can't survive arbitrary p*...%255 here.
// if (0 == a && 0 != p) {
// return 0;
// }
// return ALOG_TABLE[p * LOG_TABLE[a] % 255];
// }
//
// /**
// * Computes the inverse of a number in GF(256). (a<sup>-1</sup>)
// *
// * @param a number in range 0 - 255
// * @return the inverse of a <i>(a<sup>-1</sup>)</i> in GF(256) (will be in range 0 - 255)
// */
// public static int inverse(int a) {
// return ALOG_TABLE[255 - (LOG_TABLE[a] % 255)];
// }
//
// public static int div(int a, int b) {
// if (b == 0) { // a / 0
// throw new ArithmeticException("Division by 0");
// }
//
// return ALOG_TABLE[LOG_TABLE[a] + 255 - LOG_TABLE[b]];
// }
//
// public static int evaluateAt(int coeffs[], int x) {
// int degree = coeffs.length - 1;
//
// /* @author flexiprovider */
// int result = coeffs[degree];
// for (int i = degree - 1; i >= 0; i--) {
// result = add(mult(result, x), coeffs[i]);
// }
// return result;
// }
//
// public static int getFieldSize() {
// return 256;
// }
// }
// Path: src/test/java/at/archistar/crypto/math/TestGF256Algebra.java
import at.archistar.crypto.math.gf256.GF256;
import org.bouncycastle.pqc.math.linearalgebra.GF2mField;
import java.util.Set;
import java.util.HashSet;
import java.util.BitSet;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
package at.archistar.crypto.math;
public class TestGF256Algebra {
private final Field<Integer> gf256Abstract;
private static Field<Integer> gf256ACache; | private final GF256 gf256 = new GF256(); |
Archistar/archistar-smc | src/main/java/at/archistar/crypto/data/ReconstructionResult.java | // Path: src/main/java/at/archistar/crypto/secretsharing/ReconstructionException.java
// public class ReconstructionException extends Exception {
//
// /**
// * creates a reconstruction exception with an error message
// *
// * @param msg the to be used error message
// */
// public ReconstructionException(String msg) {
// super(msg);
// }
// }
| import at.archistar.crypto.secretsharing.ReconstructionException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Collections;
import java.util.List; | package at.archistar.crypto.data;
/**
* The result of a reconstruction operation
* (CryptoEngine::reconstruct or CryptoEngine::reconstructPartial)
* <p>
* This encapsulation was necessary because a reconstruction can not
* only cleanly succeed or fail. If Shares are validated, reconstruction
* can succeed even when some Shares are faulty. In these cases we want
* to propagate the errors and we did not want to (mis)use Exceptions for
* this
*
* @author florian
*/
public class ReconstructionResult {
private final byte[] data;
private final boolean okay;
private final List<String> errors;
@SuppressFBWarnings("EI_EXPOSE_REP2")
public ReconstructionResult(byte[] data) {
this.data = data;
this.okay = true;
this.errors = Collections.emptyList();
}
public ReconstructionResult(List<String> errors) {
this.data = new byte[0];
this.okay = false;
this.errors = errors;
}
@SuppressFBWarnings("EI_EXPOSE_REP2")
public ReconstructionResult(byte[] data, List<String> errors) {
this.data = data;
this.okay = true;
this.errors = errors;
}
@SuppressFBWarnings("EI_EXPOSE_REP") | // Path: src/main/java/at/archistar/crypto/secretsharing/ReconstructionException.java
// public class ReconstructionException extends Exception {
//
// /**
// * creates a reconstruction exception with an error message
// *
// * @param msg the to be used error message
// */
// public ReconstructionException(String msg) {
// super(msg);
// }
// }
// Path: src/main/java/at/archistar/crypto/data/ReconstructionResult.java
import at.archistar.crypto.secretsharing.ReconstructionException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Collections;
import java.util.List;
package at.archistar.crypto.data;
/**
* The result of a reconstruction operation
* (CryptoEngine::reconstruct or CryptoEngine::reconstructPartial)
* <p>
* This encapsulation was necessary because a reconstruction can not
* only cleanly succeed or fail. If Shares are validated, reconstruction
* can succeed even when some Shares are faulty. In these cases we want
* to propagate the errors and we did not want to (mis)use Exceptions for
* this
*
* @author florian
*/
public class ReconstructionResult {
private final byte[] data;
private final boolean okay;
private final List<String> errors;
@SuppressFBWarnings("EI_EXPOSE_REP2")
public ReconstructionResult(byte[] data) {
this.data = data;
this.okay = true;
this.errors = Collections.emptyList();
}
public ReconstructionResult(List<String> errors) {
this.data = new byte[0];
this.okay = false;
this.errors = errors;
}
@SuppressFBWarnings("EI_EXPOSE_REP2")
public ReconstructionResult(byte[] data, List<String> errors) {
this.data = data;
this.okay = true;
this.errors = errors;
}
@SuppressFBWarnings("EI_EXPOSE_REP") | public byte[] getData() throws ReconstructionException { |
Archistar/archistar-smc | src/main/java/at/archistar/crypto/CryptoEngineFactory.java | // Path: src/main/java/at/archistar/crypto/data/InvalidParametersException.java
// public class InvalidParametersException extends Exception {
//
// public InvalidParametersException(String msg) {
// super(msg);
// }
// }
//
// Path: src/main/java/at/archistar/crypto/secretsharing/WeakSecurityException.java
// public class WeakSecurityException extends Exception {
//
// /**
// * create a new exception that denotes that an algorithm was configured
// * in such a way, that it would yield no security or privacy
// *
// * @param msg an detailed error message
// */
// public WeakSecurityException(String msg) {
// super(msg);
// }
// }
| import at.archistar.crypto.data.InvalidParametersException;
import at.archistar.crypto.random.RandomSource;
import at.archistar.crypto.secretsharing.WeakSecurityException;
import java.security.NoSuchAlgorithmException; | package at.archistar.crypto;
/**
* @author florian
*/
public class CryptoEngineFactory {
/**
* Computational Secure Secret Sharing with Fingerprinting
*/
public static CSSEngine getCSSEngine(int n, int k) throws WeakSecurityException {
return new CSSEngine(n, k);
}
/**
* Computational Secure Secret Sharing with Fingerprinting (custom Random Number Generator)
*/
public static CSSEngine getCSSEngine(int n, int k, RandomSource rng) throws WeakSecurityException {
return new CSSEngine(n, k, rng);
}
/**
* Computational Secure Secret Sharing with Fingerprinting (custom Random Number Generator)
* <p>
* This variant will use the given key to encrypt all generated keys before secret-sharing
*/ | // Path: src/main/java/at/archistar/crypto/data/InvalidParametersException.java
// public class InvalidParametersException extends Exception {
//
// public InvalidParametersException(String msg) {
// super(msg);
// }
// }
//
// Path: src/main/java/at/archistar/crypto/secretsharing/WeakSecurityException.java
// public class WeakSecurityException extends Exception {
//
// /**
// * create a new exception that denotes that an algorithm was configured
// * in such a way, that it would yield no security or privacy
// *
// * @param msg an detailed error message
// */
// public WeakSecurityException(String msg) {
// super(msg);
// }
// }
// Path: src/main/java/at/archistar/crypto/CryptoEngineFactory.java
import at.archistar.crypto.data.InvalidParametersException;
import at.archistar.crypto.random.RandomSource;
import at.archistar.crypto.secretsharing.WeakSecurityException;
import java.security.NoSuchAlgorithmException;
package at.archistar.crypto;
/**
* @author florian
*/
public class CryptoEngineFactory {
/**
* Computational Secure Secret Sharing with Fingerprinting
*/
public static CSSEngine getCSSEngine(int n, int k) throws WeakSecurityException {
return new CSSEngine(n, k);
}
/**
* Computational Secure Secret Sharing with Fingerprinting (custom Random Number Generator)
*/
public static CSSEngine getCSSEngine(int n, int k, RandomSource rng) throws WeakSecurityException {
return new CSSEngine(n, k, rng);
}
/**
* Computational Secure Secret Sharing with Fingerprinting (custom Random Number Generator)
* <p>
* This variant will use the given key to encrypt all generated keys before secret-sharing
*/ | public static CSSEngine getCSSEngine(int n, int k, RandomSource rng, byte[] key) throws WeakSecurityException, InvalidParametersException { |
Archistar/archistar-smc | src/main/java/at/archistar/crypto/informationchecking/CevallosUSRSS.java | // Path: src/main/java/at/archistar/crypto/secretsharing/WeakSecurityException.java
// public class WeakSecurityException extends Exception {
//
// /**
// * create a new exception that denotes that an algorithm was configured
// * in such a way, that it would yield no security or privacy
// *
// * @param msg an detailed error message
// */
// public WeakSecurityException(String msg) {
// super(msg);
// }
// }
| import at.archistar.crypto.data.InformationCheckingShare;
import at.archistar.crypto.mac.MacHelper;
import at.archistar.crypto.random.RandomSource;
import at.archistar.crypto.secretsharing.WeakSecurityException;
import java.util.*;
import java.util.stream.Collectors; | package at.archistar.crypto.informationchecking;
/**
* <p>This class implements the <i>Unconditionally-Secure Robust Secret Sharing with Compact Shares</i>-scheme developed by:
* Alfonso Cevallos, Serge Fehr, Rafail Ostrovsky, and Yuval Rabani.</p>
*
* <p>This system basically equals the RabinBenOrRSS, but has shorter tags and therefore requires a different,
* more secure reconstruction phase.</p>
*
* <p>For detailed information about this system, see:
* <a href="http://www.iacr.org/cryptodb/data/paper.php?pubkey=24281">http://www.iacr.org/cryptodb/data/paper.php?pubkey=24281</a></p>
*/
public class CevallosUSRSS extends RabinBenOrRSS {
/**
* security constant for computing the tag length; means 128 bit
*/
public static final int E = 128;
private final MacHelper mac;
private final int n;
/**
* Constructor.
*/ | // Path: src/main/java/at/archistar/crypto/secretsharing/WeakSecurityException.java
// public class WeakSecurityException extends Exception {
//
// /**
// * create a new exception that denotes that an algorithm was configured
// * in such a way, that it would yield no security or privacy
// *
// * @param msg an detailed error message
// */
// public WeakSecurityException(String msg) {
// super(msg);
// }
// }
// Path: src/main/java/at/archistar/crypto/informationchecking/CevallosUSRSS.java
import at.archistar.crypto.data.InformationCheckingShare;
import at.archistar.crypto.mac.MacHelper;
import at.archistar.crypto.random.RandomSource;
import at.archistar.crypto.secretsharing.WeakSecurityException;
import java.util.*;
import java.util.stream.Collectors;
package at.archistar.crypto.informationchecking;
/**
* <p>This class implements the <i>Unconditionally-Secure Robust Secret Sharing with Compact Shares</i>-scheme developed by:
* Alfonso Cevallos, Serge Fehr, Rafail Ostrovsky, and Yuval Rabani.</p>
*
* <p>This system basically equals the RabinBenOrRSS, but has shorter tags and therefore requires a different,
* more secure reconstruction phase.</p>
*
* <p>For detailed information about this system, see:
* <a href="http://www.iacr.org/cryptodb/data/paper.php?pubkey=24281">http://www.iacr.org/cryptodb/data/paper.php?pubkey=24281</a></p>
*/
public class CevallosUSRSS extends RabinBenOrRSS {
/**
* security constant for computing the tag length; means 128 bit
*/
public static final int E = 128;
private final MacHelper mac;
private final int n;
/**
* Constructor.
*/ | public CevallosUSRSS(int n, int k, MacHelper mac, RandomSource rng) throws WeakSecurityException { |
Archistar/archistar-smc | src/main/java/at/archistar/crypto/informationchecking/InformationChecking.java | // Path: src/main/java/at/archistar/crypto/data/InvalidParametersException.java
// public class InvalidParametersException extends Exception {
//
// public InvalidParametersException(String msg) {
// super(msg);
// }
// }
| import at.archistar.crypto.data.InformationCheckingShare;
import at.archistar.crypto.data.InvalidParametersException;
import java.util.List;
import java.util.Map; | package at.archistar.crypto.informationchecking;
/**
* <p>Secret-sharing splits up the original secret data into n shares, k of
* which are needed to reconstruct the original secret. Basic algorithms expect
* shares to either be available and thus not corrupted or unavailable.
* Information checking allows detection of altered shares. This can be
* utilized by implementations to select k uncorrupted shares for reconstruction</p>
*
* <p>An information checking algorithm takes a collection of shares and adds
* share validation information. It should set the share's informationChecking,
* macKeys and macs member variables. In addition it is allowed to add additional
* data to the share's metadata collection.</p>
*/
public interface InformationChecking {
/**
* @param shares the shares with IC information to be checked
* @return the shares that passed the IC check
*/
Map<Boolean, List<InformationCheckingShare>> checkShares(InformationCheckingShare[] shares);
/**
* @param shares the shares that need IC information to be added
* @return shares with information checking data
*/ | // Path: src/main/java/at/archistar/crypto/data/InvalidParametersException.java
// public class InvalidParametersException extends Exception {
//
// public InvalidParametersException(String msg) {
// super(msg);
// }
// }
// Path: src/main/java/at/archistar/crypto/informationchecking/InformationChecking.java
import at.archistar.crypto.data.InformationCheckingShare;
import at.archistar.crypto.data.InvalidParametersException;
import java.util.List;
import java.util.Map;
package at.archistar.crypto.informationchecking;
/**
* <p>Secret-sharing splits up the original secret data into n shares, k of
* which are needed to reconstruct the original secret. Basic algorithms expect
* shares to either be available and thus not corrupted or unavailable.
* Information checking allows detection of altered shares. This can be
* utilized by implementations to select k uncorrupted shares for reconstruction</p>
*
* <p>An information checking algorithm takes a collection of shares and adds
* share validation information. It should set the share's informationChecking,
* macKeys and macs member variables. In addition it is allowed to add additional
* data to the share's metadata collection.</p>
*/
public interface InformationChecking {
/**
* @param shares the shares with IC information to be checked
* @return the shares that passed the IC check
*/
Map<Boolean, List<InformationCheckingShare>> checkShares(InformationCheckingShare[] shares);
/**
* @param shares the shares that need IC information to be added
* @return shares with information checking data
*/ | InformationCheckingShare[] createTags(InformationCheckingShare[] shares) throws InvalidParametersException; |
Archistar/archistar-smc | src/test/java/at/archistar/crypto/mac/VariableLengthMacPerformanceTest.java | // Path: src/main/java/at/archistar/crypto/informationchecking/CevallosUSRSS.java
// public class CevallosUSRSS extends RabinBenOrRSS {
//
// /**
// * security constant for computing the tag length; means 128 bit
// */
// public static final int E = 128;
//
// private final MacHelper mac;
//
// private final int n;
//
// /**
// * Constructor.
// */
// public CevallosUSRSS(int n, int k, MacHelper mac, RandomSource rng) throws WeakSecurityException {
// super(k, mac, rng);
//
// this.n = n;
//
// if (!((k - 1) * 3 >= n) && ((k - 1) * 2 < n)) {
// throw new WeakSecurityException("this scheme only works when n/3 <= t < n/2 (where t = k-1)");
// }
//
// this.mac = mac;
// }
//
// /**
// * Computes the required MAC-tag-length to achieve a security of <i>e</i> bits.
// *
// * @param m the length of the message in bit (TODO: this should be the blocklength)
// * @param t amount of "defective" shares
// * @param e the security constant in bit
// * @return the amount of bytes the MAC-tags should have
// */
// public static int computeTagLength(int m, int t, int e) {
// int tagLengthBit = log2(t + 1) + log2(m) + 2 / (t + 1) * e + log2(e);
// return tagLengthBit / 8;
// }
//
// /**
// * Computes the integer logarithm base 2 of a given number.
// *
// * @param n the int to compute the logarithm for
// * @return the integer logarithm (whole number -> floor()) of the given number
// */
// private static int log2(int n) {
// if (n <= 0) {
// throw new IllegalArgumentException();
// }
//
// return 31 - Integer.numberOfLeadingZeros(n);
// }
//
// private int getAcceptedCount(InformationCheckingShare s1, InformationCheckingShare[] shares, boolean[][] accepts) {
//
// int counter = 0;
//
// for (InformationCheckingShare s2 : shares) {
// byte[] data = s1.getYValues();
// byte[] mac1 = s1.getMacs().get(s2.getId());
// byte[] mac2 = s2.getMacKeys().get(s1.getId());
//
// accepts[s1.getId()][s2.getId()] = mac.verifyMAC(data, mac1, mac2);
// if (accepts[s1.getId()][s2.getId()]) {
// counter++;
// }
// }
//
// return counter;
// }
//
// @Override
// public Map<Boolean, List<InformationCheckingShare>> checkShares(InformationCheckingShare[] cshares) {
//
// Queue<Integer> queue = new LinkedList<>();
// List<InformationCheckingShare> valid = new LinkedList<>();
//
// // accepts[i][j] = true means participant j accepts i
// boolean[][] accepts = new boolean[n + 1][n + 1];
// int a[] = new int[n + 1];
//
// for (InformationCheckingShare s1 : cshares) {
//
// a[s1.getId()] += getAcceptedCount(s1, cshares, accepts);
//
// if (a[s1.getId()] < k) {
// queue.add((int) s1.getId());
// } else {
// valid.add(s1);
// }
// }
//
// while (valid.size() >= k && !queue.isEmpty()) {
// int s1id = queue.poll();
// for (Iterator<InformationCheckingShare> it = valid.iterator(); it.hasNext(); ) {
// InformationCheckingShare s2 = it.next();
// if (accepts[s2.getId()][s1id]) {
// a[s2.getId()]--;
// if (a[s2.getId()] < k) {
// queue.add((int) s2.getId());
// it.remove();
// }
// }
// }
// }
//
// Map<Boolean, List<InformationCheckingShare>> res = new HashMap<>();
// res.put(Boolean.TRUE, valid);
// res.put(Boolean.FALSE, queue.stream().map(i -> cshares[i]).collect(Collectors.toList()));
//
// return res;
// }
//
// @Override
// public String toString() {
// return "Cevallos(" + k + "/" + n + ", " + mac + ")";
// }
// }
//
// Path: src/main/java/at/archistar/crypto/random/FakeRandomSource.java
// public class FakeRandomSource implements RandomSource {
//
// @Override
// public void fillBytes(byte[] toBeFilled) {
// Arrays.fill(toBeFilled, (byte) 4);
// }
//
// @Override
// public void fillBytesAsInts(int[] toBeFilled) {
// Arrays.fill(toBeFilled, (byte) 4);
// }
//
// /**
// * @return human readable representation of this random source
// */
// @Override
// public String toString() {
// return "FakeRandomSource()";
// }
// }
| import at.archistar.crypto.informationchecking.CevallosUSRSS;
import at.archistar.crypto.random.FakeRandomSource;
import at.archistar.crypto.random.RandomSource;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; | package at.archistar.crypto.mac;
/**
* benchmark our variable-length macs
*/
@RunWith(value = Parameterized.class)
public class VariableLengthMacPerformanceTest {
private final byte[] key;
private final byte[] data;
private final int t;
public VariableLengthMacPerformanceTest(byte[] key, byte[] data, int t) {
this.key = key;
this.data = data;
this.t = t;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
System.err.println("All tests on 500MB data a 1MB chunks");
| // Path: src/main/java/at/archistar/crypto/informationchecking/CevallosUSRSS.java
// public class CevallosUSRSS extends RabinBenOrRSS {
//
// /**
// * security constant for computing the tag length; means 128 bit
// */
// public static final int E = 128;
//
// private final MacHelper mac;
//
// private final int n;
//
// /**
// * Constructor.
// */
// public CevallosUSRSS(int n, int k, MacHelper mac, RandomSource rng) throws WeakSecurityException {
// super(k, mac, rng);
//
// this.n = n;
//
// if (!((k - 1) * 3 >= n) && ((k - 1) * 2 < n)) {
// throw new WeakSecurityException("this scheme only works when n/3 <= t < n/2 (where t = k-1)");
// }
//
// this.mac = mac;
// }
//
// /**
// * Computes the required MAC-tag-length to achieve a security of <i>e</i> bits.
// *
// * @param m the length of the message in bit (TODO: this should be the blocklength)
// * @param t amount of "defective" shares
// * @param e the security constant in bit
// * @return the amount of bytes the MAC-tags should have
// */
// public static int computeTagLength(int m, int t, int e) {
// int tagLengthBit = log2(t + 1) + log2(m) + 2 / (t + 1) * e + log2(e);
// return tagLengthBit / 8;
// }
//
// /**
// * Computes the integer logarithm base 2 of a given number.
// *
// * @param n the int to compute the logarithm for
// * @return the integer logarithm (whole number -> floor()) of the given number
// */
// private static int log2(int n) {
// if (n <= 0) {
// throw new IllegalArgumentException();
// }
//
// return 31 - Integer.numberOfLeadingZeros(n);
// }
//
// private int getAcceptedCount(InformationCheckingShare s1, InformationCheckingShare[] shares, boolean[][] accepts) {
//
// int counter = 0;
//
// for (InformationCheckingShare s2 : shares) {
// byte[] data = s1.getYValues();
// byte[] mac1 = s1.getMacs().get(s2.getId());
// byte[] mac2 = s2.getMacKeys().get(s1.getId());
//
// accepts[s1.getId()][s2.getId()] = mac.verifyMAC(data, mac1, mac2);
// if (accepts[s1.getId()][s2.getId()]) {
// counter++;
// }
// }
//
// return counter;
// }
//
// @Override
// public Map<Boolean, List<InformationCheckingShare>> checkShares(InformationCheckingShare[] cshares) {
//
// Queue<Integer> queue = new LinkedList<>();
// List<InformationCheckingShare> valid = new LinkedList<>();
//
// // accepts[i][j] = true means participant j accepts i
// boolean[][] accepts = new boolean[n + 1][n + 1];
// int a[] = new int[n + 1];
//
// for (InformationCheckingShare s1 : cshares) {
//
// a[s1.getId()] += getAcceptedCount(s1, cshares, accepts);
//
// if (a[s1.getId()] < k) {
// queue.add((int) s1.getId());
// } else {
// valid.add(s1);
// }
// }
//
// while (valid.size() >= k && !queue.isEmpty()) {
// int s1id = queue.poll();
// for (Iterator<InformationCheckingShare> it = valid.iterator(); it.hasNext(); ) {
// InformationCheckingShare s2 = it.next();
// if (accepts[s2.getId()][s1id]) {
// a[s2.getId()]--;
// if (a[s2.getId()] < k) {
// queue.add((int) s2.getId());
// it.remove();
// }
// }
// }
// }
//
// Map<Boolean, List<InformationCheckingShare>> res = new HashMap<>();
// res.put(Boolean.TRUE, valid);
// res.put(Boolean.FALSE, queue.stream().map(i -> cshares[i]).collect(Collectors.toList()));
//
// return res;
// }
//
// @Override
// public String toString() {
// return "Cevallos(" + k + "/" + n + ", " + mac + ")";
// }
// }
//
// Path: src/main/java/at/archistar/crypto/random/FakeRandomSource.java
// public class FakeRandomSource implements RandomSource {
//
// @Override
// public void fillBytes(byte[] toBeFilled) {
// Arrays.fill(toBeFilled, (byte) 4);
// }
//
// @Override
// public void fillBytesAsInts(int[] toBeFilled) {
// Arrays.fill(toBeFilled, (byte) 4);
// }
//
// /**
// * @return human readable representation of this random source
// */
// @Override
// public String toString() {
// return "FakeRandomSource()";
// }
// }
// Path: src/test/java/at/archistar/crypto/mac/VariableLengthMacPerformanceTest.java
import at.archistar.crypto.informationchecking.CevallosUSRSS;
import at.archistar.crypto.random.FakeRandomSource;
import at.archistar.crypto.random.RandomSource;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
package at.archistar.crypto.mac;
/**
* benchmark our variable-length macs
*/
@RunWith(value = Parameterized.class)
public class VariableLengthMacPerformanceTest {
private final byte[] key;
private final byte[] data;
private final int t;
public VariableLengthMacPerformanceTest(byte[] key, byte[] data, int t) {
this.key = key;
this.data = data;
this.t = t;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
System.err.println("All tests on 500MB data a 1MB chunks");
| RandomSource rng = new FakeRandomSource(); |
Archistar/archistar-smc | src/test/java/at/archistar/TestHelper.java | // Path: src/main/java/at/archistar/crypto/data/Share.java
// public interface Share extends Comparable<Share> {
//
// /** on-disk version of the share */
// int VERSION = 5;
//
// static void writeMap(DataOutputStream sout, Map<Byte, byte[]> map) throws IOException {
// sout.writeInt(map.size());
// for (Map.Entry<Byte, byte[]> e : map.entrySet()) {
// Byte key = e.getKey();
// byte[] value = e.getValue();
//
// sout.writeByte(key);
// sout.writeInt(value.length);
// sout.write(value);
// }
// }
//
// /**
// * @return the share's X-value (same as id)
// */
// int getX();
//
// /**
// * @return the share's id (same as x-value)
// */
// byte getId();
//
// /**
// * @return the share's main body (y-values)
// */
// @SuppressFBWarnings("EI_EXPOSE_REP")
// byte[] getYValues();
//
// /**
// * This returns a serialized form of the content (plus IC info) of the share.
// *
// * @return the share's byte[] representation containing all information
// * @throws IOException
// */
// byte[] getSerializedData() throws IOException;
//
// /**
// * This returns a Map of the metadata that are common to all share types;
// * the idea is that the getMetaData()-implementations in all the share types
// * first get this Map and then add their own special keys
// *
// * @return the metadata that are common to all shares
// */
// default HashMap<String, String> getCommonMetaData() {
// HashMap<String, String> res = new HashMap<>();
// res.put("archistar-share-type", getShareType());
// res.put("archistar-version", Integer.toString(VERSION));
// res.put("archistar-id", Byte.toString(getId()));
// res.put("archistar-length", Integer.toString(getYValues().length));
// return res;
// }
//
// /**
// * @return the (internal) metadata of a share necessary for reconstruction
// */
// HashMap<String, String> getMetaData();
//
// /**
// * compare two shares
// *
// * @param t the share to be compared
// * @return +/-1 if different, 0 if same
// */
// @Override
// default int compareTo(Share t) {
//
// try {
// if (Arrays.equals(getSerializedData(), t.getSerializedData())) {
// return 0;
// } else {
// return t.getId()- getId();
// }
// } catch (IOException ex) {
// return t.getId() - getId();
// }
// }
//
// /**
// * @return a String representation of the type of the share
// */
// String getShareType();
//
// /**
// * @return the length of the original file
// */
// int getOriginalLength();
// }
| import at.archistar.crypto.data.Share; | package at.archistar;
/**
* commonly needed test functionality
*/
public class TestHelper {
/** test size for slow-running tests */
public static final int REDUCED_TEST_SIZE = 4 * 1024 * 1024;
/** test size for normal tests */
public static final int TEST_SIZE = 10 * REDUCED_TEST_SIZE;
/**
* create test data
*
* @param elementSize fragment size in byte, this will create an array with
* elements sized "elementsSize" and a total size of TEST_SIZE
* @return test data
*/
public static byte[][] createArray(int elementSize) {
return createArray(TEST_SIZE, elementSize);
}
/**
* create test data
*
* @param size overall test data size
* @param elementSize fragment size in byte, this will create an array with
* elements sized "elementsSize" and a total size of "size"
* @return test data
*/
public static byte[][] createArray(int size, int elementSize) {
byte[][] result = new byte[size / elementSize][elementSize];
for (int i = 0; i < size / elementSize; i++) {
for (int j = 0; j < elementSize; j++) {
result[i][j] = 1;
}
}
return result;
}
/**
* drop the array element at the specified index
*
* @param shares the array to drop from
* @param i the index of the element to drop
* @return a new array without the element at the specified index
*/ | // Path: src/main/java/at/archistar/crypto/data/Share.java
// public interface Share extends Comparable<Share> {
//
// /** on-disk version of the share */
// int VERSION = 5;
//
// static void writeMap(DataOutputStream sout, Map<Byte, byte[]> map) throws IOException {
// sout.writeInt(map.size());
// for (Map.Entry<Byte, byte[]> e : map.entrySet()) {
// Byte key = e.getKey();
// byte[] value = e.getValue();
//
// sout.writeByte(key);
// sout.writeInt(value.length);
// sout.write(value);
// }
// }
//
// /**
// * @return the share's X-value (same as id)
// */
// int getX();
//
// /**
// * @return the share's id (same as x-value)
// */
// byte getId();
//
// /**
// * @return the share's main body (y-values)
// */
// @SuppressFBWarnings("EI_EXPOSE_REP")
// byte[] getYValues();
//
// /**
// * This returns a serialized form of the content (plus IC info) of the share.
// *
// * @return the share's byte[] representation containing all information
// * @throws IOException
// */
// byte[] getSerializedData() throws IOException;
//
// /**
// * This returns a Map of the metadata that are common to all share types;
// * the idea is that the getMetaData()-implementations in all the share types
// * first get this Map and then add their own special keys
// *
// * @return the metadata that are common to all shares
// */
// default HashMap<String, String> getCommonMetaData() {
// HashMap<String, String> res = new HashMap<>();
// res.put("archistar-share-type", getShareType());
// res.put("archistar-version", Integer.toString(VERSION));
// res.put("archistar-id", Byte.toString(getId()));
// res.put("archistar-length", Integer.toString(getYValues().length));
// return res;
// }
//
// /**
// * @return the (internal) metadata of a share necessary for reconstruction
// */
// HashMap<String, String> getMetaData();
//
// /**
// * compare two shares
// *
// * @param t the share to be compared
// * @return +/-1 if different, 0 if same
// */
// @Override
// default int compareTo(Share t) {
//
// try {
// if (Arrays.equals(getSerializedData(), t.getSerializedData())) {
// return 0;
// } else {
// return t.getId()- getId();
// }
// } catch (IOException ex) {
// return t.getId() - getId();
// }
// }
//
// /**
// * @return a String representation of the type of the share
// */
// String getShareType();
//
// /**
// * @return the length of the original file
// */
// int getOriginalLength();
// }
// Path: src/test/java/at/archistar/TestHelper.java
import at.archistar.crypto.data.Share;
package at.archistar;
/**
* commonly needed test functionality
*/
public class TestHelper {
/** test size for slow-running tests */
public static final int REDUCED_TEST_SIZE = 4 * 1024 * 1024;
/** test size for normal tests */
public static final int TEST_SIZE = 10 * REDUCED_TEST_SIZE;
/**
* create test data
*
* @param elementSize fragment size in byte, this will create an array with
* elements sized "elementsSize" and a total size of TEST_SIZE
* @return test data
*/
public static byte[][] createArray(int elementSize) {
return createArray(TEST_SIZE, elementSize);
}
/**
* create test data
*
* @param size overall test data size
* @param elementSize fragment size in byte, this will create an array with
* elements sized "elementsSize" and a total size of "size"
* @return test data
*/
public static byte[][] createArray(int size, int elementSize) {
byte[][] result = new byte[size / elementSize][elementSize];
for (int i = 0; i < size / elementSize; i++) {
for (int j = 0; j < elementSize; j++) {
result[i][j] = 1;
}
}
return result;
}
/**
* drop the array element at the specified index
*
* @param shares the array to drop from
* @param i the index of the element to drop
* @return a new array without the element at the specified index
*/ | public static Share[] dropElementAt(Share[] shares, int i) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/OrExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The boolean or operator.
* Usage in stupid: {@code expr or expr}
*/
public class OrExpression implements Expression {
private final Expression left, right;
public OrExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/OrExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The boolean or operator.
* Usage in stupid: {@code expr or expr}
*/
public class OrExpression implements Expression {
private final Expression left, right;
public OrExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/DivisionExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* Divide one value by another. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied. May lead to division by zero.
* In stupid: {@code expr / expr}
*/
public class DivisionExpression implements Expression {
private final Expression left, right;
public DivisionExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/DivisionExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* Divide one value by another. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied. May lead to division by zero.
* In stupid: {@code expr / expr}
*/
public class DivisionExpression implements Expression {
private final Expression left, right;
public DivisionExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/VarExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* Get a variable, either for getting a value or assigning to it.
* Usage in stupid: {@code var}, or {@code obj.var}.
*/
public class VarExpression implements Expression {
private final Expression base;
private final String identifier;
public VarExpression(Expression base, String identifier) {
this.base = base;
this.identifier = identifier;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/VarExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* Get a variable, either for getting a value or assigning to it.
* Usage in stupid: {@code var}, or {@code obj.var}.
*/
public class VarExpression implements Expression {
private final Expression base;
private final String identifier;
public VarExpression(Expression base, String identifier) {
this.base = base;
this.identifier = identifier;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/test/java/com/madisp/stupid/VarScopeTest.java | // Path: src/main/java/com/madisp/stupid/context/VarContext.java
// public class VarContext extends BaseContext {
//
// /**
// * The type of the VarContext.
// */
// public static enum Type {
// /**
// * No variables can be created, the variable set is immutable.
// */
// NO_CREATE,
// /**
// * Variables can (and will be created) with assignment
// */
// CREATE_ON_SET,
// /**
// * Variables will be created when getting a value even if they don't
// * exist yet. A bit weird but useful later on.
// */
// CREATE_ON_SET_OR_GET
// }
// private final Type type;
// private final Var base;
//
// /**
// * Create a new immutable context with a set of variables.
// * @param vars The String->Object (identifier->value) map of variables
// */
// public VarContext(Map<String, Object> vars) {
// this(Type.NO_CREATE, vars);
// }
//
// /**
// * Create a new context with the given type and no starting variables.
// * @param type The type of the context
// */
// public VarContext(Type type) {
// this(type, null);
// }
//
// /**
// * Create a new context with the given type and a set of variables
// * @param type The type of the context
// * @param vars The String->Object (identifier->value) map of variables
// */
// public VarContext(Type type, Map<String, Object> vars) {
// this.type = type;
// this.base = new Var(null);
// if (vars != null) {
// for (Map.Entry<String, Object> entry : vars.entrySet()) {
// base.put(entry.getKey(), entry.getValue());
// }
// }
// }
//
// @Override
// public Object getFieldValue(Object root, String identifier) throws NoSuchFieldException {
// Var obj = base;
// if (root != null) {
// if (root instanceof Var) {
// obj = (Var)root;
// } else {
// throw new NoSuchFieldException();
// }
// }
//
// if (!obj.has(identifier)) {
// if (type != Type.CREATE_ON_SET_OR_GET) {
// throw new NoSuchFieldException();
// }
// obj.put(identifier, null);
// }
// return obj.get(identifier);
// }
//
// @Override
// public Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException {
// Var obj = base;
// if (root != null) {
// if (root instanceof Var) {
// obj = (Var)root;
// } else {
// throw new NoSuchFieldException();
// }
// }
//
// if (!obj.has(identifier)) {
// if (type == Type.NO_CREATE) {
// throw new NoSuchFieldException();
// }
// }
// return obj.put(identifier, new Var(value));
// }
//
// private static class Var implements Value {
// private Object value = null;
// private final Map<String, Var> vars;
//
// private Var(Object value) {
// this.value = value;
// this.vars = new HashMap<String, Var>();
// }
//
// private boolean has(String identifier) {
// return vars.containsKey(identifier);
// }
//
// private Object get(String identifier) {
// return vars.get(identifier);
// }
//
// private Object put(String identifier, Object value) {
// vars.put(identifier, new Var(value));
// return value;
// }
//
// @Override
// public Object value(ExecContext ctx) {
// return value;
// }
// }
// }
| import com.madisp.stupid.context.VarContext;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull; | package com.madisp.stupid;
public class VarScopeTest extends BaseExpressionTest {
@Test
public void testNoCreate() throws Exception {
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", "foo");
vars.put("bar", "bar");
| // Path: src/main/java/com/madisp/stupid/context/VarContext.java
// public class VarContext extends BaseContext {
//
// /**
// * The type of the VarContext.
// */
// public static enum Type {
// /**
// * No variables can be created, the variable set is immutable.
// */
// NO_CREATE,
// /**
// * Variables can (and will be created) with assignment
// */
// CREATE_ON_SET,
// /**
// * Variables will be created when getting a value even if they don't
// * exist yet. A bit weird but useful later on.
// */
// CREATE_ON_SET_OR_GET
// }
// private final Type type;
// private final Var base;
//
// /**
// * Create a new immutable context with a set of variables.
// * @param vars The String->Object (identifier->value) map of variables
// */
// public VarContext(Map<String, Object> vars) {
// this(Type.NO_CREATE, vars);
// }
//
// /**
// * Create a new context with the given type and no starting variables.
// * @param type The type of the context
// */
// public VarContext(Type type) {
// this(type, null);
// }
//
// /**
// * Create a new context with the given type and a set of variables
// * @param type The type of the context
// * @param vars The String->Object (identifier->value) map of variables
// */
// public VarContext(Type type, Map<String, Object> vars) {
// this.type = type;
// this.base = new Var(null);
// if (vars != null) {
// for (Map.Entry<String, Object> entry : vars.entrySet()) {
// base.put(entry.getKey(), entry.getValue());
// }
// }
// }
//
// @Override
// public Object getFieldValue(Object root, String identifier) throws NoSuchFieldException {
// Var obj = base;
// if (root != null) {
// if (root instanceof Var) {
// obj = (Var)root;
// } else {
// throw new NoSuchFieldException();
// }
// }
//
// if (!obj.has(identifier)) {
// if (type != Type.CREATE_ON_SET_OR_GET) {
// throw new NoSuchFieldException();
// }
// obj.put(identifier, null);
// }
// return obj.get(identifier);
// }
//
// @Override
// public Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException {
// Var obj = base;
// if (root != null) {
// if (root instanceof Var) {
// obj = (Var)root;
// } else {
// throw new NoSuchFieldException();
// }
// }
//
// if (!obj.has(identifier)) {
// if (type == Type.NO_CREATE) {
// throw new NoSuchFieldException();
// }
// }
// return obj.put(identifier, new Var(value));
// }
//
// private static class Var implements Value {
// private Object value = null;
// private final Map<String, Var> vars;
//
// private Var(Object value) {
// this.value = value;
// this.vars = new HashMap<String, Var>();
// }
//
// private boolean has(String identifier) {
// return vars.containsKey(identifier);
// }
//
// private Object get(String identifier) {
// return vars.get(identifier);
// }
//
// private Object put(String identifier, Object value) {
// vars.put(identifier, new Var(value));
// return value;
// }
//
// @Override
// public Object value(ExecContext ctx) {
// return value;
// }
// }
// }
// Path: src/test/java/com/madisp/stupid/VarScopeTest.java
import com.madisp.stupid.context.VarContext;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
package com.madisp.stupid;
public class VarScopeTest extends BaseExpressionTest {
@Test
public void testNoCreate() throws Exception {
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("foo", "foo");
vars.put("bar", "bar");
| ctx.pushExecContext(new VarContext(vars)); |
madisp/stupid | src/main/java/com/madisp/stupid/expr/ComparisonExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The arithmetic minus expression. If any of the arguments is a double then
* both of the arguments are converted to double. Otherwise an Integer is implied.
* Note that this class is used for both less than and larger than operations (as the
* only difference is the order of operands).
*
* Usage in stupid: {@code expr < expr}
*/
public class ComparisonExpression implements Expression<Boolean> {
private Expression left, right;
public ComparisonExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/ComparisonExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The arithmetic minus expression. If any of the arguments is a double then
* both of the arguments are converted to double. Otherwise an Integer is implied.
* Note that this class is used for both less than and larger than operations (as the
* only difference is the order of operands).
*
* Usage in stupid: {@code expr < expr}
*/
public class ComparisonExpression implements Expression<Boolean> {
private Expression left, right;
public ComparisonExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | public Boolean value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/context/VarContext.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Value;
import java.util.HashMap;
import java.util.Map; | }
if (!obj.has(identifier)) {
if (type != Type.CREATE_ON_SET_OR_GET) {
throw new NoSuchFieldException();
}
obj.put(identifier, null);
}
return obj.get(identifier);
}
@Override
public Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException {
Var obj = base;
if (root != null) {
if (root instanceof Var) {
obj = (Var)root;
} else {
throw new NoSuchFieldException();
}
}
if (!obj.has(identifier)) {
if (type == Type.NO_CREATE) {
throw new NoSuchFieldException();
}
}
return obj.put(identifier, new Var(value));
}
| // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
// Path: src/main/java/com/madisp/stupid/context/VarContext.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Value;
import java.util.HashMap;
import java.util.Map;
}
if (!obj.has(identifier)) {
if (type != Type.CREATE_ON_SET_OR_GET) {
throw new NoSuchFieldException();
}
obj.put(identifier, null);
}
return obj.get(identifier);
}
@Override
public Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException {
Var obj = base;
if (root != null) {
if (root instanceof Var) {
obj = (Var)root;
} else {
throw new NoSuchFieldException();
}
}
if (!obj.has(identifier)) {
if (type == Type.NO_CREATE) {
throw new NoSuchFieldException();
}
}
return obj.put(identifier, new Var(value));
}
| private static class Var implements Value { |
madisp/stupid | src/main/java/com/madisp/stupid/context/VarContext.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Value;
import java.util.HashMap;
import java.util.Map; | if (type == Type.NO_CREATE) {
throw new NoSuchFieldException();
}
}
return obj.put(identifier, new Var(value));
}
private static class Var implements Value {
private Object value = null;
private final Map<String, Var> vars;
private Var(Object value) {
this.value = value;
this.vars = new HashMap<String, Var>();
}
private boolean has(String identifier) {
return vars.containsKey(identifier);
}
private Object get(String identifier) {
return vars.get(identifier);
}
private Object put(String identifier, Object value) {
vars.put(identifier, new Var(value));
return value;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
// Path: src/main/java/com/madisp/stupid/context/VarContext.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Value;
import java.util.HashMap;
import java.util.Map;
if (type == Type.NO_CREATE) {
throw new NoSuchFieldException();
}
}
return obj.put(identifier, new Var(value));
}
private static class Var implements Value {
private Object value = null;
private final Map<String, Var> vars;
private Var(Object value) {
this.value = value;
this.vars = new HashMap<String, Var>();
}
private boolean has(String identifier) {
return vars.containsKey(identifier);
}
private Object get(String identifier) {
return vars.get(identifier);
}
private Object put(String identifier, Object value) {
vars.put(identifier, new Var(value));
return value;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/AssignExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* Assign a value to a field.
* Usage in stupid: {@code var = expr}
*/
public class AssignExpression implements Expression {
private final Expression base;
private final String identifier;
private final Expression value;
public AssignExpression(Expression base, String identifier, Expression value) {
this.base = base;
this.identifier = identifier;
this.value = value;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/AssignExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* Assign a value to a field.
* Usage in stupid: {@code var = expr}
*/
public class AssignExpression implements Expression {
private final Expression base;
private final String identifier;
private final Expression value;
public AssignExpression(Expression base, String identifier, Expression value) {
this.base = base;
this.identifier = identifier;
this.value = value;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/NegateExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The unary minus (negation) operator.
*
* Usage in stupid: {@code -expr}
*/
public class NegateExpression implements Expression {
private final Expression expr;
public NegateExpression(Expression expr) {
this.expr = expr;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/NegateExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The unary minus (negation) operator.
*
* Usage in stupid: {@code -expr}
*/
public class NegateExpression implements Expression {
private final Expression expr;
public NegateExpression(Expression expr) {
this.expr = expr;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/EqualsExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The equals expression.
* The implementation uses the {@link Object#equals(Object)} method under the hood, so
* comparing strings with the == operator is valid, for instance.
* In stupid: {@code expr == expr}
*/
public class EqualsExpression implements Expression<Boolean> {
private Expression left, right;
public EqualsExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public Expression[] children() {
return new Expression[] { left, right };
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/EqualsExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The equals expression.
* The implementation uses the {@link Object#equals(Object)} method under the hood, so
* comparing strings with the == operator is valid, for instance.
* In stupid: {@code expr == expr}
*/
public class EqualsExpression implements Expression<Boolean> {
private Expression left, right;
public EqualsExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public Expression[] children() {
return new Expression[] { left, right };
}
@Override | public Boolean value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/ApplyExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* An apply expression, usually evals to yielding a block.
* Usage in stupid: {@code expr.(arg1, arg2, ..., argN)}
*/
public class ApplyExpression implements Expression {
private final Expression value;
private final Expression[] args;
public ApplyExpression(Expression value, Expression... args) {
this.value = value;
this.args = args;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/ApplyExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* An apply expression, usually evals to yielding a block.
* Usage in stupid: {@code expr.(arg1, arg2, ..., argN)}
*/
public class ApplyExpression implements Expression {
private final Expression value;
private final Expression[] args;
public ApplyExpression(Expression value, Expression... args) {
this.value = value;
this.args = args;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/PlusExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The arithmetic plus operator. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied.
*
* Usage in stupid: {@code expr + expr}
*/
public class PlusExpression implements Expression {
private final Expression left, right;
public PlusExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/PlusExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The arithmetic plus operator. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied.
*
* Usage in stupid: {@code expr + expr}
*/
public class PlusExpression implements Expression {
private final Expression left, right;
public PlusExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/AndExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The boolean and operator.
* Usage in stupid: {@code expr and expr}
*/
public class AndExpression implements Expression<Boolean> {
private final Expression left, right;
public AndExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/AndExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The boolean and operator.
* Usage in stupid: {@code expr and expr}
*/
public class AndExpression implements Expression<Boolean> {
private final Expression left, right;
public AndExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | public Boolean value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/ConstantExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* Constant value. Super boring, used for literals and null.
*/
public class ConstantExpression implements Expression {
private final Object constant;
public ConstantExpression(Object constant) {
this.constant = constant;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/ConstantExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* Constant value. Super boring, used for literals and null.
*/
public class ConstantExpression implements Expression {
private final Object constant;
public ConstantExpression(Object constant) {
this.constant = constant;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/ResourceExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The resource expression. This is currently unsupported but can be used on
* android. The value of this is typically an android resource id which is an
* int.
*
* Stupid usage: {@code @pckg:type/name}
*/
public class ResourceExpression implements Expression {
private final String pckg, type, name;
public ResourceExpression(String pckg, String type, String name) {
this.pckg = pckg;
this.type = type;
this.name = name;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/ResourceExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The resource expression. This is currently unsupported but can be used on
* android. The value of this is typically an android resource id which is an
* int.
*
* Stupid usage: {@code @pckg:type/name}
*/
public class ResourceExpression implements Expression {
private final String pckg, type, name;
public ResourceExpression(String pckg, String type, String name) {
this.pckg = pckg;
this.type = type;
this.name = name;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/StatementListExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import com.madisp.stupid.Value;
import java.util.Collections;
import java.util.List; | package com.madisp.stupid.expr;
/**
* A list of statements. Return value is the last one executed.
* Allows one to construct intricate programs by having multiple
* expressions.
* In stupid: {@code statement1; statement2; ...; statementN}
*/
public class StatementListExpression implements Expression {
private final List<Expression> statements;
public StatementListExpression(List<Expression> statements) {
this.statements = Collections.unmodifiableList(statements);
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
// Path: src/main/java/com/madisp/stupid/expr/StatementListExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import com.madisp.stupid.Value;
import java.util.Collections;
import java.util.List;
package com.madisp.stupid.expr;
/**
* A list of statements. Return value is the last one executed.
* Allows one to construct intricate programs by having multiple
* expressions.
* In stupid: {@code statement1; statement2; ...; statementN}
*/
public class StatementListExpression implements Expression {
private final List<Expression> statements;
public StatementListExpression(List<Expression> statements) {
this.statements = Collections.unmodifiableList(statements);
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/StatementListExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import com.madisp.stupid.Value;
import java.util.Collections;
import java.util.List; | package com.madisp.stupid.expr;
/**
* A list of statements. Return value is the last one executed.
* Allows one to construct intricate programs by having multiple
* expressions.
* In stupid: {@code statement1; statement2; ...; statementN}
*/
public class StatementListExpression implements Expression {
private final List<Expression> statements;
public StatementListExpression(List<Expression> statements) {
this.statements = Collections.unmodifiableList(statements);
}
@Override
public Object value(ExecContext ctx) {
Object ret = null; | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
// Path: src/main/java/com/madisp/stupid/expr/StatementListExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import com.madisp.stupid.Value;
import java.util.Collections;
import java.util.List;
package com.madisp.stupid.expr;
/**
* A list of statements. Return value is the last one executed.
* Allows one to construct intricate programs by having multiple
* expressions.
* In stupid: {@code statement1; statement2; ...; statementN}
*/
public class StatementListExpression implements Expression {
private final List<Expression> statements;
public StatementListExpression(List<Expression> statements) {
this.statements = Collections.unmodifiableList(statements);
}
@Override
public Object value(ExecContext ctx) {
Object ret = null; | for (Value e : statements) { |
madisp/stupid | src/main/java/com/madisp/stupid/context/BaseContext.java | // Path: src/main/java/com/madisp/stupid/Converter.java
// public interface Converter {
// /**
// * Convert an object to a boolean.
// * @param value object to convert, may be null
// * @return boolean representation of the object
// */
// boolean toBool(Object value);
//
// /**
// * Convert an object to an integer.
// * @param value object to convert, may be null
// * @return integer representation of given object
// */
// int toInt(Object value);
//
// /**
// * Convert an object to a double.
// * @param value object to convert, may be null
// * @return the double representation of the argument
// */
// double toDouble(Object value);
//
// /**
// * Convert an object to a string.
// * Java already has semantics for converting (.toString()) but
// * it is nice to still have it here anyway.
// * @param value object to convert, may be null
// * @return the argument represented as a String
// */
// String toString(Object value);
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
| import com.madisp.stupid.Converter;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Value; | package com.madisp.stupid.context;
/**
* Base class for all of the {@link ExecContext} implementations in stupid.
* All of the methods that can throw NoSuch* exceptions will throw them.
* The dereference() method runs instanceof {@link Value} checks in a loop and
* evaluates the Value until it obtains a POJO instance or null.
* The getConverter() method returns a {@link DefaultConverter} but this may
* be overridden by calling setConverter().
*/
public class BaseContext implements ExecContext {
private Converter converter = new DefaultConverter();
@Override
public Object getFieldValue(Object root, String identifier) throws NoSuchFieldException {
throw new NoSuchFieldException();
}
@Override
public Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException {
throw new NoSuchFieldException();
}
@Override
public Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException {
throw new NoSuchMethodException();
}
@Override
public Object apply(Object base, Object[] args) throws NoSuchMethodException {
throw new NoSuchMethodException();
}
@Override
public Object getResource(String pckg, String type, String name) throws NoSuchFieldException {
throw new NoSuchFieldException();
}
@Override
public Object dereference(Object object) { | // Path: src/main/java/com/madisp/stupid/Converter.java
// public interface Converter {
// /**
// * Convert an object to a boolean.
// * @param value object to convert, may be null
// * @return boolean representation of the object
// */
// boolean toBool(Object value);
//
// /**
// * Convert an object to an integer.
// * @param value object to convert, may be null
// * @return integer representation of given object
// */
// int toInt(Object value);
//
// /**
// * Convert an object to a double.
// * @param value object to convert, may be null
// * @return the double representation of the argument
// */
// double toDouble(Object value);
//
// /**
// * Convert an object to a string.
// * Java already has semantics for converting (.toString()) but
// * it is nice to still have it here anyway.
// * @param value object to convert, may be null
// * @return the argument represented as a String
// */
// String toString(Object value);
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Value.java
// public interface Value<T> {
// /**
// * Dereference a value to a POJO instance
// * @param ctx the execution context
// * @return POJO representation of this value (expression)
// */
// T value(ExecContext ctx);
// }
// Path: src/main/java/com/madisp/stupid/context/BaseContext.java
import com.madisp.stupid.Converter;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Value;
package com.madisp.stupid.context;
/**
* Base class for all of the {@link ExecContext} implementations in stupid.
* All of the methods that can throw NoSuch* exceptions will throw them.
* The dereference() method runs instanceof {@link Value} checks in a loop and
* evaluates the Value until it obtains a POJO instance or null.
* The getConverter() method returns a {@link DefaultConverter} but this may
* be overridden by calling setConverter().
*/
public class BaseContext implements ExecContext {
private Converter converter = new DefaultConverter();
@Override
public Object getFieldValue(Object root, String identifier) throws NoSuchFieldException {
throw new NoSuchFieldException();
}
@Override
public Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException {
throw new NoSuchFieldException();
}
@Override
public Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException {
throw new NoSuchMethodException();
}
@Override
public Object apply(Object base, Object[] args) throws NoSuchMethodException {
throw new NoSuchMethodException();
}
@Override
public Object getResource(String pckg, String type, String name) throws NoSuchFieldException {
throw new NoSuchFieldException();
}
@Override
public Object dereference(Object object) { | while (object != null && object instanceof Value) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/BlockExpression.java | // Path: src/main/java/com/madisp/stupid/Block.java
// public class Block {
// private final StatementListExpression body;
// private final String[] varNames;
//
// /**
// * Create a new block with named arguments
// * @param varNames list of argument names
// * @param body expression that is to be evaluated
// */
// public Block(String[] varNames, StatementListExpression body) {
// this.varNames = Arrays.copyOf(varNames, varNames.length);
// this.body = body;
// }
//
// /**
// * Evaluate the body of a block with given arguments. The length
// * of arguments must match the length of given names in the constructor.
// * @param ctx The context wherein to evaluate the block
// * @param args argument values (must match the same length and order as given
// * in the constructor)
// * @return The evaluated value of the block
// */
// public Object yield(ExecContext ctx, Object... args) {
// if (varNames.length != args.length) {
// throw new IllegalArgumentException();
// }
// Map<String, Object> argMap = new HashMap<String, Object>();
// for (int i = 0; i < varNames.length; i++) {
// argMap.put(varNames[i], args[i]);
// }
// // wrap our block arguments over the underlying context
// StackContext withArgs = new StackContext();
// withArgs.pushExecContext(ctx); // the underlying context
// withArgs.pushExecContext(new VarContext(Collections.unmodifiableMap(argMap))); // args
// return body.value(withArgs);
// };
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.Block;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import java.util.Arrays; | package com.madisp.stupid.expr;
/**
* An expression that returns a block when evaluated.
* Usage in stupid: {@code sqr = {|x| x * x }}
*/
public class BlockExpression implements Expression {
private final StatementListExpression body;
private final String[] varNames;
public BlockExpression(String[] varNames, StatementListExpression body) {
this.varNames = Arrays.copyOf(varNames, varNames.length);
this.body = body;
}
@Override | // Path: src/main/java/com/madisp/stupid/Block.java
// public class Block {
// private final StatementListExpression body;
// private final String[] varNames;
//
// /**
// * Create a new block with named arguments
// * @param varNames list of argument names
// * @param body expression that is to be evaluated
// */
// public Block(String[] varNames, StatementListExpression body) {
// this.varNames = Arrays.copyOf(varNames, varNames.length);
// this.body = body;
// }
//
// /**
// * Evaluate the body of a block with given arguments. The length
// * of arguments must match the length of given names in the constructor.
// * @param ctx The context wherein to evaluate the block
// * @param args argument values (must match the same length and order as given
// * in the constructor)
// * @return The evaluated value of the block
// */
// public Object yield(ExecContext ctx, Object... args) {
// if (varNames.length != args.length) {
// throw new IllegalArgumentException();
// }
// Map<String, Object> argMap = new HashMap<String, Object>();
// for (int i = 0; i < varNames.length; i++) {
// argMap.put(varNames[i], args[i]);
// }
// // wrap our block arguments over the underlying context
// StackContext withArgs = new StackContext();
// withArgs.pushExecContext(ctx); // the underlying context
// withArgs.pushExecContext(new VarContext(Collections.unmodifiableMap(argMap))); // args
// return body.value(withArgs);
// };
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/BlockExpression.java
import com.madisp.stupid.Block;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import java.util.Arrays;
package com.madisp.stupid.expr;
/**
* An expression that returns a block when evaluated.
* Usage in stupid: {@code sqr = {|x| x * x }}
*/
public class BlockExpression implements Expression {
private final StatementListExpression body;
private final String[] varNames;
public BlockExpression(String[] varNames, StatementListExpression body) {
this.varNames = Arrays.copyOf(varNames, varNames.length);
this.body = body;
}
@Override | public Object value(final ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/BlockExpression.java | // Path: src/main/java/com/madisp/stupid/Block.java
// public class Block {
// private final StatementListExpression body;
// private final String[] varNames;
//
// /**
// * Create a new block with named arguments
// * @param varNames list of argument names
// * @param body expression that is to be evaluated
// */
// public Block(String[] varNames, StatementListExpression body) {
// this.varNames = Arrays.copyOf(varNames, varNames.length);
// this.body = body;
// }
//
// /**
// * Evaluate the body of a block with given arguments. The length
// * of arguments must match the length of given names in the constructor.
// * @param ctx The context wherein to evaluate the block
// * @param args argument values (must match the same length and order as given
// * in the constructor)
// * @return The evaluated value of the block
// */
// public Object yield(ExecContext ctx, Object... args) {
// if (varNames.length != args.length) {
// throw new IllegalArgumentException();
// }
// Map<String, Object> argMap = new HashMap<String, Object>();
// for (int i = 0; i < varNames.length; i++) {
// argMap.put(varNames[i], args[i]);
// }
// // wrap our block arguments over the underlying context
// StackContext withArgs = new StackContext();
// withArgs.pushExecContext(ctx); // the underlying context
// withArgs.pushExecContext(new VarContext(Collections.unmodifiableMap(argMap))); // args
// return body.value(withArgs);
// };
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.Block;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import java.util.Arrays; | package com.madisp.stupid.expr;
/**
* An expression that returns a block when evaluated.
* Usage in stupid: {@code sqr = {|x| x * x }}
*/
public class BlockExpression implements Expression {
private final StatementListExpression body;
private final String[] varNames;
public BlockExpression(String[] varNames, StatementListExpression body) {
this.varNames = Arrays.copyOf(varNames, varNames.length);
this.body = body;
}
@Override
public Object value(final ExecContext ctx) { | // Path: src/main/java/com/madisp/stupid/Block.java
// public class Block {
// private final StatementListExpression body;
// private final String[] varNames;
//
// /**
// * Create a new block with named arguments
// * @param varNames list of argument names
// * @param body expression that is to be evaluated
// */
// public Block(String[] varNames, StatementListExpression body) {
// this.varNames = Arrays.copyOf(varNames, varNames.length);
// this.body = body;
// }
//
// /**
// * Evaluate the body of a block with given arguments. The length
// * of arguments must match the length of given names in the constructor.
// * @param ctx The context wherein to evaluate the block
// * @param args argument values (must match the same length and order as given
// * in the constructor)
// * @return The evaluated value of the block
// */
// public Object yield(ExecContext ctx, Object... args) {
// if (varNames.length != args.length) {
// throw new IllegalArgumentException();
// }
// Map<String, Object> argMap = new HashMap<String, Object>();
// for (int i = 0; i < varNames.length; i++) {
// argMap.put(varNames[i], args[i]);
// }
// // wrap our block arguments over the underlying context
// StackContext withArgs = new StackContext();
// withArgs.pushExecContext(ctx); // the underlying context
// withArgs.pushExecContext(new VarContext(Collections.unmodifiableMap(argMap))); // args
// return body.value(withArgs);
// };
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/BlockExpression.java
import com.madisp.stupid.Block;
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
import java.util.Arrays;
package com.madisp.stupid.expr;
/**
* An expression that returns a block when evaluated.
* Usage in stupid: {@code sqr = {|x| x * x }}
*/
public class BlockExpression implements Expression {
private final StatementListExpression body;
private final String[] varNames;
public BlockExpression(String[] varNames, StatementListExpression body) {
this.varNames = Arrays.copyOf(varNames, varNames.length);
this.body = body;
}
@Override
public Object value(final ExecContext ctx) { | return new Block(varNames, body); |
madisp/stupid | src/main/java/com/madisp/stupid/expr/MinusExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The arithmetic minus operator. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied.
*
* Usage in stupid: {@code expr - expr}
*/
public class MinusExpression implements Expression {
private final Expression left, right;
public MinusExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/MinusExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The arithmetic minus operator. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied.
*
* Usage in stupid: {@code expr - expr}
*/
public class MinusExpression implements Expression {
private final Expression left, right;
public MinusExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/context/StackContext.java | // Path: src/main/java/com/madisp/stupid/Block.java
// public class Block {
// private final StatementListExpression body;
// private final String[] varNames;
//
// /**
// * Create a new block with named arguments
// * @param varNames list of argument names
// * @param body expression that is to be evaluated
// */
// public Block(String[] varNames, StatementListExpression body) {
// this.varNames = Arrays.copyOf(varNames, varNames.length);
// this.body = body;
// }
//
// /**
// * Evaluate the body of a block with given arguments. The length
// * of arguments must match the length of given names in the constructor.
// * @param ctx The context wherein to evaluate the block
// * @param args argument values (must match the same length and order as given
// * in the constructor)
// * @return The evaluated value of the block
// */
// public Object yield(ExecContext ctx, Object... args) {
// if (varNames.length != args.length) {
// throw new IllegalArgumentException();
// }
// Map<String, Object> argMap = new HashMap<String, Object>();
// for (int i = 0; i < varNames.length; i++) {
// argMap.put(varNames[i], args[i]);
// }
// // wrap our block arguments over the underlying context
// StackContext withArgs = new StackContext();
// withArgs.pushExecContext(ctx); // the underlying context
// withArgs.pushExecContext(new VarContext(Collections.unmodifiableMap(argMap))); // args
// return body.value(withArgs);
// };
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
| import com.madisp.stupid.Block;
import com.madisp.stupid.ExecContext;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList; | @Override
public Object setFieldValue(Object root, String identifier, Object value) {
Iterator<ExecContext> iter = stack.descendingIterator();
while (iter.hasNext()) {
try {
return iter.next().setFieldValue(root, identifier, value);
} catch (NoSuchFieldException e) {
// ignore, jump to next scope
if (false) { e.printStackTrace(); }
}
}
return null;
}
@Override
public Object callMethod(Object root, String identifier, Object... args) {
Iterator<ExecContext> iter = stack.descendingIterator();
while (iter.hasNext()) {
try {
return iter.next().callMethod(dereference(root), identifier, args);
} catch (NoSuchMethodException e) {
// ignore, jump to next scope
if (false) { e.printStackTrace(); }
}
}
return null;
}
@Override
public Object apply(Object base, Object[] args) { | // Path: src/main/java/com/madisp/stupid/Block.java
// public class Block {
// private final StatementListExpression body;
// private final String[] varNames;
//
// /**
// * Create a new block with named arguments
// * @param varNames list of argument names
// * @param body expression that is to be evaluated
// */
// public Block(String[] varNames, StatementListExpression body) {
// this.varNames = Arrays.copyOf(varNames, varNames.length);
// this.body = body;
// }
//
// /**
// * Evaluate the body of a block with given arguments. The length
// * of arguments must match the length of given names in the constructor.
// * @param ctx The context wherein to evaluate the block
// * @param args argument values (must match the same length and order as given
// * in the constructor)
// * @return The evaluated value of the block
// */
// public Object yield(ExecContext ctx, Object... args) {
// if (varNames.length != args.length) {
// throw new IllegalArgumentException();
// }
// Map<String, Object> argMap = new HashMap<String, Object>();
// for (int i = 0; i < varNames.length; i++) {
// argMap.put(varNames[i], args[i]);
// }
// // wrap our block arguments over the underlying context
// StackContext withArgs = new StackContext();
// withArgs.pushExecContext(ctx); // the underlying context
// withArgs.pushExecContext(new VarContext(Collections.unmodifiableMap(argMap))); // args
// return body.value(withArgs);
// };
// }
//
// Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
// Path: src/main/java/com/madisp/stupid/context/StackContext.java
import com.madisp.stupid.Block;
import com.madisp.stupid.ExecContext;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
@Override
public Object setFieldValue(Object root, String identifier, Object value) {
Iterator<ExecContext> iter = stack.descendingIterator();
while (iter.hasNext()) {
try {
return iter.next().setFieldValue(root, identifier, value);
} catch (NoSuchFieldException e) {
// ignore, jump to next scope
if (false) { e.printStackTrace(); }
}
}
return null;
}
@Override
public Object callMethod(Object root, String identifier, Object... args) {
Iterator<ExecContext> iter = stack.descendingIterator();
while (iter.hasNext()) {
try {
return iter.next().callMethod(dereference(root), identifier, args);
} catch (NoSuchMethodException e) {
// ignore, jump to next scope
if (false) { e.printStackTrace(); }
}
}
return null;
}
@Override
public Object apply(Object base, Object[] args) { | if (base instanceof Block) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/TernaryExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The classic ternary expression, e.g. expr ? trueValue : falseValue.
* I know everybody hates it but it has been proven useful from time to time.
*
* In stupid: {@code expr ? trueValue : falseValue}
*/
public class TernaryExpression implements Expression {
private final Expression expression, trueValue, falseValue;
public TernaryExpression(Expression expression, Expression trueValue, Expression falseValue) {
this.expression = expression;
this.trueValue = trueValue;
this.falseValue = falseValue;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/TernaryExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The classic ternary expression, e.g. expr ? trueValue : falseValue.
* I know everybody hates it but it has been proven useful from time to time.
*
* In stupid: {@code expr ? trueValue : falseValue}
*/
public class TernaryExpression implements Expression {
private final Expression expression, trueValue, falseValue;
public TernaryExpression(Expression expression, Expression trueValue, Expression falseValue) {
this.expression = expression;
this.trueValue = trueValue;
this.falseValue = falseValue;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/CallExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* Call a method.
* Usage in stupid: {@code method(arg1, arg2, ..., argN)}, or
* {@code obj.method(arg1, arg2, ..., argN)}.
*/
public class CallExpression implements Expression {
private final Expression base;
private final String identifier;
private final Expression[] args;
public CallExpression(Expression base, String identifier, Expression... args) {
this.base = base;
this.identifier = identifier;
this.args = args;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/CallExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* Call a method.
* Usage in stupid: {@code method(arg1, arg2, ..., argN)}, or
* {@code obj.method(arg1, arg2, ..., argN)}.
*/
public class CallExpression implements Expression {
private final Expression base;
private final String identifier;
private final Expression[] args;
public CallExpression(Expression base, String identifier, Expression... args) {
this.base = base;
this.identifier = identifier;
this.args = args;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/MultiplicationExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The arithmetic multiplication operator. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied.
*
* Usage in stupid: {@code expr * expr}
*/
public class MultiplicationExpression implements Expression {
private final Expression left, right;
public MultiplicationExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/MultiplicationExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The arithmetic multiplication operator. If any of the arguments is a double then
* both of the arguments are converted to double and the return value is also
* a double. Otherwise an Integer is implied.
*
* Usage in stupid: {@code expr * expr}
*/
public class MultiplicationExpression implements Expression {
private final Expression left, right;
public MultiplicationExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override | public Object value(ExecContext ctx) { |
madisp/stupid | src/main/java/com/madisp/stupid/expr/NotExpression.java | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
| import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression; | package com.madisp.stupid.expr;
/**
* The unary boolean not operator.
*
* Usage in stupid: {@code !expr}
*/
public class NotExpression implements Expression<Boolean> {
private final Expression expr;
public NotExpression(Expression expr) {
this.expr = expr;
}
@Override | // Path: src/main/java/com/madisp/stupid/ExecContext.java
// public interface ExecContext {
// /**
// * Get a field value from the environment.
// * @param root The object whose field value is being queried. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @return the Java value of the given field
// * @throws NoSuchFieldException if field was not found / getting value is not supported
// */
// Object getFieldValue(Object root, String identifier) throws NoSuchFieldException;
//
// /**
// * Assigns a value to a field in the environment.
// * @param root The object whose field value is being set. May be null which semantically
// * means getting a value from the "scope" or ExecContext itself.
// * @param identifier field identifier
// * @param value the new value for the field
// * @return if successful, the value itself
// * @throws NoSuchFieldException if the field was not found / setting values is not supported
// */
// Object setFieldValue(Object root, String identifier, Object value) throws NoSuchFieldException;
//
// /**
// * Calls a method in the environment.
// * @param root The object whose method is being called. May be null.
// * @param identifier The method name
// * @param args List of arguments, the types of these will be matched against the methods
// * @return The result of calling {root}.{identifier}({args})
// * @throws NoSuchMethodException if no method with matching signature was found or calling is not supported
// */
// Object callMethod(Object root, String identifier, Object... args) throws NoSuchMethodException;
//
// /**
// * Yield a value with some arguments.
// * Typically used for evaluating {@link Block} instances, but in some implementations
// * may also be used to execute SAM (single-access-method) interface. For an example
// * implementation see {@link com.madisp.stupid.context.ReflectionContext}
// * @param base The object/value to yield
// * @param args The arguments, if any, to apply
// * @return The result of yielding the base object
// * @throws NoSuchMethodException
// */
// Object apply(Object base, Object[] args) throws NoSuchMethodException;
//
// /**
// * Obtain a descriptor for a given resource.
// * The only Android-specific part in stupid. This method was intended to be used
// * for resolving android integer ID's from package-type-name tuplets. It may be
// * reused for other purposes if it makes sense. All implementations in stupid itself
// * currently throw NoSuchFieldException.
// * @param pckg The package name of the resource
// * @param type The type of the resource
// * @param name The identifier for the resource
// * @return An object describing the resource
// * @throws NoSuchFieldException if the resource wasn't found
// */
// Object getResource(String pckg, String type, String name) throws NoSuchFieldException;
//
// /**
// * Dereference an object.
// * Usually this means applying .value(this) onto a value until
// * we have a POJO instance. See {@link com.madisp.stupid.context.BaseContext} for an
// * implementation.
// * @param object The object to dereference. May be null.
// * @return The dereferenced object. May return the same object if it already was dereferenced.
// */
// Object dereference(Object object);
//
// /**
// * Obtain the type coercion rules.
// * @return the Converter defining the type coercion rules for the environment
// */
// Converter getConverter();
// }
//
// Path: src/main/java/com/madisp/stupid/Expression.java
// public interface Expression<T> extends Value<T> {
// /**
// * Get the set of sub-expressions, if any.
// * @return an array of sub-expressions, it may be an empty array
// */
// Expression[] children();
// }
// Path: src/main/java/com/madisp/stupid/expr/NotExpression.java
import com.madisp.stupid.ExecContext;
import com.madisp.stupid.Expression;
package com.madisp.stupid.expr;
/**
* The unary boolean not operator.
*
* Usage in stupid: {@code !expr}
*/
public class NotExpression implements Expression<Boolean> {
private final Expression expr;
public NotExpression(Expression expr) {
this.expr = expr;
}
@Override | public Boolean value(ExecContext ctx) { |
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/ConstructorAnalysisTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static AnalysisResult analyse(
// Class<?> klass, Constructor<?> constructor) throws IOException {
// Class<?>[] parameterTypes = constructor.getParameterTypes();
// InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
// if (in == null) {
// throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
// }
// return analyse(in, klass.getName().replace('.', '/'),
// klass.getSuperclass().getName().replace('.', '/'),
// parameterTypes);
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class FormalParameter implements JavaValue {
// private final int index;
// private final Class<?> kind;
// FormalParameter(int index, Class<?> kind) {
// this.index = index;
// this.kind = kind;
// }
// @Override
// public String toString() {
// return format("p%s", index);
// }
// int getIndex() {
// return index;
// }
// Class<?> getKind() {
// return kind;
// }
// @Override
// public boolean containsFormalParameter() {
// return true;
// }
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class IllegalConstructorException extends RuntimeException {
//
// private static final long serialVersionUID = -7666362130696013958L;
//
// IllegalConstructorException() {
// }
//
// IllegalConstructorException(String format, Object... args) {
// super(format(format, args));
// }
//
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static com.kaching.platform.converters.ConstructorAnalysis.analyse;
import static java.math.BigDecimal.ZERO;
import static java.math.MathContext.DECIMAL32;
import static java.util.Collections.emptyMap;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.kaching.platform.converters.ConstructorAnalysis.FormalParameter;
import com.kaching.platform.converters.ConstructorAnalysis.IllegalConstructorException; | Collections.emptyMap());
}
static class ContainerToTrickLibraryUsingAliasing { List<String> ref; }
static class AliasingResolutionIsNotSupported {
List<String> non_idempotent;
AliasingResolutionIsNotSupported(
ContainerToTrickLibraryUsingAliasing trick,
List<String> names) {
trick.ref = names;
trick.ref.add(Integer.toString(trick.ref.size()));
this.non_idempotent = names;
}
}
@Test
public void aliasingResolutionIsNotSupported() throws Exception {
/* Due to the lack of support for aliasing, one can successfully trick the
* analysis. This is not an important case to protect for.
*/
assertAssignement(
AliasingResolutionIsNotSupported.class,
ImmutableMap.of(
"non_idempotent", "p1"));
}
@Test
public void regression1() throws IOException {
InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class01.bin");
assertNotNull(classInputStream); | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static AnalysisResult analyse(
// Class<?> klass, Constructor<?> constructor) throws IOException {
// Class<?>[] parameterTypes = constructor.getParameterTypes();
// InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
// if (in == null) {
// throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
// }
// return analyse(in, klass.getName().replace('.', '/'),
// klass.getSuperclass().getName().replace('.', '/'),
// parameterTypes);
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class FormalParameter implements JavaValue {
// private final int index;
// private final Class<?> kind;
// FormalParameter(int index, Class<?> kind) {
// this.index = index;
// this.kind = kind;
// }
// @Override
// public String toString() {
// return format("p%s", index);
// }
// int getIndex() {
// return index;
// }
// Class<?> getKind() {
// return kind;
// }
// @Override
// public boolean containsFormalParameter() {
// return true;
// }
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class IllegalConstructorException extends RuntimeException {
//
// private static final long serialVersionUID = -7666362130696013958L;
//
// IllegalConstructorException() {
// }
//
// IllegalConstructorException(String format, Object... args) {
// super(format(format, args));
// }
//
// }
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/ConstructorAnalysisTest.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static com.kaching.platform.converters.ConstructorAnalysis.analyse;
import static java.math.BigDecimal.ZERO;
import static java.math.MathContext.DECIMAL32;
import static java.util.Collections.emptyMap;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.kaching.platform.converters.ConstructorAnalysis.FormalParameter;
import com.kaching.platform.converters.ConstructorAnalysis.IllegalConstructorException;
Collections.emptyMap());
}
static class ContainerToTrickLibraryUsingAliasing { List<String> ref; }
static class AliasingResolutionIsNotSupported {
List<String> non_idempotent;
AliasingResolutionIsNotSupported(
ContainerToTrickLibraryUsingAliasing trick,
List<String> names) {
trick.ref = names;
trick.ref.add(Integer.toString(trick.ref.size()));
this.non_idempotent = names;
}
}
@Test
public void aliasingResolutionIsNotSupported() throws Exception {
/* Due to the lack of support for aliasing, one can successfully trick the
* analysis. This is not an important case to protect for.
*/
assertAssignement(
AliasingResolutionIsNotSupported.class,
ImmutableMap.of(
"non_idempotent", "p1"));
}
@Test
public void regression1() throws IOException {
InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class01.bin");
assertNotNull(classInputStream); | Map<String, FormalParameter> assignements = |
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/ConstructorAnalysisTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static AnalysisResult analyse(
// Class<?> klass, Constructor<?> constructor) throws IOException {
// Class<?>[] parameterTypes = constructor.getParameterTypes();
// InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
// if (in == null) {
// throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
// }
// return analyse(in, klass.getName().replace('.', '/'),
// klass.getSuperclass().getName().replace('.', '/'),
// parameterTypes);
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class FormalParameter implements JavaValue {
// private final int index;
// private final Class<?> kind;
// FormalParameter(int index, Class<?> kind) {
// this.index = index;
// this.kind = kind;
// }
// @Override
// public String toString() {
// return format("p%s", index);
// }
// int getIndex() {
// return index;
// }
// Class<?> getKind() {
// return kind;
// }
// @Override
// public boolean containsFormalParameter() {
// return true;
// }
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class IllegalConstructorException extends RuntimeException {
//
// private static final long serialVersionUID = -7666362130696013958L;
//
// IllegalConstructorException() {
// }
//
// IllegalConstructorException(String format, Object... args) {
// super(format(format, args));
// }
//
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static com.kaching.platform.converters.ConstructorAnalysis.analyse;
import static java.math.BigDecimal.ZERO;
import static java.math.MathContext.DECIMAL32;
import static java.util.Collections.emptyMap;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.kaching.platform.converters.ConstructorAnalysis.FormalParameter;
import com.kaching.platform.converters.ConstructorAnalysis.IllegalConstructorException; | }
static class ContainerToTrickLibraryUsingAliasing { List<String> ref; }
static class AliasingResolutionIsNotSupported {
List<String> non_idempotent;
AliasingResolutionIsNotSupported(
ContainerToTrickLibraryUsingAliasing trick,
List<String> names) {
trick.ref = names;
trick.ref.add(Integer.toString(trick.ref.size()));
this.non_idempotent = names;
}
}
@Test
public void aliasingResolutionIsNotSupported() throws Exception {
/* Due to the lack of support for aliasing, one can successfully trick the
* analysis. This is not an important case to protect for.
*/
assertAssignement(
AliasingResolutionIsNotSupported.class,
ImmutableMap.of(
"non_idempotent", "p1"));
}
@Test
public void regression1() throws IOException {
InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class01.bin");
assertNotNull(classInputStream);
Map<String, FormalParameter> assignements = | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static AnalysisResult analyse(
// Class<?> klass, Constructor<?> constructor) throws IOException {
// Class<?>[] parameterTypes = constructor.getParameterTypes();
// InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
// if (in == null) {
// throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
// }
// return analyse(in, klass.getName().replace('.', '/'),
// klass.getSuperclass().getName().replace('.', '/'),
// parameterTypes);
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class FormalParameter implements JavaValue {
// private final int index;
// private final Class<?> kind;
// FormalParameter(int index, Class<?> kind) {
// this.index = index;
// this.kind = kind;
// }
// @Override
// public String toString() {
// return format("p%s", index);
// }
// int getIndex() {
// return index;
// }
// Class<?> getKind() {
// return kind;
// }
// @Override
// public boolean containsFormalParameter() {
// return true;
// }
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class IllegalConstructorException extends RuntimeException {
//
// private static final long serialVersionUID = -7666362130696013958L;
//
// IllegalConstructorException() {
// }
//
// IllegalConstructorException(String format, Object... args) {
// super(format(format, args));
// }
//
// }
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/ConstructorAnalysisTest.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static com.kaching.platform.converters.ConstructorAnalysis.analyse;
import static java.math.BigDecimal.ZERO;
import static java.math.MathContext.DECIMAL32;
import static java.util.Collections.emptyMap;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.kaching.platform.converters.ConstructorAnalysis.FormalParameter;
import com.kaching.platform.converters.ConstructorAnalysis.IllegalConstructorException;
}
static class ContainerToTrickLibraryUsingAliasing { List<String> ref; }
static class AliasingResolutionIsNotSupported {
List<String> non_idempotent;
AliasingResolutionIsNotSupported(
ContainerToTrickLibraryUsingAliasing trick,
List<String> names) {
trick.ref = names;
trick.ref.add(Integer.toString(trick.ref.size()));
this.non_idempotent = names;
}
}
@Test
public void aliasingResolutionIsNotSupported() throws Exception {
/* Due to the lack of support for aliasing, one can successfully trick the
* analysis. This is not an important case to protect for.
*/
assertAssignement(
AliasingResolutionIsNotSupported.class,
ImmutableMap.of(
"non_idempotent", "p1"));
}
@Test
public void regression1() throws IOException {
InputStream classInputStream = this.getClass().getResourceAsStream("example_scala_class01.bin");
assertNotNull(classInputStream);
Map<String, FormalParameter> assignements = | analyse(classInputStream, |
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/ConstructorAnalysisTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static AnalysisResult analyse(
// Class<?> klass, Constructor<?> constructor) throws IOException {
// Class<?>[] parameterTypes = constructor.getParameterTypes();
// InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
// if (in == null) {
// throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
// }
// return analyse(in, klass.getName().replace('.', '/'),
// klass.getSuperclass().getName().replace('.', '/'),
// parameterTypes);
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class FormalParameter implements JavaValue {
// private final int index;
// private final Class<?> kind;
// FormalParameter(int index, Class<?> kind) {
// this.index = index;
// this.kind = kind;
// }
// @Override
// public String toString() {
// return format("p%s", index);
// }
// int getIndex() {
// return index;
// }
// Class<?> getKind() {
// return kind;
// }
// @Override
// public boolean containsFormalParameter() {
// return true;
// }
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class IllegalConstructorException extends RuntimeException {
//
// private static final long serialVersionUID = -7666362130696013958L;
//
// IllegalConstructorException() {
// }
//
// IllegalConstructorException(String format, Object... args) {
// super(format(format, args));
// }
//
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static com.kaching.platform.converters.ConstructorAnalysis.analyse;
import static java.math.BigDecimal.ZERO;
import static java.math.MathContext.DECIMAL32;
import static java.util.Collections.emptyMap;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.kaching.platform.converters.ConstructorAnalysis.FormalParameter;
import com.kaching.platform.converters.ConstructorAnalysis.IllegalConstructorException; |
@Test
public void callingMethodOnStaticObject() throws Exception {
assertAssignement(
CallingMethodOnStaticObject.class,
Collections.emptyMap());
}
static class BoxingBoolean {
boolean unboxed;
Boolean boxed;
BoxingBoolean(Boolean unboxed, boolean boxed) {
this.unboxed = unboxed;
this.boxed = boxed;
}
}
@Test
public void boxingBoolean() throws Exception {
assertAssignement(
BoxingBoolean.class,
ImmutableMap.of(
"unboxed", "p0",
"boxed", "p1"));
}
private void assertAnalysisFails(Class<?> klass, String message) throws IOException {
try {
ConstructorAnalysis.analyse(klass, klass.getDeclaredConstructors()[0]);
fail("analysis should have failed"); | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static AnalysisResult analyse(
// Class<?> klass, Constructor<?> constructor) throws IOException {
// Class<?>[] parameterTypes = constructor.getParameterTypes();
// InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
// if (in == null) {
// throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
// }
// return analyse(in, klass.getName().replace('.', '/'),
// klass.getSuperclass().getName().replace('.', '/'),
// parameterTypes);
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class FormalParameter implements JavaValue {
// private final int index;
// private final Class<?> kind;
// FormalParameter(int index, Class<?> kind) {
// this.index = index;
// this.kind = kind;
// }
// @Override
// public String toString() {
// return format("p%s", index);
// }
// int getIndex() {
// return index;
// }
// Class<?> getKind() {
// return kind;
// }
// @Override
// public boolean containsFormalParameter() {
// return true;
// }
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/ConstructorAnalysis.java
// static class IllegalConstructorException extends RuntimeException {
//
// private static final long serialVersionUID = -7666362130696013958L;
//
// IllegalConstructorException() {
// }
//
// IllegalConstructorException(String format, Object... args) {
// super(format(format, args));
// }
//
// }
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/ConstructorAnalysisTest.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static com.kaching.platform.converters.ConstructorAnalysis.analyse;
import static java.math.BigDecimal.ZERO;
import static java.math.MathContext.DECIMAL32;
import static java.util.Collections.emptyMap;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.kaching.platform.converters.ConstructorAnalysis.FormalParameter;
import com.kaching.platform.converters.ConstructorAnalysis.IllegalConstructorException;
@Test
public void callingMethodOnStaticObject() throws Exception {
assertAssignement(
CallingMethodOnStaticObject.class,
Collections.emptyMap());
}
static class BoxingBoolean {
boolean unboxed;
Boolean boxed;
BoxingBoolean(Boolean unboxed, boolean boxed) {
this.unboxed = unboxed;
this.boxed = boxed;
}
}
@Test
public void boxingBoolean() throws Exception {
assertAssignement(
BoxingBoolean.class,
ImmutableMap.of(
"unboxed", "p0",
"boxed", "p1"));
}
private void assertAnalysisFails(Class<?> klass, String message) throws IOException {
try {
ConstructorAnalysis.analyse(klass, klass.getDeclaredConstructors()[0]);
fail("analysis should have failed"); | } catch (IllegalConstructorException e) { |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/OptionTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public final class EquivalenceTester {
// private EquivalenceTester() {}
//
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertTrue(format("comparison should return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldNotReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertFalse(format("comparison should not return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// }
| import static com.google.common.collect.Lists.newArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.google.common.base.Function;
import com.kaching.platform.testing.EquivalenceTester;
| /* Note: Parameterizing the none call is required otherwise Object is
* inferred for T and getOrElse(Object) is called instead of
* getOrElse(Thunk<Object>). In practice, the option one would rarely write
* such an expression but rather key off a properly parameterized optional
* value.
*/
assertEquals((Integer) 2, Option.<Integer>none().getOrElse(defaultValue));
assertTrue(defaultValue.isEvaluated());
}
@Test
public void isEmptyIsDefined() {
// isEmpty
assertFalse(Option.some("").isEmpty());
assertTrue(Option.none().isEmpty());
// isDefined
assertTrue(Option.some("").isDefined());
assertFalse(Option.none().isDefined());
}
@Test
public void testOfToString() {
assertEquals("Option.None", Option.none().toString());
assertEquals("Option.Some(string)", Option.some("string").toString());
}
@Test
@SuppressWarnings("unchecked")
public void equivalence() {
| // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public final class EquivalenceTester {
// private EquivalenceTester() {}
//
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertTrue(format("comparison should return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldNotReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertFalse(format("comparison should not return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/OptionTest.java
import static com.google.common.collect.Lists.newArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.google.common.base.Function;
import com.kaching.platform.testing.EquivalenceTester;
/* Note: Parameterizing the none call is required otherwise Object is
* inferred for T and getOrElse(Object) is called instead of
* getOrElse(Thunk<Object>). In practice, the option one would rarely write
* such an expression but rather key off a properly parameterized optional
* value.
*/
assertEquals((Integer) 2, Option.<Integer>none().getOrElse(defaultValue));
assertTrue(defaultValue.isEvaluated());
}
@Test
public void isEmptyIsDefined() {
// isEmpty
assertFalse(Option.some("").isEmpty());
assertTrue(Option.none().isEmpty());
// isDefined
assertTrue(Option.some("").isDefined());
assertFalse(Option.none().isDefined());
}
@Test
public void testOfToString() {
assertEquals("Option.None", Option.none().toString());
assertEquals("Option.Some(string)", Option.some("string").toString());
}
@Test
@SuppressWarnings("unchecked")
public void equivalence() {
| EquivalenceTester.check(
|
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/InstantiatorErrorsTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/InstantiatorErrors.java
// static Errors noSuchField(Errors errors, String fieldName) {
// return errors.addMessage(
// "no such field %s",
// fieldName);
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
| import static com.kaching.platform.converters.InstantiatorErrors.noSuchField;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Errors;
| /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
public class InstantiatorErrorsTest {
@Test
public void incorrectBoundForConverter() {
check(
"the converter interface com.kaching.platform.converters.Converter, " +
"mentioned on class java.lang.String using @ConvertedBy, " +
"does not produce instances of class java.lang.String. It produces " +
"class java.lang.Integer.",
InstantiatorErrors.incorrectBoundForConverter(
| // Path: kawala-converters/src/main/java/com/kaching/platform/converters/InstantiatorErrors.java
// static Errors noSuchField(Errors errors, String fieldName) {
// return errors.addMessage(
// "no such field %s",
// fieldName);
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/InstantiatorErrorsTest.java
import static com.kaching.platform.converters.InstantiatorErrors.noSuchField;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Errors;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
public class InstantiatorErrorsTest {
@Test
public void incorrectBoundForConverter() {
check(
"the converter interface com.kaching.platform.converters.Converter, " +
"mentioned on class java.lang.String using @ConvertedBy, " +
"does not produce instances of class java.lang.String. It produces " +
"class java.lang.Integer.",
InstantiatorErrors.incorrectBoundForConverter(
| new Errors(), String.class, Converter.class, Integer.class));
|
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/InstantiatorErrorsTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/InstantiatorErrors.java
// static Errors noSuchField(Errors errors, String fieldName) {
// return errors.addMessage(
// "no such field %s",
// fieldName);
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
| import static com.kaching.platform.converters.InstantiatorErrors.noSuchField;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Errors;
| public void enumHasAmbiguousNames() {
check(
"enum com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has ambiguous names",
InstantiatorErrors.enumHasAmbiguousNames(
new Errors(), AmbiguousEnum.class));
}
enum AmbiguousEnum {
}
@Test
public void moreThanOneMatchingFunction() {
check(
"class com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has more than one matching function",
InstantiatorErrors.moreThanOneMatchingFunction(
new Errors(), AmbiguousEnum.class));
}
@Test
public void noConverterForType() {
check(
"no converter for java.util.List<java.lang.String>",
InstantiatorErrors.noConverterForType(
new Errors(), new TypeLiteral<List<String>>() {}.getType()));
}
@Test
public void addinTwiceTheSameMessageDoesNotDuplicateTheError() {
check(
"no such field a",
| // Path: kawala-converters/src/main/java/com/kaching/platform/converters/InstantiatorErrors.java
// static Errors noSuchField(Errors errors, String fieldName) {
// return errors.addMessage(
// "no such field %s",
// fieldName);
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/InstantiatorErrorsTest.java
import static com.kaching.platform.converters.InstantiatorErrors.noSuchField;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Errors;
public void enumHasAmbiguousNames() {
check(
"enum com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has ambiguous names",
InstantiatorErrors.enumHasAmbiguousNames(
new Errors(), AmbiguousEnum.class));
}
enum AmbiguousEnum {
}
@Test
public void moreThanOneMatchingFunction() {
check(
"class com.kaching.platform.converters.InstantiatorErrorsTest$AmbiguousEnum has more than one matching function",
InstantiatorErrors.moreThanOneMatchingFunction(
new Errors(), AmbiguousEnum.class));
}
@Test
public void noConverterForType() {
check(
"no converter for java.util.List<java.lang.String>",
InstantiatorErrors.noConverterForType(
new Errors(), new TypeLiteral<List<String>>() {}.getType()));
}
@Test
public void addinTwiceTheSameMessageDoesNotDuplicateTheError() {
check(
"no such field a",
| noSuchField(noSuchField(new Errors(), "a"), "a"));
|
wealthfront/kawala | kawala-converters/src/main/java/com/kaching/platform/converters/InstantiatorErrors.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
| import com.kaching.platform.common.Errors;
import static java.lang.String.format;
import java.lang.reflect.Type;
| /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
/**
* Object helping with capturing and propagating errors.
*/
class InstantiatorErrors {
@SuppressWarnings("rawtypes")
| // Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/InstantiatorErrors.java
import com.kaching.platform.common.Errors;
import static java.lang.String.format;
import java.lang.reflect.Type;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
/**
* Object helping with capturing and propagating errors.
*/
class InstantiatorErrors {
@SuppressWarnings("rawtypes")
| static Errors incorrectBoundForConverter(
|
wealthfront/kawala | srctest/com/kaching/platform/AllTests.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/TestSuiteBuilder.java
// public static TestSuite buildFromRoot(File root) {
// final String testCaseBuildingSuite = builderCaller();
// return buildFromRoot(root, new TestFilter() {
// public boolean shouldIncludeTest(Class<?> test) {
// return !test.getName().equals(testCaseBuildingSuite);
// }
// });
// }
| import static com.kaching.platform.testing.TestSuiteBuilder.buildFromRoot;
import java.io.File;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
| /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform;
public class AllTests extends TestCase {
public static Test suite() {
| // Path: kawala-testing/src/main/java/com/kaching/platform/testing/TestSuiteBuilder.java
// public static TestSuite buildFromRoot(File root) {
// final String testCaseBuildingSuite = builderCaller();
// return buildFromRoot(root, new TestFilter() {
// public boolean shouldIncludeTest(Class<?> test) {
// return !test.getName().equals(testCaseBuildingSuite);
// }
// });
// }
// Path: srctest/com/kaching/platform/AllTests.java
import static com.kaching.platform.testing.TestSuiteBuilder.buildFromRoot;
import java.io.File;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform;
public class AllTests extends TestCase {
public static Test suite() {
| TestSuite suite = buildFromRoot(new File("srctest"));
|
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/types/TypesTest.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/types/Types.java
// public static boolean isAssignableFrom(Type a, Type b) {
// if (a instanceof Class<?>) {
// Class<?> classA = (Class<?>) a;
// if (b instanceof Class<?>) {
// return classA.isAssignableFrom((Class<?>) b);
// } else if (b instanceof GenericArrayType) {
// return classA.isArray() && isAssignableFrom(
// classA.getComponentType(), ((GenericArrayType) b).getGenericComponentType());
// } else if (b instanceof ParameterizedType) {
// return classA.isAssignableFrom((Class<?>) ((ParameterizedType) b).getRawType());
// } else if (b instanceof TypeVariable<?>) {
// TypeVariable<?> typeVariableB = (TypeVariable<?>) b;
// for (Type upperBound : typeVariableB.getBounds()) {
// if (!isAssignableFrom(a, upperBound)) {
// return false;
// }
// }
// return true;
// } else if (b instanceof WildcardType) {
// WildcardType wildcardTypeB = (WildcardType) b;
// for (Type upperBound : wildcardTypeB.getUpperBounds()) {
// if (!isAssignableFrom(a, upperBound)) {
// return false;
// }
// }
// return true;
// }
// } else if (a instanceof GenericArrayType) {
// if (b instanceof GenericArrayType) {
// return isAssignableFrom(
// ((GenericArrayType) a).getGenericComponentType(),
// ((GenericArrayType) b).getGenericComponentType());
// }
// } else if (a instanceof ParameterizedType) {
// ParameterizedType parameterizedTypeA = (ParameterizedType) a;
// if (b instanceof Class<?>) {
// return isAssignableFrom(parameterizedTypeA.getRawType(), b);
// } else if (b instanceof ParameterizedType) {
// ParameterizedType parameterizedTypeB = (ParameterizedType) b;
// Type[] actualTypeArgumentsA = parameterizedTypeA.getActualTypeArguments();
// Type[] actualTypeArgumentsB = parameterizedTypeB.getActualTypeArguments();
// if (actualTypeArgumentsA.length != actualTypeArgumentsB.length) {
// return false;
// }
// for (int i = 0; i < actualTypeArgumentsA.length; i++) {
// if (!isInstance(actualTypeArgumentsA[i], actualTypeArgumentsB[i])) {
// return false;
// }
// }
// return isAssignableFrom(
// parameterizedTypeA.getRawType(),
// parameterizedTypeB.getRawType());
// }
// } else if (a instanceof TypeVariable<?>) {
// for (Type bound : ((TypeVariable<?>) a).getBounds()) {
// if (!isAssignableFrom(bound, b)) {
// return false;
// }
// }
// return true;
// } else if (a instanceof WildcardType) {
// WildcardType wildcardType = (WildcardType) a;
// Type[] lowerBounds = wildcardType.getLowerBounds();
// for (Type lowerBound : lowerBounds) {
// if (!isAssignableFrom(lowerBound, b)) {
// return false;
// }
// }
// return lowerBounds.length != 0;
// }
// return false;
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/types/Types.java
// public static boolean isInstance(Type a, Type b) {
// if (a instanceof Class<?>) {
// return a.equals(b);
// } else if (a instanceof GenericArrayType) {
// if (b instanceof GenericArrayType) {
// return isInstance(
// ((GenericArrayType) a).getGenericComponentType(),
// ((GenericArrayType) b).getGenericComponentType());
// } else {
// return false;
// }
// } else if (a instanceof ParameterizedType) {
// if (!(b instanceof ParameterizedType)) {
// return false;
// }
// ParameterizedType parameterizedTypeA = (ParameterizedType) a;
// ParameterizedType parameterizedTypeB = (ParameterizedType) b;
// Type[] actualTypeArgumentsA = parameterizedTypeA.getActualTypeArguments();
// Type[] actualTypeArgumentsB = parameterizedTypeB.getActualTypeArguments();
// if (!parameterizedTypeA.getRawType().equals(parameterizedTypeB.getRawType()) ||
// actualTypeArgumentsA.length != actualTypeArgumentsB.length) {
// return false;
// }
// for (int i = 0; i < actualTypeArgumentsA.length; i++) {
// if (!isInstance(actualTypeArgumentsA[i], actualTypeArgumentsB[i])) {
// return false;
// }
// }
// return true;
// } else if (a instanceof TypeVariable<?>) {
// TypeVariable<?> typeVariable = (TypeVariable<?>) a;
// for (Type bound : typeVariable.getBounds()) {
// return isAssignableFrom(bound, b);
// }
// return true;
// } else if (a instanceof WildcardType) {
// WildcardType wildcardType = (WildcardType) a;
// for (Type lowerBound : wildcardType.getLowerBounds()) {
// if (!isAssignableFrom(b, lowerBound)) {
// return false;
// }
// }
// for (Type upperBound : wildcardType.getUpperBounds()) {
// if (!isAssignableFrom(upperBound, b)) {
// return false;
// }
// }
// return true;
// }
// throw new IllegalStateException();
// }
| import static com.google.inject.util.Types.listOf;
import static com.google.inject.util.Types.newParameterizedType;
import static com.google.inject.util.Types.setOf;
import static com.google.inject.util.Types.subtypeOf;
import static com.google.inject.util.Types.supertypeOf;
import static com.kaching.platform.common.types.Types.isAssignableFrom;
import static com.kaching.platform.common.types.Types.isInstance;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.io.Serializable;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Test;
import com.google.inject.TypeLiteral; | package com.kaching.platform.common.types;
public class TypesTest {
@Test
public void testIsInstance() {
// class | // Path: kawala-common/src/main/java/com/kaching/platform/common/types/Types.java
// public static boolean isAssignableFrom(Type a, Type b) {
// if (a instanceof Class<?>) {
// Class<?> classA = (Class<?>) a;
// if (b instanceof Class<?>) {
// return classA.isAssignableFrom((Class<?>) b);
// } else if (b instanceof GenericArrayType) {
// return classA.isArray() && isAssignableFrom(
// classA.getComponentType(), ((GenericArrayType) b).getGenericComponentType());
// } else if (b instanceof ParameterizedType) {
// return classA.isAssignableFrom((Class<?>) ((ParameterizedType) b).getRawType());
// } else if (b instanceof TypeVariable<?>) {
// TypeVariable<?> typeVariableB = (TypeVariable<?>) b;
// for (Type upperBound : typeVariableB.getBounds()) {
// if (!isAssignableFrom(a, upperBound)) {
// return false;
// }
// }
// return true;
// } else if (b instanceof WildcardType) {
// WildcardType wildcardTypeB = (WildcardType) b;
// for (Type upperBound : wildcardTypeB.getUpperBounds()) {
// if (!isAssignableFrom(a, upperBound)) {
// return false;
// }
// }
// return true;
// }
// } else if (a instanceof GenericArrayType) {
// if (b instanceof GenericArrayType) {
// return isAssignableFrom(
// ((GenericArrayType) a).getGenericComponentType(),
// ((GenericArrayType) b).getGenericComponentType());
// }
// } else if (a instanceof ParameterizedType) {
// ParameterizedType parameterizedTypeA = (ParameterizedType) a;
// if (b instanceof Class<?>) {
// return isAssignableFrom(parameterizedTypeA.getRawType(), b);
// } else if (b instanceof ParameterizedType) {
// ParameterizedType parameterizedTypeB = (ParameterizedType) b;
// Type[] actualTypeArgumentsA = parameterizedTypeA.getActualTypeArguments();
// Type[] actualTypeArgumentsB = parameterizedTypeB.getActualTypeArguments();
// if (actualTypeArgumentsA.length != actualTypeArgumentsB.length) {
// return false;
// }
// for (int i = 0; i < actualTypeArgumentsA.length; i++) {
// if (!isInstance(actualTypeArgumentsA[i], actualTypeArgumentsB[i])) {
// return false;
// }
// }
// return isAssignableFrom(
// parameterizedTypeA.getRawType(),
// parameterizedTypeB.getRawType());
// }
// } else if (a instanceof TypeVariable<?>) {
// for (Type bound : ((TypeVariable<?>) a).getBounds()) {
// if (!isAssignableFrom(bound, b)) {
// return false;
// }
// }
// return true;
// } else if (a instanceof WildcardType) {
// WildcardType wildcardType = (WildcardType) a;
// Type[] lowerBounds = wildcardType.getLowerBounds();
// for (Type lowerBound : lowerBounds) {
// if (!isAssignableFrom(lowerBound, b)) {
// return false;
// }
// }
// return lowerBounds.length != 0;
// }
// return false;
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/types/Types.java
// public static boolean isInstance(Type a, Type b) {
// if (a instanceof Class<?>) {
// return a.equals(b);
// } else if (a instanceof GenericArrayType) {
// if (b instanceof GenericArrayType) {
// return isInstance(
// ((GenericArrayType) a).getGenericComponentType(),
// ((GenericArrayType) b).getGenericComponentType());
// } else {
// return false;
// }
// } else if (a instanceof ParameterizedType) {
// if (!(b instanceof ParameterizedType)) {
// return false;
// }
// ParameterizedType parameterizedTypeA = (ParameterizedType) a;
// ParameterizedType parameterizedTypeB = (ParameterizedType) b;
// Type[] actualTypeArgumentsA = parameterizedTypeA.getActualTypeArguments();
// Type[] actualTypeArgumentsB = parameterizedTypeB.getActualTypeArguments();
// if (!parameterizedTypeA.getRawType().equals(parameterizedTypeB.getRawType()) ||
// actualTypeArgumentsA.length != actualTypeArgumentsB.length) {
// return false;
// }
// for (int i = 0; i < actualTypeArgumentsA.length; i++) {
// if (!isInstance(actualTypeArgumentsA[i], actualTypeArgumentsB[i])) {
// return false;
// }
// }
// return true;
// } else if (a instanceof TypeVariable<?>) {
// TypeVariable<?> typeVariable = (TypeVariable<?>) a;
// for (Type bound : typeVariable.getBounds()) {
// return isAssignableFrom(bound, b);
// }
// return true;
// } else if (a instanceof WildcardType) {
// WildcardType wildcardType = (WildcardType) a;
// for (Type lowerBound : wildcardType.getLowerBounds()) {
// if (!isAssignableFrom(b, lowerBound)) {
// return false;
// }
// }
// for (Type upperBound : wildcardType.getUpperBounds()) {
// if (!isAssignableFrom(upperBound, b)) {
// return false;
// }
// }
// return true;
// }
// throw new IllegalStateException();
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/types/TypesTest.java
import static com.google.inject.util.Types.listOf;
import static com.google.inject.util.Types.newParameterizedType;
import static com.google.inject.util.Types.setOf;
import static com.google.inject.util.Types.subtypeOf;
import static com.google.inject.util.Types.supertypeOf;
import static com.kaching.platform.common.types.Types.isAssignableFrom;
import static com.kaching.platform.common.types.Types.isInstance;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.io.Serializable;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Test;
import com.google.inject.TypeLiteral;
package com.kaching.platform.common.types;
public class TypesTest {
@Test
public void testIsInstance() {
// class | assertTrue(isInstance(String.class, String.class)); |
wealthfront/kawala | kawala-testing/src/main/java/com/kaching/platform/testing/ParsedElements.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/Strings.java
// public static String format(String template, Object... args) {
// template = String.valueOf(template); // null -> "null"
//
// // start substituting the arguments into the '%s' placeholders
// StringBuilder builder = new StringBuilder(
// template.length() + 16 * args.length);
// int templateStart = 0;
// int i = 0;
// while (i < args.length) {
// int placeholderStart = template.indexOf("%s", templateStart);
// if (placeholderStart == -1) {
// break;
// }
// builder.append(template.substring(templateStart, placeholderStart));
// builder.append(args[i++]);
// templateStart = placeholderStart + 2;
// }
// builder.append(template.substring(templateStart));
//
// // if we run out of placeholders, append the extra args in square braces
// if (i < args.length) {
// builder.append(" [");
// builder.append(args[i++]);
// while (i < args.length) {
// builder.append(", ");
// builder.append(args[i++]);
// }
// builder.append("]");
// }
//
// return builder.toString();
// }
| import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;
import static com.kaching.platform.common.Strings.format;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.objectweb.asm.Type;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
public class ParsedElements {
public static class ParsedClass implements ParsedElement {
private final String name;
public ParsedClass(String name) {
this.name = name.replace("/", ".");
}
String getPackageName() {
return name.substring(0, name.split("\\$")[0].lastIndexOf('.'));
}
public String getOwner() {
return name.split("\\$")[0];
}
Class<?> load() {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
Annotation loadAnnotation(Class<? extends Annotation> annotation) {
Class<?> clazz = load();
if (clazz == null) { | // Path: kawala-common/src/main/java/com/kaching/platform/common/Strings.java
// public static String format(String template, Object... args) {
// template = String.valueOf(template); // null -> "null"
//
// // start substituting the arguments into the '%s' placeholders
// StringBuilder builder = new StringBuilder(
// template.length() + 16 * args.length);
// int templateStart = 0;
// int i = 0;
// while (i < args.length) {
// int placeholderStart = template.indexOf("%s", templateStart);
// if (placeholderStart == -1) {
// break;
// }
// builder.append(template.substring(templateStart, placeholderStart));
// builder.append(args[i++]);
// templateStart = placeholderStart + 2;
// }
// builder.append(template.substring(templateStart));
//
// // if we run out of placeholders, append the extra args in square braces
// if (i < args.length) {
// builder.append(" [");
// builder.append(args[i++]);
// while (i < args.length) {
// builder.append(", ");
// builder.append(args[i++]);
// }
// builder.append("]");
// }
//
// return builder.toString();
// }
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/ParsedElements.java
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;
import static com.kaching.platform.common.Strings.format;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.objectweb.asm.Type;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
public class ParsedElements {
public static class ParsedClass implements ParsedElement {
private final String name;
public ParsedClass(String name) {
this.name = name.replace("/", ".");
}
String getPackageName() {
return name.substring(0, name.split("\\$")[0].lastIndexOf('.'));
}
public String getOwner() {
return name.split("\\$")[0];
}
Class<?> load() {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
Annotation loadAnnotation(Class<? extends Annotation> annotation) {
Class<?> clazz = load();
if (clazz == null) { | throw new NullPointerException(format("class %s not found", name)); |
wealthfront/kawala | kawala-common/src/main/java/com/kaching/platform/common/logging/Log.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/Strings.java
// public static String format(String template, Object... args) {
// template = String.valueOf(template); // null -> "null"
//
// // start substituting the arguments into the '%s' placeholders
// StringBuilder builder = new StringBuilder(
// template.length() + 16 * args.length);
// int templateStart = 0;
// int i = 0;
// while (i < args.length) {
// int placeholderStart = template.indexOf("%s", templateStart);
// if (placeholderStart == -1) {
// break;
// }
// builder.append(template.substring(templateStart, placeholderStart));
// builder.append(args[i++]);
// templateStart = placeholderStart + 2;
// }
// builder.append(template.substring(templateStart));
//
// // if we run out of placeholders, append the extra args in square braces
// if (i < args.length) {
// builder.append(" [");
// builder.append(args[i++]);
// while (i < args.length) {
// builder.append(", ");
// builder.append(args[i++]);
// }
// builder.append("]");
// }
//
// return builder.toString();
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
| import static com.kaching.platform.common.Strings.format;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.perf4j.commonslog.CommonsLogStopWatch;
import com.google.common.annotations.VisibleForTesting;
import com.kaching.platform.common.Pair; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common.logging;
/**
* A convenient interface on top of Log4J that makes using log4j along with
* {@link String#format(String, Object...)} more concise. Its interface is
* similar to log4j's {@link org.apache.commons.logging.Log} with the addition
* of varargs arguments that are used to render the any format specifiers in the
* log message.
*/
public class Log {
public static Log getLog(Class<?> clazz) {
return new Log(clazz);
}
public static Log getLog(String name) {
return new Log(name);
}
public static void logContextPut(String key, Object value) {
MDC.put(key, value);
}
public static void logContextRemove(String key) {
MDC.remove(key);
}
public static void withLogContext(Runnable runnable, | // Path: kawala-common/src/main/java/com/kaching/platform/common/Strings.java
// public static String format(String template, Object... args) {
// template = String.valueOf(template); // null -> "null"
//
// // start substituting the arguments into the '%s' placeholders
// StringBuilder builder = new StringBuilder(
// template.length() + 16 * args.length);
// int templateStart = 0;
// int i = 0;
// while (i < args.length) {
// int placeholderStart = template.indexOf("%s", templateStart);
// if (placeholderStart == -1) {
// break;
// }
// builder.append(template.substring(templateStart, placeholderStart));
// builder.append(args[i++]);
// templateStart = placeholderStart + 2;
// }
// builder.append(template.substring(templateStart));
//
// // if we run out of placeholders, append the extra args in square braces
// if (i < args.length) {
// builder.append(" [");
// builder.append(args[i++]);
// while (i < args.length) {
// builder.append(", ");
// builder.append(args[i++]);
// }
// builder.append("]");
// }
//
// return builder.toString();
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
// Path: kawala-common/src/main/java/com/kaching/platform/common/logging/Log.java
import static com.kaching.platform.common.Strings.format;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.perf4j.commonslog.CommonsLogStopWatch;
import com.google.common.annotations.VisibleForTesting;
import com.kaching.platform.common.Pair;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common.logging;
/**
* A convenient interface on top of Log4J that makes using log4j along with
* {@link String#format(String, Object...)} more concise. Its interface is
* similar to log4j's {@link org.apache.commons.logging.Log} with the addition
* of varargs arguments that are used to render the any format specifiers in the
* log message.
*/
public class Log {
public static Log getLog(Class<?> clazz) {
return new Log(clazz);
}
public static Log getLog(String name) {
return new Log(name);
}
public static void logContextPut(String key, Object value) {
MDC.put(key, value);
}
public static void logContextRemove(String key) {
MDC.remove(key);
}
public static void withLogContext(Runnable runnable, | Pair<String, Object>... contexts) { |
wealthfront/kawala | kawala-common/src/main/java/com/kaching/platform/common/logging/Log.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/Strings.java
// public static String format(String template, Object... args) {
// template = String.valueOf(template); // null -> "null"
//
// // start substituting the arguments into the '%s' placeholders
// StringBuilder builder = new StringBuilder(
// template.length() + 16 * args.length);
// int templateStart = 0;
// int i = 0;
// while (i < args.length) {
// int placeholderStart = template.indexOf("%s", templateStart);
// if (placeholderStart == -1) {
// break;
// }
// builder.append(template.substring(templateStart, placeholderStart));
// builder.append(args[i++]);
// templateStart = placeholderStart + 2;
// }
// builder.append(template.substring(templateStart));
//
// // if we run out of placeholders, append the extra args in square braces
// if (i < args.length) {
// builder.append(" [");
// builder.append(args[i++]);
// while (i < args.length) {
// builder.append(", ");
// builder.append(args[i++]);
// }
// builder.append("]");
// }
//
// return builder.toString();
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
| import static com.kaching.platform.common.Strings.format;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.perf4j.commonslog.CommonsLogStopWatch;
import com.google.common.annotations.VisibleForTesting;
import com.kaching.platform.common.Pair; | runnable.run();
} finally {
for (Pair<String, Object> context : contexts) {
logContextRemove(context.left);
}
}
}
private final org.apache.commons.logging.Log log;
@VisibleForTesting
Log(Class<?> clazz) {
this.log = LogFactory.getLog(clazz);
}
@VisibleForTesting
Log(String name) {
this.log = LogFactory.getLog(name);
}
public boolean isTraceEnabled() {
return log.isTraceEnabled();
}
public void trace(String message) {
if (log.isTraceEnabled()) {
log.trace(message);
}
}
| // Path: kawala-common/src/main/java/com/kaching/platform/common/Strings.java
// public static String format(String template, Object... args) {
// template = String.valueOf(template); // null -> "null"
//
// // start substituting the arguments into the '%s' placeholders
// StringBuilder builder = new StringBuilder(
// template.length() + 16 * args.length);
// int templateStart = 0;
// int i = 0;
// while (i < args.length) {
// int placeholderStart = template.indexOf("%s", templateStart);
// if (placeholderStart == -1) {
// break;
// }
// builder.append(template.substring(templateStart, placeholderStart));
// builder.append(args[i++]);
// templateStart = placeholderStart + 2;
// }
// builder.append(template.substring(templateStart));
//
// // if we run out of placeholders, append the extra args in square braces
// if (i < args.length) {
// builder.append(" [");
// builder.append(args[i++]);
// while (i < args.length) {
// builder.append(", ");
// builder.append(args[i++]);
// }
// builder.append("]");
// }
//
// return builder.toString();
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
// Path: kawala-common/src/main/java/com/kaching/platform/common/logging/Log.java
import static com.kaching.platform.common.Strings.format;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.perf4j.commonslog.CommonsLogStopWatch;
import com.google.common.annotations.VisibleForTesting;
import com.kaching.platform.common.Pair;
runnable.run();
} finally {
for (Pair<String, Object> context : contexts) {
logContextRemove(context.left);
}
}
}
private final org.apache.commons.logging.Log log;
@VisibleForTesting
Log(Class<?> clazz) {
this.log = LogFactory.getLog(clazz);
}
@VisibleForTesting
Log(String name) {
this.log = LogFactory.getLog(name);
}
public boolean isTraceEnabled() {
return log.isTraceEnabled();
}
public void trace(String message) {
if (log.isTraceEnabled()) {
log.trace(message);
}
}
| public void trace(String format, Object... args) { |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/RangeTest.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/Range.java
// public static Range range(int start, int end) {
// return new Range(start, end);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
| import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.common.Range.range;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test; | package com.kaching.platform.common;
public class RangeTest {
@Test
public void testContains() throws Exception {
assertTrue(new Range(0, 5).contains(new Range(2, 4)));
assertTrue(new Range(0, 5).contains(new Range(0, 5)));
assertFalse(new Range(3, 5).contains(new Range(0, 5)));
assertFalse(new Range(0, 5).contains(new Range(0, 6)));
assertFalse(new Range(0, 5).contains(new Range(7, 8)));
}
@Test
public void testOverlaps() throws Exception {
assertTrue(new Range(0, 5).overlaps(new Range(2, 4)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(3, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 6)));
assertFalse(new Range(0, 5).overlaps(new Range(7, 8)));
assertFalse(new Range(4, 6).overlaps(new Range(0, 4)));
assertTrue(new Range(3, 6).overlaps(new Range(0, 4)));
assertFalse(new Range(4, 6).overlaps(new Range(6, 7)));
assertTrue(new Range(4, 6).overlaps(new Range(5, 7)));
assertTrue(new Range(0, 22).overlaps(new Range(13, 16)));
assertTrue(new Range(13, 16).overlaps(new Range(0, 22)));
}
@Test
public void equivalence() { | // Path: kawala-common/src/main/java/com/kaching/platform/common/Range.java
// public static Range range(int start, int end) {
// return new Range(start, end);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/RangeTest.java
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.common.Range.range;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
package com.kaching.platform.common;
public class RangeTest {
@Test
public void testContains() throws Exception {
assertTrue(new Range(0, 5).contains(new Range(2, 4)));
assertTrue(new Range(0, 5).contains(new Range(0, 5)));
assertFalse(new Range(3, 5).contains(new Range(0, 5)));
assertFalse(new Range(0, 5).contains(new Range(0, 6)));
assertFalse(new Range(0, 5).contains(new Range(7, 8)));
}
@Test
public void testOverlaps() throws Exception {
assertTrue(new Range(0, 5).overlaps(new Range(2, 4)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(3, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 6)));
assertFalse(new Range(0, 5).overlaps(new Range(7, 8)));
assertFalse(new Range(4, 6).overlaps(new Range(0, 4)));
assertTrue(new Range(3, 6).overlaps(new Range(0, 4)));
assertFalse(new Range(4, 6).overlaps(new Range(6, 7)));
assertTrue(new Range(4, 6).overlaps(new Range(5, 7)));
assertTrue(new Range(0, 22).overlaps(new Range(13, 16)));
assertTrue(new Range(13, 16).overlaps(new Range(0, 22)));
}
@Test
public void equivalence() { | check( |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/RangeTest.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/Range.java
// public static Range range(int start, int end) {
// return new Range(start, end);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
| import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.common.Range.range;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test; | }
@Test
public void testOverlaps() throws Exception {
assertTrue(new Range(0, 5).overlaps(new Range(2, 4)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(3, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 6)));
assertFalse(new Range(0, 5).overlaps(new Range(7, 8)));
assertFalse(new Range(4, 6).overlaps(new Range(0, 4)));
assertTrue(new Range(3, 6).overlaps(new Range(0, 4)));
assertFalse(new Range(4, 6).overlaps(new Range(6, 7)));
assertTrue(new Range(4, 6).overlaps(new Range(5, 7)));
assertTrue(new Range(0, 22).overlaps(new Range(13, 16)));
assertTrue(new Range(13, 16).overlaps(new Range(0, 22)));
}
@Test
public void equivalence() {
check(
newArrayList(
new Range(0, 2),
new Range(0, 2)),
newArrayList(
new Range(1, 3),
new Range(1, 3)));
}
@Test public void itShouldBeFunctional() {
List<Integer> accumulator = new ArrayList<Integer>(); | // Path: kawala-common/src/main/java/com/kaching/platform/common/Range.java
// public static Range range(int start, int end) {
// return new Range(start, end);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/RangeTest.java
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.common.Range.range;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
}
@Test
public void testOverlaps() throws Exception {
assertTrue(new Range(0, 5).overlaps(new Range(2, 4)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(3, 5).overlaps(new Range(0, 5)));
assertTrue(new Range(0, 5).overlaps(new Range(0, 6)));
assertFalse(new Range(0, 5).overlaps(new Range(7, 8)));
assertFalse(new Range(4, 6).overlaps(new Range(0, 4)));
assertTrue(new Range(3, 6).overlaps(new Range(0, 4)));
assertFalse(new Range(4, 6).overlaps(new Range(6, 7)));
assertTrue(new Range(4, 6).overlaps(new Range(5, 7)));
assertTrue(new Range(0, 22).overlaps(new Range(13, 16)));
assertTrue(new Range(13, 16).overlaps(new Range(0, 22)));
}
@Test
public void equivalence() {
check(
newArrayList(
new Range(0, 2),
new Range(0, 2)),
newArrayList(
new Range(1, 3),
new Range(1, 3)));
}
@Test public void itShouldBeFunctional() {
List<Integer> accumulator = new ArrayList<Integer>(); | for (Integer i : range(1, 10)) { |
wealthfront/kawala | kawala-testing/src/test/java/com/kaching/platform/testing/AssertTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertBigDecimalEquals(double d1, BigDecimal d2) {
// assertBigDecimalEquals(null, d1, d2);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertFloatEquals(float f1, float f2) {
// assertBigDecimalEquals(null, new BigDecimal(Float.toString(f1)),
// new BigDecimal(Float.toString(f2)));
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
| import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.Assert.assertBigDecimalEquals;
import static com.kaching.platform.testing.Assert.assertFloatEquals;
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;
import static java.math.BigDecimal.valueOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.List;
import org.junit.ComparisonFailure;
import org.junit.Test; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
public class AssertTest {
@Test
public void assertBigDecimalEquals1() { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertBigDecimalEquals(double d1, BigDecimal d2) {
// assertBigDecimalEquals(null, d1, d2);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertFloatEquals(float f1, float f2) {
// assertBigDecimalEquals(null, new BigDecimal(Float.toString(f1)),
// new BigDecimal(Float.toString(f2)));
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
// Path: kawala-testing/src/test/java/com/kaching/platform/testing/AssertTest.java
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.Assert.assertBigDecimalEquals;
import static com.kaching.platform.testing.Assert.assertFloatEquals;
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;
import static java.math.BigDecimal.valueOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.List;
import org.junit.ComparisonFailure;
import org.junit.Test;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
public class AssertTest {
@Test
public void assertBigDecimalEquals1() { | assertBigDecimalEquals((BigDecimal) null, null); |
wealthfront/kawala | kawala-testing/src/test/java/com/kaching/platform/testing/AssertTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertBigDecimalEquals(double d1, BigDecimal d2) {
// assertBigDecimalEquals(null, d1, d2);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertFloatEquals(float f1, float f2) {
// assertBigDecimalEquals(null, new BigDecimal(Float.toString(f1)),
// new BigDecimal(Float.toString(f2)));
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
| import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.Assert.assertBigDecimalEquals;
import static com.kaching.platform.testing.Assert.assertFloatEquals;
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;
import static java.math.BigDecimal.valueOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.List;
import org.junit.ComparisonFailure;
import org.junit.Test; | e.getMessage());
}
}
@Test
public void assertBigDecimalEquals3_onLists() {
try {
assertBigDecimalEquals(
newArrayList(new BigDecimal("2"), valueOf(3)), null);
} catch (AssertionError e) {
assertEquals(
"expected:<[2, 3]> but was:<null>",
e.getMessage());
}
}
@Test
public void assertBigDecimalEquals4_onLists() {
try {
assertBigDecimalEquals(
null, newArrayList(new BigDecimal("2"), valueOf(3)));
} catch (AssertionError e) {
assertEquals(
"expected:<null> but was:<[2, 3]>",
e.getMessage());
}
}
@Test
public void assertNotEquals1() throws Exception { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertBigDecimalEquals(double d1, BigDecimal d2) {
// assertBigDecimalEquals(null, d1, d2);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertFloatEquals(float f1, float f2) {
// assertBigDecimalEquals(null, new BigDecimal(Float.toString(f1)),
// new BigDecimal(Float.toString(f2)));
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
// Path: kawala-testing/src/test/java/com/kaching/platform/testing/AssertTest.java
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.Assert.assertBigDecimalEquals;
import static com.kaching.platform.testing.Assert.assertFloatEquals;
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;
import static java.math.BigDecimal.valueOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.List;
import org.junit.ComparisonFailure;
import org.junit.Test;
e.getMessage());
}
}
@Test
public void assertBigDecimalEquals3_onLists() {
try {
assertBigDecimalEquals(
newArrayList(new BigDecimal("2"), valueOf(3)), null);
} catch (AssertionError e) {
assertEquals(
"expected:<[2, 3]> but was:<null>",
e.getMessage());
}
}
@Test
public void assertBigDecimalEquals4_onLists() {
try {
assertBigDecimalEquals(
null, newArrayList(new BigDecimal("2"), valueOf(3)));
} catch (AssertionError e) {
assertEquals(
"expected:<null> but was:<[2, 3]>",
e.getMessage());
}
}
@Test
public void assertNotEquals1() throws Exception { | assertNotEquals(1, 2); |
wealthfront/kawala | kawala-testing/src/test/java/com/kaching/platform/testing/AssertTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertBigDecimalEquals(double d1, BigDecimal d2) {
// assertBigDecimalEquals(null, d1, d2);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertFloatEquals(float f1, float f2) {
// assertBigDecimalEquals(null, new BigDecimal(Float.toString(f1)),
// new BigDecimal(Float.toString(f2)));
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
| import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.Assert.assertBigDecimalEquals;
import static com.kaching.platform.testing.Assert.assertFloatEquals;
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;
import static java.math.BigDecimal.valueOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.List;
import org.junit.ComparisonFailure;
import org.junit.Test; |
@Test
public void assertNotEquals1() throws Exception {
assertNotEquals(1, 2);
assertNotEquals("foo", "bar");
assertNotEquals(1, null);
assertNotEquals(null, 2);
}
@Test
public void assertNotEquals2() throws Exception {
try {
assertNotEquals(1, 1);
fail();
} catch (AssertionError e) {
}
try {
assertNotEquals("foo", "foo");
fail();
} catch (AssertionError e) {
}
try {
assertNotEquals(null, null);
fail();
} catch (AssertionError e) {
}
}
@Test
public void assertFloatEquals1() throws Exception { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertBigDecimalEquals(double d1, BigDecimal d2) {
// assertBigDecimalEquals(null, d1, d2);
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// public static void assertFloatEquals(float f1, float f2) {
// assertBigDecimalEquals(null, new BigDecimal(Float.toString(f1)),
// new BigDecimal(Float.toString(f2)));
// }
//
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
// Path: kawala-testing/src/test/java/com/kaching/platform/testing/AssertTest.java
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.Assert.assertBigDecimalEquals;
import static com.kaching.platform.testing.Assert.assertFloatEquals;
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static java.math.BigDecimal.ONE;
import static java.math.BigDecimal.ZERO;
import static java.math.BigDecimal.valueOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.List;
import org.junit.ComparisonFailure;
import org.junit.Test;
@Test
public void assertNotEquals1() throws Exception {
assertNotEquals(1, 2);
assertNotEquals("foo", "bar");
assertNotEquals(1, null);
assertNotEquals(null, 2);
}
@Test
public void assertNotEquals2() throws Exception {
try {
assertNotEquals(1, 1);
fail();
} catch (AssertionError e) {
}
try {
assertNotEquals("foo", "foo");
fail();
} catch (AssertionError e) {
}
try {
assertNotEquals(null, null);
fail();
} catch (AssertionError e) {
}
}
@Test
public void assertFloatEquals1() throws Exception { | assertFloatEquals(0.00100f, 0.001f); |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/ErrorsTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public final class EquivalenceTester {
// private EquivalenceTester() {}
//
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertTrue(format("comparison should return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldNotReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertFalse(format("comparison should not return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// }
| import static com.google.common.collect.Lists.newArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.kaching.platform.testing.EquivalenceTester; | new Errors().throwIfHasErrors();
}
@Test
public void hasErrors() {
assertFalse(new Errors().hasErrors());
assertTrue(new Errors().addMessage("").hasErrors());
}
@Test
public void aggregate1() {
assertEquals(
2,
new Errors().addMessage("a").addErrors(new Errors().addMessage("b")).size());
}
@Test
public void aggregate2() {
assertEquals(
1,
new Errors().addMessage("a").addErrors(new Errors().addMessage("a")).size());
}
@Test
public void aggregate3() {
assertFalse(new Errors().addErrors(new Errors()).hasErrors());
}
@Test
public void equivalence() { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public final class EquivalenceTester {
// private EquivalenceTester() {}
//
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertTrue(format("comparison should return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldNotReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertFalse(format("comparison should not return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/ErrorsTest.java
import static com.google.common.collect.Lists.newArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.kaching.platform.testing.EquivalenceTester;
new Errors().throwIfHasErrors();
}
@Test
public void hasErrors() {
assertFalse(new Errors().hasErrors());
assertTrue(new Errors().addMessage("").hasErrors());
}
@Test
public void aggregate1() {
assertEquals(
2,
new Errors().addMessage("a").addErrors(new Errors().addMessage("b")).size());
}
@Test
public void aggregate2() {
assertEquals(
1,
new Errors().addMessage("a").addErrors(new Errors().addMessage("a")).size());
}
@Test
public void aggregate3() {
assertFalse(new Errors().addErrors(new Errors()).hasErrors());
}
@Test
public void equivalence() { | EquivalenceTester.check( |
wealthfront/kawala | kawala-guice/src/test/java/com/kaching/platform/guice/TypeLiteralsTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
| import static com.kaching.platform.testing.Assert.assertNotEquals;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Pair; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.guice;
public class TypeLiteralsTest {
@Test
public void get1() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<List<Foo>>() {};
TypeLiteral<?> actual = TypeLiterals.get(List.class, Foo.class);
assertEquals(expected, actual);
}
@Test
public void get2() throws Exception { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
// Path: kawala-guice/src/test/java/com/kaching/platform/guice/TypeLiteralsTest.java
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Pair;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.guice;
public class TypeLiteralsTest {
@Test
public void get1() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<List<Foo>>() {};
TypeLiteral<?> actual = TypeLiterals.get(List.class, Foo.class);
assertEquals(expected, actual);
}
@Test
public void get2() throws Exception { | TypeLiteral<?> expected = new TypeLiteral<Pair<Integer, Double>>() {}; |
wealthfront/kawala | kawala-guice/src/test/java/com/kaching/platform/guice/TypeLiteralsTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
| import static com.kaching.platform.testing.Assert.assertNotEquals;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Pair; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.guice;
public class TypeLiteralsTest {
@Test
public void get1() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<List<Foo>>() {};
TypeLiteral<?> actual = TypeLiterals.get(List.class, Foo.class);
assertEquals(expected, actual);
}
@Test
public void get2() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<Pair<Integer, Double>>() {};
TypeLiteral<?> actual = TypeLiterals.get(
Pair.class, Integer.class, Double.class);
assertEquals(expected, actual);
}
@Test
public void get3() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<List<List<Foo>>>() {};
TypeLiteral<?> inner = new TypeLiteral<List<Foo>>() {};
TypeLiteral<?> actual = TypeLiterals.get(List.class, inner);
assertEquals(expected, actual);
}
@Test
public void get4() throws Exception {
TypeLiteral<?> a = TypeLiterals.get(List.class, Integer.class);
TypeLiteral<?> b = TypeLiterals.get(List.class, Double.class);
| // Path: kawala-testing/src/main/java/com/kaching/platform/testing/Assert.java
// @SuppressWarnings("finally")
// public static void assertNotEquals(Object expected, Object actual) {
// boolean wasEqual = false;
// try {
// assertEquals(expected, actual);
// wasEqual = true;
// } catch (AssertionError e) {
// } finally {
// if (wasEqual) {
// fail();
// }
// return;
// }
// }
//
// Path: kawala-common/src/main/java/com/kaching/platform/common/Pair.java
// public class Pair<S, T> {
//
// public final S left;
// public final T right;
//
// public static <S, T> Pair<S, T> of(S left, T right) {
// return new Pair<S, T>(left, right);
// }
//
// public Pair(S left, T right) {
// this.left = left;
// this.right = right;
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(left, right);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
//
// Pair<?, ?> other = (Pair<?, ?>) obj;
// return Objects.equal(left, other.left) &&
// Objects.equal(right, other.right);
// }
//
// @Override
// public String toString() {
// return "(" + left + "," + right + ")";
// }
//
// }
// Path: kawala-guice/src/test/java/com/kaching/platform/guice/TypeLiteralsTest.java
import static com.kaching.platform.testing.Assert.assertNotEquals;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.Pair;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.guice;
public class TypeLiteralsTest {
@Test
public void get1() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<List<Foo>>() {};
TypeLiteral<?> actual = TypeLiterals.get(List.class, Foo.class);
assertEquals(expected, actual);
}
@Test
public void get2() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<Pair<Integer, Double>>() {};
TypeLiteral<?> actual = TypeLiterals.get(
Pair.class, Integer.class, Double.class);
assertEquals(expected, actual);
}
@Test
public void get3() throws Exception {
TypeLiteral<?> expected = new TypeLiteral<List<List<Foo>>>() {};
TypeLiteral<?> inner = new TypeLiteral<List<Foo>>() {};
TypeLiteral<?> actual = TypeLiterals.get(List.class, inner);
assertEquals(expected, actual);
}
@Test
public void get4() throws Exception {
TypeLiteral<?> a = TypeLiterals.get(List.class, Integer.class);
TypeLiteral<?> b = TypeLiterals.get(List.class, Double.class);
| assertNotEquals(a, b); |
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/someotherpackage/ValueWithConverterAsInnerClass.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/AbstractIdentifier.java
// public abstract class AbstractIdentifier<I extends Comparable<I>> implements
// Comparable<AbstractIdentifier<I>>, Serializable {
//
// private static final long serialVersionUID = 8147623822365809694L;
//
// private final I id;
//
// /**
// * Creates an identifier.
// * @param id the wrapped identifier
// */
// protected AbstractIdentifier(I id) {
// this.id = checkNotNull(id);
// }
//
// /**
// * Gets the wrapped identifier.
// * @return the wrapped identifier
// */
// public I getId() {
// return id;
// }
//
// @Override
// public boolean equals(Object that) {
// return
// this == that ||
// (that != null &&
// this.getClass().equals(that.getClass())) &&
// id.equals(((AbstractIdentifier<?>) that).id);
// }
//
// @Override
// public int compareTo(AbstractIdentifier<I> that) {
// if (that == null) {
// return 1;
// }
// int result = this.getId().compareTo(that.getId());
// return result != 0 ? result :
// this.getClass().toString().compareTo(
// that.getClass().toString());
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(id);
// }
//
// @Override
// public String toString() {
// return String.valueOf(id);
// }
//
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
| import com.kaching.platform.common.AbstractIdentifier;
import com.kaching.platform.converters.ConvertedBy;
import com.kaching.platform.converters.Converter;
| /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters.someotherpackage;
@ConvertedBy(ValueWithConverterAsInnerClass.Cvter.class)
public class ValueWithConverterAsInnerClass extends AbstractIdentifier<Integer> {
private static final long serialVersionUID = -290291493253896409L;
ValueWithConverterAsInnerClass(int val) {
super(val);
}
| // Path: kawala-common/src/main/java/com/kaching/platform/common/AbstractIdentifier.java
// public abstract class AbstractIdentifier<I extends Comparable<I>> implements
// Comparable<AbstractIdentifier<I>>, Serializable {
//
// private static final long serialVersionUID = 8147623822365809694L;
//
// private final I id;
//
// /**
// * Creates an identifier.
// * @param id the wrapped identifier
// */
// protected AbstractIdentifier(I id) {
// this.id = checkNotNull(id);
// }
//
// /**
// * Gets the wrapped identifier.
// * @return the wrapped identifier
// */
// public I getId() {
// return id;
// }
//
// @Override
// public boolean equals(Object that) {
// return
// this == that ||
// (that != null &&
// this.getClass().equals(that.getClass())) &&
// id.equals(((AbstractIdentifier<?>) that).id);
// }
//
// @Override
// public int compareTo(AbstractIdentifier<I> that) {
// if (that == null) {
// return 1;
// }
// int result = this.getId().compareTo(that.getId());
// return result != 0 ? result :
// this.getClass().toString().compareTo(
// that.getClass().toString());
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(id);
// }
//
// @Override
// public String toString() {
// return String.valueOf(id);
// }
//
// }
//
// Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/someotherpackage/ValueWithConverterAsInnerClass.java
import com.kaching.platform.common.AbstractIdentifier;
import com.kaching.platform.converters.ConvertedBy;
import com.kaching.platform.converters.Converter;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters.someotherpackage;
@ConvertedBy(ValueWithConverterAsInnerClass.Cvter.class)
public class ValueWithConverterAsInnerClass extends AbstractIdentifier<Integer> {
private static final long serialVersionUID = -290291493253896409L;
ValueWithConverterAsInnerClass(int val) {
super(val);
}
| static class Cvter implements Converter<ValueWithConverterAsInnerClass> {
|
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/AbstractIdentifierTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public final class EquivalenceTester {
// private EquivalenceTester() {}
//
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertTrue(format("comparison should return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldNotReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertFalse(format("comparison should not return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// }
| import com.kaching.platform.testing.EquivalenceTester;
import static com.google.common.collect.Lists.newArrayList;
import static org.junit.Assert.assertEquals;
import org.junit.Test; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common;
public class AbstractIdentifierTest {
@Test(expected = NullPointerException.class)
public void creationWithNull() {
new MyId1(null);
}
@Test
public void equivalence_simplest() { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public final class EquivalenceTester {
// private EquivalenceTester() {}
//
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertTrue(format("comparison should return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// @SuppressWarnings("unchecked")
// private static void compareShouldNotReturn0(Object e1, Object e2) {
// if (e1 instanceof Comparable<?> &&
// e2 instanceof Comparable<?>) {
// assertFalse(format("comparison should not return 0 for %s and %s", e1, e2),
// ((Comparable<Object>) e1).compareTo(e2) == 0);
// }
// }
//
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/AbstractIdentifierTest.java
import com.kaching.platform.testing.EquivalenceTester;
import static com.google.common.collect.Lists.newArrayList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common;
public class AbstractIdentifierTest {
@Test(expected = NullPointerException.class)
public void creationWithNull() {
new MyId1(null);
}
@Test
public void equivalence_simplest() { | EquivalenceTester.check( |
wealthfront/kawala | kawala-hibernate/src/test/java/com/kaching/platform/hibernate/types/AbstractStringImmutableTypeTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.sql.ResultSet;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.Sequence;
import org.junit.Before;
import org.junit.Test;
import com.kaching.platform.converters.Converter;
| /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.hibernate.types;
public class AbstractStringImmutableTypeTest {
private Mockery mockery;
private AbstractStringImmutableType<Integer> type;
@Before
public void before() {
mockery = new Mockery();
type = new AbstractStringImmutableType<Integer>() {
@Override
| // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
// Path: kawala-hibernate/src/test/java/com/kaching/platform/hibernate/types/AbstractStringImmutableTypeTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.sql.ResultSet;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.Sequence;
import org.junit.Before;
import org.junit.Test;
import com.kaching.platform.converters.Converter;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.hibernate.types;
public class AbstractStringImmutableTypeTest {
private Mockery mockery;
private AbstractStringImmutableType<Integer> type;
@Before
public void before() {
mockery = new Mockery();
type = new AbstractStringImmutableType<Integer>() {
@Override
| protected Converter<Integer> converter() {
|
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/IssuesTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Instantiators.java
// public static <T> Instantiator<T> createInstantiator(
// Class<T> klass, InstantiatorModule... modules) {
// Errors errors = new Errors();
// for (Instantiator<T> instantiator : createInstantiator(errors, klass, modules)) {
// return instantiator;
// }
// errors.throwIfHasErrors();
//
// // The following program should not be reachable since the factory should
// // produce errors if it is unable to create an instantiator.
// throw new IllegalStateException();
// }
| import static com.kaching.platform.converters.Instantiators.createInstantiator;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
| /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
public class IssuesTest {
@Test
public void issue17() {
| // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Instantiators.java
// public static <T> Instantiator<T> createInstantiator(
// Class<T> klass, InstantiatorModule... modules) {
// Errors errors = new Errors();
// for (Instantiator<T> instantiator : createInstantiator(errors, klass, modules)) {
// return instantiator;
// }
// errors.throwIfHasErrors();
//
// // The following program should not be reachable since the factory should
// // produce errors if it is unable to create an instantiator.
// throw new IllegalStateException();
// }
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/IssuesTest.java
import static com.kaching.platform.converters.Instantiators.createInstantiator;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
public class IssuesTest {
@Test
public void issue17() {
| assertNotNull(createInstantiator(Issue17.class).newInstance(""));
|
wealthfront/kawala | kawala-guice/src/main/java/com/kaching/platform/guice/TypeLiterals.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/types/ParameterizedTypeImpl.java
// public class ParameterizedTypeImpl implements ParameterizedType {
//
// private final Type rawType;
// private final Type[] actualTypeParameters;
//
// public ParameterizedTypeImpl(Type type, Type[] parameters) {
// this.rawType = type;
// this.actualTypeParameters = parameters;
// }
//
// public Type[] getActualTypeArguments() {
// return actualTypeParameters;
// }
//
// public Type getOwnerType() {
// return null;
// }
//
// public Type getRawType() {
// return rawType;
// }
//
// }
| import java.lang.reflect.Type;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.types.ParameterizedTypeImpl; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.guice;
/**
* Factory methods to construct {@link TypeLiteral}s.
*/
public final class TypeLiterals {
private TypeLiterals() {}
/**
* Creates a new {@link TypeLiteral} for {@code type} parameterized by
* {@code parameters}.
*
* <p>For example, the type {@code Map<Integer, String>} is constructed with
* {@code TypeLiterals.get(Map.class, Integer.class, String.class)}.
*/
@SuppressWarnings("unchecked")
public static <T> TypeLiteral<T> get(Class<T> type, Type... parameters) { | // Path: kawala-common/src/main/java/com/kaching/platform/common/types/ParameterizedTypeImpl.java
// public class ParameterizedTypeImpl implements ParameterizedType {
//
// private final Type rawType;
// private final Type[] actualTypeParameters;
//
// public ParameterizedTypeImpl(Type type, Type[] parameters) {
// this.rawType = type;
// this.actualTypeParameters = parameters;
// }
//
// public Type[] getActualTypeArguments() {
// return actualTypeParameters;
// }
//
// public Type getOwnerType() {
// return null;
// }
//
// public Type getRawType() {
// return rawType;
// }
//
// }
// Path: kawala-guice/src/main/java/com/kaching/platform/guice/TypeLiterals.java
import java.lang.reflect.Type;
import com.google.inject.TypeLiteral;
import com.kaching.platform.common.types.ParameterizedTypeImpl;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.guice;
/**
* Factory methods to construct {@link TypeLiteral}s.
*/
public final class TypeLiterals {
private TypeLiterals() {}
/**
* Creates a new {@link TypeLiteral} for {@code type} parameterized by
* {@code parameters}.
*
* <p>For example, the type {@code Map<Integer, String>} is constructed with
* {@code TypeLiterals.get(Map.class, Integer.class, String.class)}.
*/
@SuppressWarnings("unchecked")
public static <T> TypeLiteral<T> get(Class<T> type, Type... parameters) { | return (TypeLiteral<T>) TypeLiteral.get(new ParameterizedTypeImpl(type, parameters)); |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/types/UnificationTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
| import static java.util.Arrays.asList;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.converters.Converter; | for (int i = 0; i < 3; i++) {
assertEquals(
asList(String.class, Double.class, Integer.class).get(i),
Unification.getActualTypeArgument(
MultipleInterfaces.class, ManyTypeParams.class, i));
}
}
static class MultipleInterfaces
implements TopLevel<Type>, ManyTypeParams<String, Double, Integer> {}
@Test
public void implementsMultipleInterfacesSomeWithNoParametrization() throws Exception {
for (int i = 0; i < 3; i++) {
assertEquals(
asList(String.class, Double.class, Integer.class).get(i),
Unification.getActualTypeArgument(
MultipleInterfacesSomeWithNoParametrization.class, ManyTypeParams.class, i));
}
}
@SuppressWarnings("rawtypes")
static class MultipleInterfacesSomeWithNoParametrization
implements TopLevel, ManyTypeParams<String, Double, Integer> {}
@Test
public void listOfIntConverter() throws Exception {
assertEquals(
new TypeLiteral<List<Integer>>() {}.getType(),
Unification.getActualTypeArgument( | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/types/UnificationTest.java
import static java.util.Arrays.asList;
import static junit.framework.Assert.fail;
import static org.junit.Assert.assertEquals;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import com.google.inject.TypeLiteral;
import com.kaching.platform.converters.Converter;
for (int i = 0; i < 3; i++) {
assertEquals(
asList(String.class, Double.class, Integer.class).get(i),
Unification.getActualTypeArgument(
MultipleInterfaces.class, ManyTypeParams.class, i));
}
}
static class MultipleInterfaces
implements TopLevel<Type>, ManyTypeParams<String, Double, Integer> {}
@Test
public void implementsMultipleInterfacesSomeWithNoParametrization() throws Exception {
for (int i = 0; i < 3; i++) {
assertEquals(
asList(String.class, Double.class, Integer.class).get(i),
Unification.getActualTypeArgument(
MultipleInterfacesSomeWithNoParametrization.class, ManyTypeParams.class, i));
}
}
@SuppressWarnings("rawtypes")
static class MultipleInterfacesSomeWithNoParametrization
implements TopLevel, ManyTypeParams<String, Double, Integer> {}
@Test
public void listOfIntConverter() throws Exception {
assertEquals(
new TypeLiteral<List<Integer>>() {}.getType(),
Unification.getActualTypeArgument( | ListOfIntConverter.class, Converter.class, 0)); |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/reflect/ReflectUtilsTest.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/reflect/ReflectUtils.java
// public static Object getField(Object obj, String name) {
// try {
// Class<? extends Object> klass = obj.getClass();
// do {
// try {
// Field field = klass.getDeclaredField(name);
// field.setAccessible(true);
// return field.get(obj);
// } catch (NoSuchFieldException e) {
// klass = klass.getSuperclass();
// }
// } while (klass != null);
// throw new RuntimeException(); // true no such field exception
// } catch (SecurityException e) {
// throw new RuntimeException(e);
// } catch (IllegalArgumentException e) {
// throw new RuntimeException(e);
// } catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
| import static com.kaching.platform.common.reflect.ReflectUtils.getField;
import static org.junit.Assert.assertEquals;
import org.junit.Test; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common.reflect;
public class ReflectUtilsTest {
@Test
public void getField1() { | // Path: kawala-common/src/main/java/com/kaching/platform/common/reflect/ReflectUtils.java
// public static Object getField(Object obj, String name) {
// try {
// Class<? extends Object> klass = obj.getClass();
// do {
// try {
// Field field = klass.getDeclaredField(name);
// field.setAccessible(true);
// return field.get(obj);
// } catch (NoSuchFieldException e) {
// klass = klass.getSuperclass();
// }
// } while (klass != null);
// throw new RuntimeException(); // true no such field exception
// } catch (SecurityException e) {
// throw new RuntimeException(e);
// } catch (IllegalArgumentException e) {
// throw new RuntimeException(e);
// } catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/reflect/ReflectUtilsTest.java
import static com.kaching.platform.common.reflect.ReflectUtils.getField;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common.reflect;
public class ReflectUtilsTest {
@Test
public void getField1() { | assertEquals("child", getField(new Child(), "field1")); |
wealthfront/kawala | kawala-testing/src/test/java/com/kaching/platform/testing/CyclicDependencyTestRunnerTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/CyclicDependencyTestRunner.java
// static class Result {
// final int numClasses;
// final Map<JavaPackage, Set<JavaPackage>> sccs = Maps.newHashMap();
// Result(int numClasses) {
// this.numClasses = numClasses;
// }
//
// boolean hasCycle() {
// return !sccs.isEmpty();
// }
//
// void addCycles(List<JavaPackage> cycles) {
// Set<JavaPackage> scc = Sets.newHashSet(cycles);
// for (JavaPackage pkg : cycles) {
// sccs.put(pkg, scc);
// }
// }
//
// Set<Set<JavaPackage>> getUniqueCycles() {
// return Sets.newHashSet(sccs.values());
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder("Strongly connected components: {\n");
// for (Set<JavaPackage> scc : getUniqueCycles()) {
// boolean first = true;
// sb.append("[");
// for (JavaPackage jp : scc) {
// if (first) {
// first = false;
// } else {
// sb.append(",\n ");
// }
// sb.append(jp.getName());
// }
// sb.append("]\n");
// }
// return sb.append("}").toString();
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import com.kaching.platform.testing.CyclicDependencyTestRunner.Packages;
import com.kaching.platform.testing.CyclicDependencyTestRunner.PackagesBuilder.Result; | /**
* Copyright 2015 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
public class CyclicDependencyTestRunnerTest {
@Packages(
binDirectories = "target/test-classes",
forPackages = "com.kaching.platform.testing.testexamples.a")
private static class SinglePackage {}
@Test
public void testSinglePackage_NoCycles() throws IOException {
CyclicDependencyTestRunner runner = new CyclicDependencyTestRunner(SinglePackage.class); | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/CyclicDependencyTestRunner.java
// static class Result {
// final int numClasses;
// final Map<JavaPackage, Set<JavaPackage>> sccs = Maps.newHashMap();
// Result(int numClasses) {
// this.numClasses = numClasses;
// }
//
// boolean hasCycle() {
// return !sccs.isEmpty();
// }
//
// void addCycles(List<JavaPackage> cycles) {
// Set<JavaPackage> scc = Sets.newHashSet(cycles);
// for (JavaPackage pkg : cycles) {
// sccs.put(pkg, scc);
// }
// }
//
// Set<Set<JavaPackage>> getUniqueCycles() {
// return Sets.newHashSet(sccs.values());
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder("Strongly connected components: {\n");
// for (Set<JavaPackage> scc : getUniqueCycles()) {
// boolean first = true;
// sb.append("[");
// for (JavaPackage jp : scc) {
// if (first) {
// first = false;
// } else {
// sb.append(",\n ");
// }
// sb.append(jp.getName());
// }
// sb.append("]\n");
// }
// return sb.append("}").toString();
// }
// }
// Path: kawala-testing/src/test/java/com/kaching/platform/testing/CyclicDependencyTestRunnerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import org.junit.Test;
import com.kaching.platform.testing.CyclicDependencyTestRunner.Packages;
import com.kaching.platform.testing.CyclicDependencyTestRunner.PackagesBuilder.Result;
/**
* Copyright 2015 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
public class CyclicDependencyTestRunnerTest {
@Packages(
binDirectories = "target/test-classes",
forPackages = "com.kaching.platform.testing.testexamples.a")
private static class SinglePackage {}
@Test
public void testSinglePackage_NoCycles() throws IOException {
CyclicDependencyTestRunner runner = new CyclicDependencyTestRunner(SinglePackage.class); | Result result = runner.getTestResults(SinglePackage.class.getAnnotation(Packages.class)); |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/values/SsnTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
| import org.junit.Test;
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static org.junit.Assert.assertEquals; | new Ssn("772006789");
}
@Test(expected = IllegalArgumentException.class)
public void allZeros3() throws Exception {
new Ssn("772450000");
}
@Test(expected = IllegalArgumentException.class)
public void theBeast() throws Exception {
new Ssn("666123456");
}
@Test(expected = IllegalArgumentException.class)
public void reservedForAdvertisment1() throws Exception {
new Ssn("98765430");
}
@Test(expected = IllegalArgumentException.class)
public void reservedForAdvertisment2() throws Exception {
new Ssn("98765431");
}
@Test(expected = IllegalArgumentException.class)
public void reservedForAdvertisment3() throws Exception {
new Ssn("98765439");
}
@Test
public void equivalence() { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/values/SsnTest.java
import org.junit.Test;
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static org.junit.Assert.assertEquals;
new Ssn("772006789");
}
@Test(expected = IllegalArgumentException.class)
public void allZeros3() throws Exception {
new Ssn("772450000");
}
@Test(expected = IllegalArgumentException.class)
public void theBeast() throws Exception {
new Ssn("666123456");
}
@Test(expected = IllegalArgumentException.class)
public void reservedForAdvertisment1() throws Exception {
new Ssn("98765430");
}
@Test(expected = IllegalArgumentException.class)
public void reservedForAdvertisment2() throws Exception {
new Ssn("98765431");
}
@Test(expected = IllegalArgumentException.class)
public void reservedForAdvertisment3() throws Exception {
new Ssn("98765439");
}
@Test
public void equivalence() { | check( |
wealthfront/kawala | kawala-testing/src/main/java/com/kaching/platform/testing/CombinedAssertionFailedError.java | // Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
| import com.kaching.platform.common.Errors; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
/**
* Thrown when an assertion failed for multiple reasons.
*/
public class CombinedAssertionFailedError extends AssertionError {
private static final long serialVersionUID = 5967202290583940192L;
private final String message; | // Path: kawala-common/src/main/java/com/kaching/platform/common/Errors.java
// public class Errors {
//
// // null or [E :: L] where L is any list
// private List<String> messages;
//
// public Errors addMessage(String message, Object... values) {
// if (messages == null) {
// messages = newArrayList();
// }
// String formattedMessage = format(message, values);
// if (!messages.contains(formattedMessage)) {
// messages.add(formattedMessage);
// }
// return this;
// }
//
// public Errors addErrors(Errors errors) {
// if (errors.messages == null) {
// return this;
// }
// for (String message : errors.messages) {
// addMessage(message);
// }
// return this;
// }
//
// public List<String> getMessages() {
// if (messages == null) {
// return emptyList();
// }
// return ImmutableList.copyOf(messages);
// }
//
// public void throwIfHasErrors() {
// if (messages != null) {
// throw new RuntimeException(toString());
// }
// }
//
// public int size() {
// return messages == null ? 0 : messages.size();
// }
//
// public boolean hasErrors() {
// return 0 < size();
// }
//
// @Override
// public int hashCode() {
// return messages == null ? EMPTY_LIST.hashCode() : messages.hashCode();
// }
//
// @Override
// public boolean equals(Object that) {
// if (this == that) {
// return true;
// }
// if (!(that instanceof Errors)) {
// return false;
// }
// return this.messages == null ?
// ((Errors) that).messages == null :
// this.messages.equals(((Errors) that).messages);
// }
//
// @Override
// public String toString() {
// if (messages == null) {
// return "no errors";
// }
// StringBuilder buf = new StringBuilder();
// int num = 1;
// String separator = "";
// for (String message : messages) {
// buf.append(separator);
// buf.append(num);
// buf.append(") ");
// buf.append(message);
// num++;
// separator = "\n\n";
// }
// return buf.toString();
// }
//
// }
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/CombinedAssertionFailedError.java
import com.kaching.platform.common.Errors;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
/**
* Thrown when an assertion failed for multiple reasons.
*/
public class CombinedAssertionFailedError extends AssertionError {
private static final long serialVersionUID = 5967202290583940192L;
private final String message; | private final Errors errors; |
wealthfront/kawala | kawala-testing/src/main/java/com/kaching/platform/testing/CyclicDependencyTestRunner.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/CyclicDependencyTestRunner.java
// static class Result {
// final int numClasses;
// final Map<JavaPackage, Set<JavaPackage>> sccs = Maps.newHashMap();
// Result(int numClasses) {
// this.numClasses = numClasses;
// }
//
// boolean hasCycle() {
// return !sccs.isEmpty();
// }
//
// void addCycles(List<JavaPackage> cycles) {
// Set<JavaPackage> scc = Sets.newHashSet(cycles);
// for (JavaPackage pkg : cycles) {
// sccs.put(pkg, scc);
// }
// }
//
// Set<Set<JavaPackage>> getUniqueCycles() {
// return Sets.newHashSet(sccs.values());
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder("Strongly connected components: {\n");
// for (Set<JavaPackage> scc : getUniqueCycles()) {
// boolean first = true;
// sb.append("[");
// for (JavaPackage jp : scc) {
// if (first) {
// first = false;
// } else {
// sb.append(",\n ");
// }
// sb.append(jp.getName());
// }
// sb.append("]\n");
// }
// return sb.append("}").toString();
// }
// }
| import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format;
import static java.lang.System.getProperty;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import jdepend.framework.PackageFilter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.kaching.platform.testing.CyclicDependencyTestRunner.PackagesBuilder.Result; | /**
* Copyright 2015 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
/**
* @see <a href="http://clarkware.com/software/JDepend.html#junit">JDepend and JUnit</a>
*/
public class CyclicDependencyTestRunner extends AbstractDeclarativeTestRunner<CyclicDependencyTestRunner.Packages> {
@Target(TYPE)
@Retention(RUNTIME)
public @interface Packages {
public int minClasses() default 10;
public String[] forPackages();
public String[] binDirectories() default "target/test-classes";
public String binDirectoryProperty() default "kawala.bin_directories";
}
public CyclicDependencyTestRunner(Class<?> testClass) {
super(testClass, Packages.class);
}
@Override
@SuppressWarnings("unchecked")
protected void runTest(final Packages dependencies) throws IOException { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/CyclicDependencyTestRunner.java
// static class Result {
// final int numClasses;
// final Map<JavaPackage, Set<JavaPackage>> sccs = Maps.newHashMap();
// Result(int numClasses) {
// this.numClasses = numClasses;
// }
//
// boolean hasCycle() {
// return !sccs.isEmpty();
// }
//
// void addCycles(List<JavaPackage> cycles) {
// Set<JavaPackage> scc = Sets.newHashSet(cycles);
// for (JavaPackage pkg : cycles) {
// sccs.put(pkg, scc);
// }
// }
//
// Set<Set<JavaPackage>> getUniqueCycles() {
// return Sets.newHashSet(sccs.values());
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder("Strongly connected components: {\n");
// for (Set<JavaPackage> scc : getUniqueCycles()) {
// boolean first = true;
// sb.append("[");
// for (JavaPackage jp : scc) {
// if (first) {
// first = false;
// } else {
// sb.append(",\n ");
// }
// sb.append(jp.getName());
// }
// sb.append("]\n");
// }
// return sb.append("}").toString();
// }
// }
// Path: kawala-testing/src/main/java/com/kaching/platform/testing/CyclicDependencyTestRunner.java
import static com.google.common.collect.Sets.newHashSet;
import static java.lang.String.format;
import static java.lang.System.getProperty;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jdepend.framework.JDepend;
import jdepend.framework.JavaPackage;
import jdepend.framework.PackageFilter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.kaching.platform.testing.CyclicDependencyTestRunner.PackagesBuilder.Result;
/**
* Copyright 2015 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.testing;
/**
* @see <a href="http://clarkware.com/software/JDepend.html#junit">JDepend and JUnit</a>
*/
public class CyclicDependencyTestRunner extends AbstractDeclarativeTestRunner<CyclicDependencyTestRunner.Packages> {
@Target(TYPE)
@Retention(RUNTIME)
public @interface Packages {
public int minClasses() default 10;
public String[] forPackages();
public String[] binDirectories() default "target/test-classes";
public String binDirectoryProperty() default "kawala.bin_directories";
}
public CyclicDependencyTestRunner(Class<?> testClass) {
super(testClass, Packages.class);
}
@Override
@SuppressWarnings("unchecked")
protected void runTest(final Packages dependencies) throws IOException { | Result results = getTestResults(dependencies); |
wealthfront/kawala | kawala-hibernate/src/main/java/com/kaching/platform/hibernate/types/AbstractStringImmutableType.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
| import static java.sql.Types.VARCHAR;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import com.kaching.platform.converters.Converter; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.hibernate.types;
/**
* An abstract hibernate type providing marshalling an unmarshalling to a
* string representation.
*/
public abstract class AbstractStringImmutableType<T>
extends AbstractImmutableType implements UserType {
private static final int[] SQL_TYPES = { VARCHAR };
public final T nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String representation = rs.getString(names[0]);
// deferred call to wasNull
// http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSet.html#wasNull()
if (rs.wasNull() || representation == null) {
return null;
} else {
return converter().fromString(representation);
}
}
@SuppressWarnings("unchecked")
@Override
public final void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
super.nullSafeSet(st, value, index);
if (value == null) {
st.setNull(index, VARCHAR);
} else {
st.setString(index, converter().toString((T) value));
}
}
/**
* Gets the converter to use to transform values into strings and vice-versa.
* @return the converter
*/ | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/Converter.java
// public interface Converter<T> extends ToString<T>, FromString<T> {
// }
// Path: kawala-hibernate/src/main/java/com/kaching/platform/hibernate/types/AbstractStringImmutableType.java
import static java.sql.Types.VARCHAR;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import com.kaching.platform.converters.Converter;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.hibernate.types;
/**
* An abstract hibernate type providing marshalling an unmarshalling to a
* string representation.
*/
public abstract class AbstractStringImmutableType<T>
extends AbstractImmutableType implements UserType {
private static final int[] SQL_TYPES = { VARCHAR };
public final T nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String representation = rs.getString(names[0]);
// deferred call to wasNull
// http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSet.html#wasNull()
if (rs.wasNull() || representation == null) {
return null;
} else {
return converter().fromString(representation);
}
}
@SuppressWarnings("unchecked")
@Override
public final void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
super.nullSafeSet(st, value, index);
if (value == null) {
st.setNull(index, VARCHAR);
} else {
st.setString(index, converter().toString((T) value));
}
}
/**
* Gets the converter to use to transform values into strings and vice-versa.
* @return the converter
*/ | protected abstract Converter<T> converter(); |
wealthfront/kawala | kawala-common-tests/src/test/java/com/kaching/platform/common/PairTest.java | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
| import org.junit.Test;
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static org.junit.Assert.assertEquals; | /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common;
public class PairTest {
@Test
@SuppressWarnings("unchecked")
public void equivalence() { | // Path: kawala-testing/src/main/java/com/kaching/platform/testing/EquivalenceTester.java
// public static void check(Collection<?>... equivalenceClasses) {
// List<List<Object>> ec =
// newArrayListWithExpectedSize(equivalenceClasses.length);
//
// // nothing can be equal to null
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// for (Object element : congruenceClass) {
// try {
// assertFalse(
// format("%s can not be equal to null", element),
// element.equals(null));
// } catch (NullPointerException e) {
// throw new AssertionError(
// format("NullPointerException when comparing %s to null", element));
// }
// }
// }
//
// // reflexivity
// for (Collection<? extends Object> congruenceClass : equivalenceClasses) {
// List<Object> c = newArrayList();
// ec.add(c);
// for (Object element : congruenceClass) {
// assertTrue(format("reflexivity of %s", element),
// element.equals(element));
// compareShouldReturn0(element, element);
// c.add(element);
// }
// }
//
// // equality within congruence classes
// for (List<Object> c : ec) {
// for (int i = 0; i < c.size(); i++) {
// Object e1 = c.get(i);
// for (int j = i + 1; j < c.size(); j++) {
// Object e2 = c.get(j);
// assertTrue(format("%s=%s", e1, e2), e1.equals(e2));
// assertTrue(format("%s=%s", e2, e1), e2.equals(e1));
// compareShouldReturn0(e1, e2);
// compareShouldReturn0(e2, e1);
// assertEquals(format("hashCode %s vs. %s", e1, e2), e1.hashCode(), e2.hashCode());
// }
// }
// }
//
// // inequality across congruence classes
// for (int i = 0; i < ec.size(); i++) {
// List<Object> c1 = ec.get(i);
// for (int j = i + 1; j < ec.size(); j++) {
// List<Object> c2 = ec.get(j);
// for (Object e1 : c1) {
// for (Object e2 : c2) {
// assertFalse(format("%s!=%s", e1, e2), e1.equals(e2));
// assertFalse(format("%s!=%s", e2, e1), e2.equals(e1));
// compareShouldNotReturn0(e1, e2);
// compareShouldNotReturn0(e2, e1);
// }
// }
// }
// }
// }
// Path: kawala-common-tests/src/test/java/com/kaching/platform/common/PairTest.java
import org.junit.Test;
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.testing.EquivalenceTester.check;
import static org.junit.Assert.assertEquals;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.common;
public class PairTest {
@Test
@SuppressWarnings("unchecked")
public void equivalence() { | check( |
wealthfront/kawala | kawala-converters/src/test/java/com/kaching/platform/converters/CollectionOfElementsConverterTest.java | // Path: kawala-converters/src/main/java/com/kaching/platform/converters/NativeConverters.java
// static final Converter<Boolean> C_BOOLEAN = new ConverterWithToString<Boolean>() {
// @Override
// public Boolean fromString(String representation) {
// String trimmed = representation.trim();
// if ("true".equalsIgnoreCase(trimmed)) {
// return true;
// }
// if ("false".equalsIgnoreCase(trimmed)) {
// return false;
// }
// throw new IllegalArgumentException(String.format("representation is not a valid boolean : %s", representation));
// }
// };
| import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.converters.NativeConverters.C_BOOLEAN;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
| /**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
public class CollectionOfElementsConverterTest {
@Test
public void emptyList() {
check(Collections.emptyList(), "");
}
@Test
public void oneElementList() {
check(newArrayList((Object) true), "true");
}
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void createsRightKindOfCollection() {
assertEquals(
HashSet.class,
| // Path: kawala-converters/src/main/java/com/kaching/platform/converters/NativeConverters.java
// static final Converter<Boolean> C_BOOLEAN = new ConverterWithToString<Boolean>() {
// @Override
// public Boolean fromString(String representation) {
// String trimmed = representation.trim();
// if ("true".equalsIgnoreCase(trimmed)) {
// return true;
// }
// if ("false".equalsIgnoreCase(trimmed)) {
// return false;
// }
// throw new IllegalArgumentException(String.format("representation is not a valid boolean : %s", representation));
// }
// };
// Path: kawala-converters/src/test/java/com/kaching/platform/converters/CollectionOfElementsConverterTest.java
import static com.google.common.collect.Lists.newArrayList;
import static com.kaching.platform.converters.NativeConverters.C_BOOLEAN;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
/**
* Copyright 2010 Wealthfront Inc. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.kaching.platform.converters;
public class CollectionOfElementsConverterTest {
@Test
public void emptyList() {
check(Collections.emptyList(), "");
}
@Test
public void oneElementList() {
check(newArrayList((Object) true), "true");
}
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void createsRightKindOfCollection() {
assertEquals(
HashSet.class,
| new CollectionOfElementsConverter(Set.class, C_BOOLEAN).fromString("").getClass());
|
TheCookieLab/poloniex-api-java | src/main/java/com/cf/client/poloniex/PoloniexPublicAPIClient.java | // Path: src/main/java/com/cf/PriceDataAPIClient.java
// public interface PriceDataAPIClient
// {
// public String returnTicker();
//
// public String getUSDBTCChartData(Long periodInSeconds, Long startEpochInSeconds);
//
// public String getUSDETHChartData(Long periodInSeconds, Long startEpochInSeconds);
//
// public String getChartData(String currencyPair, Long periodInSeconds, Long startEpochSeconds);
//
// public String getChartData(String currencyPair, Long periodInSeconds, Long startEpochSeconds, Long endEpochSeconds);
// }
//
// Path: src/main/java/com/cf/client/HTTPClient.java
// public class HTTPClient
// {
//
// private final HttpHost proxy;
//
// public HTTPClient()
// {
// this.proxy = null;
// }
//
// public HTTPClient(HttpHost proxy)
// {
// this.proxy = proxy;
// }
//
//
// public String postHttp(String url, List<NameValuePair> params, List<NameValuePair> headers) throws IOException
// {
// HttpPost post = new HttpPost(url);
// post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
// post.getEntity().toString();
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// post.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(post);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
//
// public String getHttp(String url, List<NameValuePair> headers) throws IOException
// {
// HttpRequestBase request = new HttpGet(url);
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// request.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(request);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
// }
| import com.cf.PriceDataAPIClient;
import com.cf.client.HTTPClient;
import org.apache.http.HttpHost;
import org.apache.logging.log4j.LogManager;
import java.io.IOException; | package com.cf.client.poloniex;
/**
*
* @author David
*/
public class PoloniexPublicAPIClient implements PriceDataAPIClient
{
private static final String PUBLIC_URL = "https://poloniex.com/public?"; | // Path: src/main/java/com/cf/PriceDataAPIClient.java
// public interface PriceDataAPIClient
// {
// public String returnTicker();
//
// public String getUSDBTCChartData(Long periodInSeconds, Long startEpochInSeconds);
//
// public String getUSDETHChartData(Long periodInSeconds, Long startEpochInSeconds);
//
// public String getChartData(String currencyPair, Long periodInSeconds, Long startEpochSeconds);
//
// public String getChartData(String currencyPair, Long periodInSeconds, Long startEpochSeconds, Long endEpochSeconds);
// }
//
// Path: src/main/java/com/cf/client/HTTPClient.java
// public class HTTPClient
// {
//
// private final HttpHost proxy;
//
// public HTTPClient()
// {
// this.proxy = null;
// }
//
// public HTTPClient(HttpHost proxy)
// {
// this.proxy = proxy;
// }
//
//
// public String postHttp(String url, List<NameValuePair> params, List<NameValuePair> headers) throws IOException
// {
// HttpPost post = new HttpPost(url);
// post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
// post.getEntity().toString();
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// post.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(post);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
//
// public String getHttp(String url, List<NameValuePair> headers) throws IOException
// {
// HttpRequestBase request = new HttpGet(url);
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// request.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(request);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
// }
// Path: src/main/java/com/cf/client/poloniex/PoloniexPublicAPIClient.java
import com.cf.PriceDataAPIClient;
import com.cf.client.HTTPClient;
import org.apache.http.HttpHost;
import org.apache.logging.log4j.LogManager;
import java.io.IOException;
package com.cf.client.poloniex;
/**
*
* @author David
*/
public class PoloniexPublicAPIClient implements PriceDataAPIClient
{
private static final String PUBLIC_URL = "https://poloniex.com/public?"; | private final HTTPClient client; |
TheCookieLab/poloniex-api-java | src/main/java/com/cf/client/poloniex/PoloniexWSSClientRouter.java | // Path: src/main/java/com/cf/client/wss/handler/LoggingMessageHandler.java
// public class LoggingMessageHandler implements IMessageHandler {
//
// private final static Logger LOG = LogManager.getLogger();
//
// @Override
// public void handle(String message) {
// LOG.info(message);
// }
//
// }
//
// Path: src/main/java/com/cf/client/wss/handler/IMessageHandler.java
// public interface IMessageHandler {
// public void handle(String message);
// }
| import com.cf.client.wss.handler.LoggingMessageHandler;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.CharsetUtil;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import com.cf.client.wss.handler.IMessageHandler; | package com.cf.client.poloniex;
public class PoloniexWSSClientRouter extends SimpleChannelInboundHandler<Object> {
private final static Logger LOG = LogManager.getLogger();
private static final int MAX_FRAME_LENGTH = 1262144;
private final WebSocketClientHandshaker handshaker;
private ChannelPromise handshakeFuture;
private boolean running;
| // Path: src/main/java/com/cf/client/wss/handler/LoggingMessageHandler.java
// public class LoggingMessageHandler implements IMessageHandler {
//
// private final static Logger LOG = LogManager.getLogger();
//
// @Override
// public void handle(String message) {
// LOG.info(message);
// }
//
// }
//
// Path: src/main/java/com/cf/client/wss/handler/IMessageHandler.java
// public interface IMessageHandler {
// public void handle(String message);
// }
// Path: src/main/java/com/cf/client/poloniex/PoloniexWSSClientRouter.java
import com.cf.client.wss.handler.LoggingMessageHandler;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.CharsetUtil;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import com.cf.client.wss.handler.IMessageHandler;
package com.cf.client.poloniex;
public class PoloniexWSSClientRouter extends SimpleChannelInboundHandler<Object> {
private final static Logger LOG = LogManager.getLogger();
private static final int MAX_FRAME_LENGTH = 1262144;
private final WebSocketClientHandshaker handshaker;
private ChannelPromise handshakeFuture;
private boolean running;
| private Map<Double, IMessageHandler> subscriptions; |
TheCookieLab/poloniex-api-java | src/main/java/com/cf/client/poloniex/PoloniexWSSClientRouter.java | // Path: src/main/java/com/cf/client/wss/handler/LoggingMessageHandler.java
// public class LoggingMessageHandler implements IMessageHandler {
//
// private final static Logger LOG = LogManager.getLogger();
//
// @Override
// public void handle(String message) {
// LOG.info(message);
// }
//
// }
//
// Path: src/main/java/com/cf/client/wss/handler/IMessageHandler.java
// public interface IMessageHandler {
// public void handle(String message);
// }
| import com.cf.client.wss.handler.LoggingMessageHandler;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.CharsetUtil;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import com.cf.client.wss.handler.IMessageHandler; | package com.cf.client.poloniex;
public class PoloniexWSSClientRouter extends SimpleChannelInboundHandler<Object> {
private final static Logger LOG = LogManager.getLogger();
private static final int MAX_FRAME_LENGTH = 1262144;
private final WebSocketClientHandshaker handshaker;
private ChannelPromise handshakeFuture;
private boolean running;
private Map<Double, IMessageHandler> subscriptions;
private final IMessageHandler defaultSubscriptionMessageHandler;
private final Gson gson;
public PoloniexWSSClientRouter(URI url, Map<Double, IMessageHandler> subscriptions) throws URISyntaxException {
this(WebSocketClientHandshakerFactory
.newHandshaker(url, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_LENGTH), subscriptions);
}
public PoloniexWSSClientRouter(WebSocketClientHandshaker handshaker, Map<Double, IMessageHandler> subscriptions) {
this.handshaker = handshaker;
this.subscriptions = subscriptions; | // Path: src/main/java/com/cf/client/wss/handler/LoggingMessageHandler.java
// public class LoggingMessageHandler implements IMessageHandler {
//
// private final static Logger LOG = LogManager.getLogger();
//
// @Override
// public void handle(String message) {
// LOG.info(message);
// }
//
// }
//
// Path: src/main/java/com/cf/client/wss/handler/IMessageHandler.java
// public interface IMessageHandler {
// public void handle(String message);
// }
// Path: src/main/java/com/cf/client/poloniex/PoloniexWSSClientRouter.java
import com.cf.client.wss.handler.LoggingMessageHandler;
import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.util.CharsetUtil;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import com.cf.client.wss.handler.IMessageHandler;
package com.cf.client.poloniex;
public class PoloniexWSSClientRouter extends SimpleChannelInboundHandler<Object> {
private final static Logger LOG = LogManager.getLogger();
private static final int MAX_FRAME_LENGTH = 1262144;
private final WebSocketClientHandshaker handshaker;
private ChannelPromise handshakeFuture;
private boolean running;
private Map<Double, IMessageHandler> subscriptions;
private final IMessageHandler defaultSubscriptionMessageHandler;
private final Gson gson;
public PoloniexWSSClientRouter(URI url, Map<Double, IMessageHandler> subscriptions) throws URISyntaxException {
this(WebSocketClientHandshakerFactory
.newHandshaker(url, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), MAX_FRAME_LENGTH), subscriptions);
}
public PoloniexWSSClientRouter(WebSocketClientHandshaker handshaker, Map<Double, IMessageHandler> subscriptions) {
this.handshaker = handshaker;
this.subscriptions = subscriptions; | this.defaultSubscriptionMessageHandler = new LoggingMessageHandler(); |
TheCookieLab/poloniex-api-java | src/main/java/com/cf/data/map/poloniex/PoloniexDataMapper.java | // Path: src/main/java/com/cf/data/model/poloniex/deserialize/PoloniexChartDataDeserializer.java
// public class PoloniexChartDataDeserializer implements JsonDeserializer<PoloniexChartData> {
//
// @Override
// public PoloniexChartData deserialize(JsonElement json, Type type, JsonDeserializationContext jdc) throws JsonParseException {
// JsonObject jo = (JsonObject) json;
// ZonedDateTime date = ZonedDateTime.ofInstant(Instant.ofEpochMilli(jo.get("date").getAsLong() * 1000), ZoneOffset.UTC);
// BigDecimal high = BigDecimal.valueOf(jo.get("high").getAsDouble());
// BigDecimal low = BigDecimal.valueOf(jo.get("low").getAsDouble());
// BigDecimal open = BigDecimal.valueOf(jo.get("open").getAsDouble());
// BigDecimal close = BigDecimal.valueOf(jo.get("close").getAsDouble());
// BigDecimal volume = BigDecimal.valueOf(jo.get("volume").getAsDouble());
// BigDecimal quoteVolume = BigDecimal.valueOf(jo.get("quoteVolume").getAsDouble());
// BigDecimal weightedAverage = BigDecimal.valueOf(jo.get("weightedAverage").getAsDouble());
//
// return new PoloniexChartData(date, high, low, open, close, volume, quoteVolume, weightedAverage);
// }
//
// }
| import com.cf.data.model.poloniex.*;
import com.cf.data.model.poloniex.deserialize.PoloniexChartDataDeserializer;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors; | package com.cf.data.map.poloniex;
/**
*
* @author David
*/
public class PoloniexDataMapper {
private final Gson gson;
private final static Logger LOGGER = LogManager.getLogger();
private final static DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.n]").withZone(ZoneOffset.UTC);
private final static String EMPTY_RESULTS = "[]";
private final static String INVALID_CHART_DATA_DATE_RANGE_RESULT = "[{\"date\":0,\"high\":0,\"low\":0,\"open\":0,\"close\":0,\"volume\":0,\"quoteVolume\":0,\"weightedAverage\":0}]";
private final static String INVALID_CHART_DATA_CURRENCY_PAIR_RESULT = "{\"error\":\"Invalid currency pair.\"}";
public PoloniexDataMapper() {
gson = new GsonBuilder()
.registerTypeAdapter(ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
@Override
public ZonedDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString(), DTF);
} | // Path: src/main/java/com/cf/data/model/poloniex/deserialize/PoloniexChartDataDeserializer.java
// public class PoloniexChartDataDeserializer implements JsonDeserializer<PoloniexChartData> {
//
// @Override
// public PoloniexChartData deserialize(JsonElement json, Type type, JsonDeserializationContext jdc) throws JsonParseException {
// JsonObject jo = (JsonObject) json;
// ZonedDateTime date = ZonedDateTime.ofInstant(Instant.ofEpochMilli(jo.get("date").getAsLong() * 1000), ZoneOffset.UTC);
// BigDecimal high = BigDecimal.valueOf(jo.get("high").getAsDouble());
// BigDecimal low = BigDecimal.valueOf(jo.get("low").getAsDouble());
// BigDecimal open = BigDecimal.valueOf(jo.get("open").getAsDouble());
// BigDecimal close = BigDecimal.valueOf(jo.get("close").getAsDouble());
// BigDecimal volume = BigDecimal.valueOf(jo.get("volume").getAsDouble());
// BigDecimal quoteVolume = BigDecimal.valueOf(jo.get("quoteVolume").getAsDouble());
// BigDecimal weightedAverage = BigDecimal.valueOf(jo.get("weightedAverage").getAsDouble());
//
// return new PoloniexChartData(date, high, low, open, close, volume, quoteVolume, weightedAverage);
// }
//
// }
// Path: src/main/java/com/cf/data/map/poloniex/PoloniexDataMapper.java
import com.cf.data.model.poloniex.*;
import com.cf.data.model.poloniex.deserialize.PoloniexChartDataDeserializer;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;
package com.cf.data.map.poloniex;
/**
*
* @author David
*/
public class PoloniexDataMapper {
private final Gson gson;
private final static Logger LOGGER = LogManager.getLogger();
private final static DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.n]").withZone(ZoneOffset.UTC);
private final static String EMPTY_RESULTS = "[]";
private final static String INVALID_CHART_DATA_DATE_RANGE_RESULT = "[{\"date\":0,\"high\":0,\"low\":0,\"open\":0,\"close\":0,\"volume\":0,\"quoteVolume\":0,\"weightedAverage\":0}]";
private final static String INVALID_CHART_DATA_CURRENCY_PAIR_RESULT = "{\"error\":\"Invalid currency pair.\"}";
public PoloniexDataMapper() {
gson = new GsonBuilder()
.registerTypeAdapter(ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
@Override
public ZonedDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString(), DTF);
} | }).registerTypeAdapter(PoloniexChartData.class, new PoloniexChartDataDeserializer()) |
TheCookieLab/poloniex-api-java | src/main/java/com/cf/client/wss/handler/TickerMessageHandler.java | // Path: src/main/java/com/cf/client/poloniex/wss/model/PoloniexWSSTicker.java
// public class PoloniexWSSTicker {
//
// public final Double currencyPair;
// public final BigDecimal lastPrice;
// public final BigDecimal lowestAsk;
// public final BigDecimal highestBid;
// public final BigDecimal percentChange;
// public final BigDecimal baseVolume;
// public final BigDecimal quoteVolume;
// public final Boolean isFrozen;
// public final BigDecimal twentyFourHourHigh;
// public final BigDecimal twentyFourHourLow;
//
// public PoloniexWSSTicker(Double currencyPair, BigDecimal lastPrice, BigDecimal lowestAsk, BigDecimal highestBid, BigDecimal percentChange, BigDecimal baseVolume, BigDecimal quoteVolume, Boolean isFrozen, BigDecimal twentyFourHourHigh, BigDecimal twentyFourHourLow) {
// this.currencyPair = currencyPair;
// this.lastPrice = lastPrice;
// this.lowestAsk = lowestAsk;
// this.highestBid = highestBid;
// this.percentChange = percentChange;
// this.baseVolume = baseVolume;
// this.quoteVolume = quoteVolume;
// this.isFrozen = isFrozen;
// this.twentyFourHourHigh = twentyFourHourHigh;
// this.twentyFourHourLow = twentyFourHourLow;
// }
//
// @Override
// public String toString() {
// return new Gson().toJson(this);
// }
//
// public static class PoloniexWSSTickerBuilder {
//
// private Double currencyPair;
// private BigDecimal lastPrice;
// private BigDecimal lowestAsk;
// private BigDecimal highestBid;
// private BigDecimal percentChange;
// private BigDecimal baseVolume;
// private BigDecimal quoteVolume;
// private Boolean isFrozen;
// private BigDecimal twentyFourHourHigh;
// private BigDecimal twentyFourHourLow;
//
// public PoloniexWSSTickerBuilder() {
// }
//
// public PoloniexWSSTickerBuilder setCurrencyPair(Double currencyPair) {
// this.currencyPair = currencyPair;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setLastPrice(BigDecimal lastPrice) {
// this.lastPrice = lastPrice;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setLowestAsk(BigDecimal lowestAsk) {
// this.lowestAsk = lowestAsk;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setHighestBid(BigDecimal highestBid) {
// this.highestBid = highestBid;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setPercentChange(BigDecimal percentChange) {
// this.percentChange = percentChange;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setBaseVolume(BigDecimal baseVolume) {
// this.baseVolume = baseVolume;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setQuoteVolume(BigDecimal quoteVolume) {
// this.quoteVolume = quoteVolume;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setIsFrozen(Boolean isFrozen) {
// this.isFrozen = isFrozen;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setTwentyFourHourHigh(BigDecimal twentyFourHourHigh) {
// this.twentyFourHourHigh = twentyFourHourHigh;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setTwentyFourHourLow(BigDecimal twentyFourHourLow) {
// this.twentyFourHourLow = twentyFourHourLow;
// return this;
// }
//
// public PoloniexWSSTicker buildPoloniexTicker() {
// return new PoloniexWSSTicker(currencyPair, lastPrice, lowestAsk, highestBid, percentChange, baseVolume, quoteVolume, isFrozen, twentyFourHourHigh, twentyFourHourLow);
// }
// }
// }
| import com.cf.client.poloniex.wss.model.PoloniexWSSTicker;
import com.google.gson.Gson;
import java.math.BigDecimal;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; | package com.cf.client.wss.handler;
/**
*
* @author David
*/
public class TickerMessageHandler implements IMessageHandler {
private final static Logger LOG = LogManager.getLogger();
private final static Gson GSON = new Gson();
@Override
public void handle(String message) { | // Path: src/main/java/com/cf/client/poloniex/wss/model/PoloniexWSSTicker.java
// public class PoloniexWSSTicker {
//
// public final Double currencyPair;
// public final BigDecimal lastPrice;
// public final BigDecimal lowestAsk;
// public final BigDecimal highestBid;
// public final BigDecimal percentChange;
// public final BigDecimal baseVolume;
// public final BigDecimal quoteVolume;
// public final Boolean isFrozen;
// public final BigDecimal twentyFourHourHigh;
// public final BigDecimal twentyFourHourLow;
//
// public PoloniexWSSTicker(Double currencyPair, BigDecimal lastPrice, BigDecimal lowestAsk, BigDecimal highestBid, BigDecimal percentChange, BigDecimal baseVolume, BigDecimal quoteVolume, Boolean isFrozen, BigDecimal twentyFourHourHigh, BigDecimal twentyFourHourLow) {
// this.currencyPair = currencyPair;
// this.lastPrice = lastPrice;
// this.lowestAsk = lowestAsk;
// this.highestBid = highestBid;
// this.percentChange = percentChange;
// this.baseVolume = baseVolume;
// this.quoteVolume = quoteVolume;
// this.isFrozen = isFrozen;
// this.twentyFourHourHigh = twentyFourHourHigh;
// this.twentyFourHourLow = twentyFourHourLow;
// }
//
// @Override
// public String toString() {
// return new Gson().toJson(this);
// }
//
// public static class PoloniexWSSTickerBuilder {
//
// private Double currencyPair;
// private BigDecimal lastPrice;
// private BigDecimal lowestAsk;
// private BigDecimal highestBid;
// private BigDecimal percentChange;
// private BigDecimal baseVolume;
// private BigDecimal quoteVolume;
// private Boolean isFrozen;
// private BigDecimal twentyFourHourHigh;
// private BigDecimal twentyFourHourLow;
//
// public PoloniexWSSTickerBuilder() {
// }
//
// public PoloniexWSSTickerBuilder setCurrencyPair(Double currencyPair) {
// this.currencyPair = currencyPair;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setLastPrice(BigDecimal lastPrice) {
// this.lastPrice = lastPrice;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setLowestAsk(BigDecimal lowestAsk) {
// this.lowestAsk = lowestAsk;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setHighestBid(BigDecimal highestBid) {
// this.highestBid = highestBid;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setPercentChange(BigDecimal percentChange) {
// this.percentChange = percentChange;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setBaseVolume(BigDecimal baseVolume) {
// this.baseVolume = baseVolume;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setQuoteVolume(BigDecimal quoteVolume) {
// this.quoteVolume = quoteVolume;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setIsFrozen(Boolean isFrozen) {
// this.isFrozen = isFrozen;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setTwentyFourHourHigh(BigDecimal twentyFourHourHigh) {
// this.twentyFourHourHigh = twentyFourHourHigh;
// return this;
// }
//
// public PoloniexWSSTickerBuilder setTwentyFourHourLow(BigDecimal twentyFourHourLow) {
// this.twentyFourHourLow = twentyFourHourLow;
// return this;
// }
//
// public PoloniexWSSTicker buildPoloniexTicker() {
// return new PoloniexWSSTicker(currencyPair, lastPrice, lowestAsk, highestBid, percentChange, baseVolume, quoteVolume, isFrozen, twentyFourHourHigh, twentyFourHourLow);
// }
// }
// }
// Path: src/main/java/com/cf/client/wss/handler/TickerMessageHandler.java
import com.cf.client.poloniex.wss.model.PoloniexWSSTicker;
import com.google.gson.Gson;
import java.math.BigDecimal;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
package com.cf.client.wss.handler;
/**
*
* @author David
*/
public class TickerMessageHandler implements IMessageHandler {
private final static Logger LOG = LogManager.getLogger();
private final static Gson GSON = new Gson();
@Override
public void handle(String message) { | PoloniexWSSTicker ticker = this.mapMessageToPoloniexTicker(message); |
TheCookieLab/poloniex-api-java | src/main/java/com/cf/client/poloniex/PoloniexTradingAPIClient.java | // Path: src/main/java/com/cf/TradingAPIClient.java
// public interface TradingAPIClient
// {
// public String returnBalances();
//
// public String returnCompleteBalances();
//
// public String returnFeeInfo();
//
// public String returnOpenOrders(String currencyPair);
//
// public String returnTradeHistory(String currencyPair);
//
// public String returnOrderTrades(String orderNumber);
//
// public String returnOrderStatus(String orderNumber);
//
// public String cancelOrder(String orderNumber);
//
// public String moveOrder(String orderNumber, BigDecimal rate);
//
// public String sell(String currencyPair, BigDecimal buyPrice, BigDecimal amount, boolean fillOrKill, boolean immediateOrCancel, boolean postOnly);
//
// public String buy(String currencyPair, BigDecimal buyPrice, BigDecimal amount, boolean fillOrKill, boolean immediateOrCancel, boolean postOnly);
//
// public String withdraw(String currency, BigDecimal amount, String address, String paymentId);
//
// // Lending APIs
// public String returnActiveLoans();
//
// public String returnLendingHistory(int hours, int limit);
//
// public String createLoanOffer(String currency, BigDecimal amount, BigDecimal lendingRate, int duration, boolean autoRenew);
//
// public String cancelLoanOffer(String orderNumber);
//
// public String returnOpenLoanOffers();
//
// public String toggleAutoRenew(String orderNumber);
//
// }
//
// Path: src/main/java/com/cf/client/HTTPClient.java
// public class HTTPClient
// {
//
// private final HttpHost proxy;
//
// public HTTPClient()
// {
// this.proxy = null;
// }
//
// public HTTPClient(HttpHost proxy)
// {
// this.proxy = proxy;
// }
//
//
// public String postHttp(String url, List<NameValuePair> params, List<NameValuePair> headers) throws IOException
// {
// HttpPost post = new HttpPost(url);
// post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
// post.getEntity().toString();
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// post.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(post);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
//
// public String getHttp(String url, List<NameValuePair> headers) throws IOException
// {
// HttpRequestBase request = new HttpGet(url);
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// request.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(request);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
// }
| import com.cf.TradingAPIClient;
import com.cf.client.HTTPClient;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List; | package com.cf.client.poloniex;
/**
*
* @author David
* @author cheolhee
*/
public class PoloniexTradingAPIClient implements TradingAPIClient {
private static final String TRADING_URL = "https://poloniex.com/tradingApi?";
private final String apiKey;
private final String apiSecret; | // Path: src/main/java/com/cf/TradingAPIClient.java
// public interface TradingAPIClient
// {
// public String returnBalances();
//
// public String returnCompleteBalances();
//
// public String returnFeeInfo();
//
// public String returnOpenOrders(String currencyPair);
//
// public String returnTradeHistory(String currencyPair);
//
// public String returnOrderTrades(String orderNumber);
//
// public String returnOrderStatus(String orderNumber);
//
// public String cancelOrder(String orderNumber);
//
// public String moveOrder(String orderNumber, BigDecimal rate);
//
// public String sell(String currencyPair, BigDecimal buyPrice, BigDecimal amount, boolean fillOrKill, boolean immediateOrCancel, boolean postOnly);
//
// public String buy(String currencyPair, BigDecimal buyPrice, BigDecimal amount, boolean fillOrKill, boolean immediateOrCancel, boolean postOnly);
//
// public String withdraw(String currency, BigDecimal amount, String address, String paymentId);
//
// // Lending APIs
// public String returnActiveLoans();
//
// public String returnLendingHistory(int hours, int limit);
//
// public String createLoanOffer(String currency, BigDecimal amount, BigDecimal lendingRate, int duration, boolean autoRenew);
//
// public String cancelLoanOffer(String orderNumber);
//
// public String returnOpenLoanOffers();
//
// public String toggleAutoRenew(String orderNumber);
//
// }
//
// Path: src/main/java/com/cf/client/HTTPClient.java
// public class HTTPClient
// {
//
// private final HttpHost proxy;
//
// public HTTPClient()
// {
// this.proxy = null;
// }
//
// public HTTPClient(HttpHost proxy)
// {
// this.proxy = proxy;
// }
//
//
// public String postHttp(String url, List<NameValuePair> params, List<NameValuePair> headers) throws IOException
// {
// HttpPost post = new HttpPost(url);
// post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
// post.getEntity().toString();
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// post.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(post);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
//
// public String getHttp(String url, List<NameValuePair> headers) throws IOException
// {
// HttpRequestBase request = new HttpGet(url);
//
// if (headers != null)
// {
// for (NameValuePair header : headers)
// {
// request.addHeader(header.getName(), header.getValue());
// }
// }
//
// HttpClient httpClient = HttpClientBuilder.create().setProxy(proxy).build();
// HttpResponse response = httpClient.execute(request);
//
// HttpEntity entity = response.getEntity();
// if (entity != null)
// {
// return EntityUtils.toString(entity);
//
// }
// return null;
// }
// }
// Path: src/main/java/com/cf/client/poloniex/PoloniexTradingAPIClient.java
import com.cf.TradingAPIClient;
import com.cf.client.HTTPClient;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
package com.cf.client.poloniex;
/**
*
* @author David
* @author cheolhee
*/
public class PoloniexTradingAPIClient implements TradingAPIClient {
private static final String TRADING_URL = "https://poloniex.com/tradingApi?";
private final String apiKey;
private final String apiSecret; | private final HTTPClient client; |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/qq/QQAuth.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONObject;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; | package ezy.sdk3rd.social.platforms.qq;
/**
* Created by ezy on 17/3/18.
*/
public class QQAuth implements IAuthorize {
public static final String TAG = "ezy.sdk3rd.qq.auth";
Activity mActivity; | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/qq/QQAuth.java
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONObject;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
package ezy.sdk3rd.social.platforms.qq;
/**
* Created by ezy on 17/3/18.
*/
public class QQAuth implements IAuthorize {
public static final String TAG = "ezy.sdk3rd.qq.auth";
Activity mActivity; | Platform mPlatform; |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/qq/QQAuth.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONObject;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; | package ezy.sdk3rd.social.platforms.qq;
/**
* Created by ezy on 17/3/18.
*/
public class QQAuth implements IAuthorize {
public static final String TAG = "ezy.sdk3rd.qq.auth";
Activity mActivity;
Platform mPlatform;
Tencent mApi;
IUiListener mListener;
QQAuth(Activity activity, Platform platform) {
mActivity = activity;
mPlatform = platform;
mApi = Tencent.createInstance(platform.getAppId(), mActivity);
}
String toMessage(UiError error) {
return "[" + error.errorCode + "]" + error.errorMessage;
}
@Override | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/qq/QQAuth.java
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONObject;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
package ezy.sdk3rd.social.platforms.qq;
/**
* Created by ezy on 17/3/18.
*/
public class QQAuth implements IAuthorize {
public static final String TAG = "ezy.sdk3rd.qq.auth";
Activity mActivity;
Platform mPlatform;
Tencent mApi;
IUiListener mListener;
QQAuth(Activity activity, Platform platform) {
mActivity = activity;
mPlatform = platform;
mApi = Tencent.createInstance(platform.getAppId(), mActivity);
}
String toMessage(UiError error) {
return "[" + error.errorCode + "]" + error.errorMessage;
}
@Override | public void authorize(@NonNull final OnCallback<String> callback) { |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/qq/QQAuth.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONObject;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; |
IUiListener mListener;
QQAuth(Activity activity, Platform platform) {
mActivity = activity;
mPlatform = platform;
mApi = Tencent.createInstance(platform.getAppId(), mActivity);
}
String toMessage(UiError error) {
return "[" + error.errorCode + "]" + error.errorMessage;
}
@Override
public void authorize(@NonNull final OnCallback<String> callback) {
mListener = new IUiListener() {
@Override
public void onComplete(Object response) {
Log.e(TAG, "complete ==> " + response);
if (response instanceof JSONObject && ((JSONObject) response).length() > 0) {
JSONObject jo = (JSONObject) response;
String token = jo.optString(Constants.PARAM_ACCESS_TOKEN);
String expires = jo.optString(Constants.PARAM_EXPIRES_IN);
String openId = jo.optString(Constants.PARAM_OPEN_ID);
if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
mApi.setAccessToken(token, expires);
mApi.setOpenId(openId);
}
callback.onSucceed(mActivity, "token|" + mApi.getOpenId() + "|" + mApi.getAccessToken());
} else { | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/qq/QQAuth.java
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.json.JSONObject;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
IUiListener mListener;
QQAuth(Activity activity, Platform platform) {
mActivity = activity;
mPlatform = platform;
mApi = Tencent.createInstance(platform.getAppId(), mActivity);
}
String toMessage(UiError error) {
return "[" + error.errorCode + "]" + error.errorMessage;
}
@Override
public void authorize(@NonNull final OnCallback<String> callback) {
mListener = new IUiListener() {
@Override
public void onComplete(Object response) {
Log.e(TAG, "complete ==> " + response);
if (response instanceof JSONObject && ((JSONObject) response).length() > 0) {
JSONObject jo = (JSONObject) response;
String token = jo.optString(Constants.PARAM_ACCESS_TOKEN);
String expires = jo.optString(Constants.PARAM_EXPIRES_IN);
String openId = jo.optString(Constants.PARAM_OPEN_ID);
if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
mApi.setAccessToken(token, expires);
mApi.setOpenId(openId);
}
callback.onSucceed(mActivity, "token|" + mApi.getOpenId() + "|" + mApi.getAccessToken());
} else { | callback.onFailed(mActivity, ResultCode.RESULT_FAILED, "登录失败: 返回为空"); |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXCallbackActivity.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
| import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import ezy.sdk3rd.social.sdk.IResult; | package ezy.sdk3rd.social.platforms.weixin;
public class WXCallbackActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Log.e(WXBase.TAG, "==> " + ((getIntent() == null) ? "" : getIntent().getExtras()));
| // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXCallbackActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import ezy.sdk3rd.social.sdk.IResult;
package ezy.sdk3rd.social.platforms.weixin;
public class WXCallbackActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Log.e(WXBase.TAG, "==> " + ((getIntent() == null) ? "" : getIntent().getExtras()));
| for (IResult service: WXBase.services.keySet()) { |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXBase.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.WeakHashMap;
import ezy.sdk3rd.social.sdk.IResult;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; | package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
abstract class WXBase implements IResult, IWXAPIEventHandler {
public static final String TAG = "ezy.sdk3rd.wx";
public static int REQUEST_CODE = 1999;
static WeakHashMap<IResult, Boolean> services = new WeakHashMap<>();
final protected Activity mActivity; | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXBase.java
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.WeakHashMap;
import ezy.sdk3rd.social.sdk.IResult;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
abstract class WXBase implements IResult, IWXAPIEventHandler {
public static final String TAG = "ezy.sdk3rd.wx";
public static int REQUEST_CODE = 1999;
static WeakHashMap<IResult, Boolean> services = new WeakHashMap<>();
final protected Activity mActivity; | final protected Platform mPlatform; |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXBase.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.WeakHashMap;
import ezy.sdk3rd.social.sdk.IResult;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; | package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
abstract class WXBase implements IResult, IWXAPIEventHandler {
public static final String TAG = "ezy.sdk3rd.wx";
public static int REQUEST_CODE = 1999;
static WeakHashMap<IResult, Boolean> services = new WeakHashMap<>();
final protected Activity mActivity;
final protected Platform mPlatform;
| // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXBase.java
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.WeakHashMap;
import ezy.sdk3rd.social.sdk.IResult;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
abstract class WXBase implements IResult, IWXAPIEventHandler {
public static final String TAG = "ezy.sdk3rd.wx";
public static int REQUEST_CODE = 1999;
static WeakHashMap<IResult, Boolean> services = new WeakHashMap<>();
final protected Activity mActivity;
final protected Platform mPlatform;
| protected OnCallback mCallback; |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXBase.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.WeakHashMap;
import ezy.sdk3rd.social.sdk.IResult;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; |
@Override
public void onResult(int requestCode, int resultCode, Intent data) {
if (mApi != null && requestCode == REQUEST_CODE) {
mApi.handleIntent(data, this);
}
}
@Override
public void onReq(BaseReq req) {
Log.e(TAG, "transaction = " + req.transaction + ", type = " + req.getType() + ", openId = " + req.openId);
}
@Override
public void onResp(BaseResp resp) {
Log.e(TAG, "transaction = " + resp.transaction + ", type = " + resp.getType() + ", errCode = " + resp.errCode + ", err = " + resp.errStr);
if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
switch (resp.getType()) {
case ConstantsAPI.COMMAND_SENDAUTH:
onResultOk((SendAuth.Resp) resp);
break;
case ConstantsAPI.COMMAND_PAY_BY_WX:
onResultOk((PayResp) resp);
break;
case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
onResultOk((SendMessageToWX.Resp) resp);
break;
}
} else if (resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) { | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IResult.java
// public interface IResult {
// void onResult(int requestCode, int resultCode, Intent data);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXBase.java
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.WeakHashMap;
import ezy.sdk3rd.social.sdk.IResult;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
@Override
public void onResult(int requestCode, int resultCode, Intent data) {
if (mApi != null && requestCode == REQUEST_CODE) {
mApi.handleIntent(data, this);
}
}
@Override
public void onReq(BaseReq req) {
Log.e(TAG, "transaction = " + req.transaction + ", type = " + req.getType() + ", openId = " + req.openId);
}
@Override
public void onResp(BaseResp resp) {
Log.e(TAG, "transaction = " + resp.transaction + ", type = " + resp.getType() + ", errCode = " + resp.errCode + ", err = " + resp.errStr);
if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
switch (resp.getType()) {
case ConstantsAPI.COMMAND_SENDAUTH:
onResultOk((SendAuth.Resp) resp);
break;
case ConstantsAPI.COMMAND_PAY_BY_WX:
onResultOk((PayResp) resp);
break;
case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX:
onResultOk((SendMessageToWX.Resp) resp);
break;
}
} else if (resp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) { | mCallback.onFailed(mActivity, ResultCode.RESULT_CANCELLED, toMessage(resp)); |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXAuth.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IDisposable.java
// public interface IDisposable {
// void onDispose();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.util.Log;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import java.io.Closeable;
import java.io.IOException;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.IDisposable;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; | package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
public class WXAuth extends WXBase implements IAuthorize, IDisposable {
WXAuth(Activity activity, Platform platform) {
super(activity, platform);
}
@Override | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IDisposable.java
// public interface IDisposable {
// void onDispose();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXAuth.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.util.Log;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import java.io.Closeable;
import java.io.IOException;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.IDisposable;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
public class WXAuth extends WXBase implements IAuthorize, IDisposable {
WXAuth(Activity activity, Platform platform) {
super(activity, platform);
}
@Override | public void authorize(@NonNull OnCallback<String> callback) { |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXAuth.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IDisposable.java
// public interface IDisposable {
// void onDispose();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.util.Log;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import java.io.Closeable;
import java.io.IOException;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.IDisposable;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode; | package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
public class WXAuth extends WXBase implements IAuthorize, IDisposable {
WXAuth(Activity activity, Platform platform) {
super(activity, platform);
}
@Override
public void authorize(@NonNull OnCallback<String> callback) {
mCallback = callback;
if (!mApi.isWXAppInstalled()) { | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/authorize/IAuthorize.java
// public interface IAuthorize extends IResult {
// void authorize(OnCallback<String> callback);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/IDisposable.java
// public interface IDisposable {
// void onDispose();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/OnCallback.java
// public interface OnCallback<T> {
// void onStarted(Activity activity);
// void onCompleted(Activity activity);
// void onSucceed(Activity activity, T result);
// void onFailed(Activity activity, int code, String message);
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/Platform.java
// public class Platform {
// final String name;
// final String appId;
//
// Map<String, String> extra;
//
// public Platform(@NonNull String name, @NonNull String appId) {
// this.name = name;
// this.appId = appId;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAppId() {
// return appId;
// }
//
// public String extra(String key) {
// return extra == null ? "" : extra.get(key);
// }
//
// public Platform extra(String key, String value) {
// if (extra == null) {
// extra = new HashMap<>();
// }
// extra.put(key, value);
// return this;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/sdk/ResultCode.java
// public class ResultCode {
// public static final int RESULT_OK = 0;
// public static final int RESULT_PENDING = 1;
// public static final int RESULT_CANCELLED = 2;
// public static final int RESULT_FAILED = 3;
//
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/platforms/weixin/WXAuth.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.util.Log;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import java.io.Closeable;
import java.io.IOException;
import ezy.sdk3rd.social.authorize.IAuthorize;
import ezy.sdk3rd.social.sdk.IDisposable;
import ezy.sdk3rd.social.sdk.OnCallback;
import ezy.sdk3rd.social.sdk.Platform;
import ezy.sdk3rd.social.sdk.ResultCode;
package ezy.sdk3rd.social.platforms.weixin;
/**
* Created by ezy on 17/3/18.
*/
public class WXAuth extends WXBase implements IAuthorize, IDisposable {
WXAuth(Activity activity, Platform platform) {
super(activity, platform);
}
@Override
public void authorize(@NonNull OnCallback<String> callback) {
mCallback = callback;
if (!mApi.isWXAppInstalled()) { | mCallback.onFailed(mActivity, ResultCode.RESULT_FAILED, "您未安装微信!"); |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
| import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource; | package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) { | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource;
package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) { | resource = new UrlResource(url); |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
| import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource; | package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) {
resource = new UrlResource(url);
}
public MoImage(File file) { | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource;
package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) {
resource = new UrlResource(url);
}
public MoImage(File file) { | resource = new FileResource(file); |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
| import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource; | package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) {
resource = new UrlResource(url);
}
public MoImage(File file) {
resource = new FileResource(file);
}
public MoImage(byte[] bytes) { | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource;
package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) {
resource = new UrlResource(url);
}
public MoImage(File file) {
resource = new FileResource(file);
}
public MoImage(byte[] bytes) { | resource = new BytesResource(bytes); |
czy1121/sdk3rd | ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
| import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource; | package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) {
resource = new UrlResource(url);
}
public MoImage(File file) {
resource = new FileResource(file);
}
public MoImage(byte[] bytes) {
resource = new BytesResource(bytes);
}
public MoImage(Bitmap bitmap) { | // Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BitmapResource.java
// public class BitmapResource implements ImageResource {
// public final Bitmap bitmap;
//
// public BitmapResource(Bitmap bitmap) {
// this.bitmap = bitmap;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return bitmap;
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(bitmap, Bitmap.CompressFormat.JPEG);
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/BytesResource.java
// public class BytesResource implements ImageResource {
// public final byte[] bytes;
//
// public BytesResource(byte[] bytes) {
// this.bytes = bytes;
// }
//
// @Override
// public String toUri() {
// return null;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(bytes);
// }
//
// @Override
// public byte[] toBytes() {
// return bytes;
// }
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/FileResource.java
// public class FileResource implements ImageResource {
// public final File file;
//
// public FileResource(File file) {
// this.file = file;
// }
//
// @Override
// public String toUri() {
// return file.toString();
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(file);
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.toBytes(ImageTool.toBitmap(file), Bitmap.CompressFormat.JPEG);
// }
//
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/ImageResource.java
// public interface ImageResource {
//
// String toUri();
//
// Bitmap toBitmap();
//
// byte[] toBytes();
// }
//
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/image/resource/UrlResource.java
// public class UrlResource implements ImageResource {
// public final String url;
//
// public UrlResource(String url) {
// this.url = url;
// }
//
// @Override
// public String toUri() {
// return url;
// }
//
// @Override
// public Bitmap toBitmap() {
// return ImageTool.toBitmap(ImageTool.loadNetImage(url));
// }
//
// @Override
// public byte[] toBytes() {
// return ImageTool.loadNetImage(url);
// }
// }
// Path: ezy.sdk3rd.social/src/main/java/ezy/sdk3rd/social/share/media/MoImage.java
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import java.io.File;
import ezy.sdk3rd.social.share.image.resource.BitmapResource;
import ezy.sdk3rd.social.share.image.resource.BytesResource;
import ezy.sdk3rd.social.share.image.resource.FileResource;
import ezy.sdk3rd.social.share.image.resource.ImageResource;
import ezy.sdk3rd.social.share.image.resource.UrlResource;
package ezy.sdk3rd.social.share.media;
public class MoImage implements IMediaObject {
public ImageResource resource;
public MoImage(@NonNull ImageResource resource) {
this.resource = resource;
}
public MoImage(String url) {
resource = new UrlResource(url);
}
public MoImage(File file) {
resource = new FileResource(file);
}
public MoImage(byte[] bytes) {
resource = new BytesResource(bytes);
}
public MoImage(Bitmap bitmap) { | resource = new BitmapResource(bitmap); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.