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 |
|---|---|---|---|---|---|---|
shapesecurity/shape-functional-java | src/test/java/com/shapesecurity/functional/data/ConcatListTest.java | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
| import java.util.function.IntFunction;
import com.shapesecurity.functional.F;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; | return acc;
}
private static ConcatList<Integer> genRL(int size) {
ConcatList<Integer> acc = ConcatList.empty();
for (int i = 0; i < size; i++) {
acc = acc.append1(i);
}
return acc;
}
@Parameterized.Parameter
public IntFunction<ConcatList<Integer>> generator;
@Test
public void simpleTest() {
assertTrue(ConcatList.empty().isEmpty());
assertFalse(ConcatList.single(0).isEmpty());
ConcatList<Integer> bt = ConcatList.single(0);
for (int i = 0; i < 10; i++) {
bt = bt.append(bt);
}
assertEquals(1024, bt.length);
assertFalse(bt.isEmpty());
assertFalse(ConcatList.empty().append(ConcatList.single(0)).isEmpty());
assertFalse(ConcatList.single(0).append(ConcatList.single(0)).isEmpty());
}
@Test
public void findTest() { | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
// Path: src/test/java/com/shapesecurity/functional/data/ConcatListTest.java
import java.util.function.IntFunction;
import com.shapesecurity.functional.F;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
return acc;
}
private static ConcatList<Integer> genRL(int size) {
ConcatList<Integer> acc = ConcatList.empty();
for (int i = 0; i < size; i++) {
acc = acc.append1(i);
}
return acc;
}
@Parameterized.Parameter
public IntFunction<ConcatList<Integer>> generator;
@Test
public void simpleTest() {
assertTrue(ConcatList.empty().isEmpty());
assertFalse(ConcatList.single(0).isEmpty());
ConcatList<Integer> bt = ConcatList.single(0);
for (int i = 0; i < 10; i++) {
bt = bt.append(bt);
}
assertEquals(1024, bt.length);
assertFalse(bt.isEmpty());
assertFalse(ConcatList.empty().append(ConcatList.single(0)).isEmpty());
assertFalse(ConcatList.single(0).append(ConcatList.single(0)).isEmpty());
}
@Test
public void findTest() { | assertEquals(Maybe.<Integer>empty(), ConcatList.<Integer>empty().find(F.constant(true))); |
shapesecurity/shape-functional-java | src/test/java/com/shapesecurity/functional/data/EitherTest.java | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.shapesecurity.functional.F;
import org.junit.Test; | /*
* Copyright 2014 Shape Security, 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.shapesecurity.functional.data;
public class EitherTest {
@Test
public void simpleTests() {
Either<String, Integer> e1 = Either.left("a");
Either<String, Integer> e2 = Either.right(1); | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
// Path: src/test/java/com/shapesecurity/functional/data/EitherTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.shapesecurity.functional.F;
import org.junit.Test;
/*
* Copyright 2014 Shape Security, 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.shapesecurity.functional.data;
public class EitherTest {
@Test
public void simpleTests() {
Either<String, Integer> e1 = Either.left("a");
Either<String, Integer> e2 = Either.right(1); | F<Integer, Integer> plusOne = integer -> integer + 1; |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/Tuple4.java | // Path: src/main/java/com/shapesecurity/functional/data/HashCodeBuilder.java
// @CheckReturnValue
// public final class HashCodeBuilder {
// //int is a 32 bit integer
// private static final int INITIAL_VALUE = -2128831035;
// private static final int MULT = 16777619;
// private static final int NULL_SIGIL = -1150993239;
//
// public static int init() {
// return INITIAL_VALUE;
// }
//
// public static int put(int hash, @Nullable Object os) {
// int p = os == null ? NULL_SIGIL : os.hashCode();
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
//
// public static int putChar(int hash, char p) {
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
// }
| import com.shapesecurity.functional.data.HashCodeBuilder;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull; | return new Tuple4<>(f.apply(this.a), this.b, this.c, this.d);
}
@Nonnull
public <B1> Tuple4<A, B1, C, D> mapB(@Nonnull F<B, B1> f) {
return new Tuple4<>(this.a, f.apply(this.b), this.c, this.d);
}
@Nonnull
public <C1> Tuple4<A, B, C1, D> mapC(@Nonnull F<C, C1> f) {
return new Tuple4<>(this.a, this.b, f.apply(this.c), this.d);
}
@Nonnull
public <D1> Tuple4<A, B, C, D1> mapD(@Nonnull F<D, D1> f) {
return new Tuple4<>(this.a, this.b, this.c, f.apply(this.d));
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof Tuple4 &&
((Tuple4<A, B, C, D>) obj).a.equals(this.a) &&
((Tuple4<A, B, C, D>) obj).b.equals(this.b) &&
((Tuple4<A, B, C, D>) obj).c.equals(this.c) &&
((Tuple4<A, B, C, D>) obj).d.equals(this.d);
}
@Override
public int hashCode() { | // Path: src/main/java/com/shapesecurity/functional/data/HashCodeBuilder.java
// @CheckReturnValue
// public final class HashCodeBuilder {
// //int is a 32 bit integer
// private static final int INITIAL_VALUE = -2128831035;
// private static final int MULT = 16777619;
// private static final int NULL_SIGIL = -1150993239;
//
// public static int init() {
// return INITIAL_VALUE;
// }
//
// public static int put(int hash, @Nullable Object os) {
// int p = os == null ? NULL_SIGIL : os.hashCode();
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
//
// public static int putChar(int hash, char p) {
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
// }
// Path: src/main/java/com/shapesecurity/functional/Tuple4.java
import com.shapesecurity.functional.data.HashCodeBuilder;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
return new Tuple4<>(f.apply(this.a), this.b, this.c, this.d);
}
@Nonnull
public <B1> Tuple4<A, B1, C, D> mapB(@Nonnull F<B, B1> f) {
return new Tuple4<>(this.a, f.apply(this.b), this.c, this.d);
}
@Nonnull
public <C1> Tuple4<A, B, C1, D> mapC(@Nonnull F<C, C1> f) {
return new Tuple4<>(this.a, this.b, f.apply(this.c), this.d);
}
@Nonnull
public <D1> Tuple4<A, B, C, D1> mapD(@Nonnull F<D, D1> f) {
return new Tuple4<>(this.a, this.b, this.c, f.apply(this.d));
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof Tuple4 &&
((Tuple4<A, B, C, D>) obj).a.equals(this.a) &&
((Tuple4<A, B, C, D>) obj).b.equals(this.b) &&
((Tuple4<A, B, C, D>) obj).c.equals(this.c) &&
((Tuple4<A, B, C, D>) obj).d.equals(this.d);
}
@Override
public int hashCode() { | int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Tuple4"); |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/Monoid.java | // Path: src/main/java/com/shapesecurity/functional/Unit.java
// public final class Unit {
// public final static Unit unit = new Unit();
//
// private Unit() {
// }
// }
| import com.shapesecurity.functional.Unit;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull; | /*
* Copyright 2014 Shape Security, 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.shapesecurity.functional.data;
@CheckReturnValue
public interface Monoid<T> extends Semigroup<T> {
public static final UnitIdentity UNIT = new UnitIdentity();
public static final IntegerAdditive INTEGER_ADDITIVE = new IntegerAdditive();
public static final IntegerMultiplicative INTEGER_MULTIPLICATIVE = new IntegerMultiplicative();
public static final StringConcat STRING_CONCAT = new StringConcat();
public static final BooleanOr BOOLEAN_OR = new BooleanOr();
public static final BooleanAnd BOOLEAN_AND = new BooleanAnd();
@Nonnull
T identity();
| // Path: src/main/java/com/shapesecurity/functional/Unit.java
// public final class Unit {
// public final static Unit unit = new Unit();
//
// private Unit() {
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/Monoid.java
import com.shapesecurity.functional.Unit;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
/*
* Copyright 2014 Shape Security, 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.shapesecurity.functional.data;
@CheckReturnValue
public interface Monoid<T> extends Semigroup<T> {
public static final UnitIdentity UNIT = new UnitIdentity();
public static final IntegerAdditive INTEGER_ADDITIVE = new IntegerAdditive();
public static final IntegerMultiplicative INTEGER_MULTIPLICATIVE = new IntegerMultiplicative();
public static final StringConcat STRING_CONCAT = new StringConcat();
public static final BooleanOr BOOLEAN_OR = new BooleanOr();
public static final BooleanAnd BOOLEAN_AND = new BooleanAnd();
@Nonnull
T identity();
| public static class UnitIdentity extends Semigroup.UnitIdentity implements Monoid<Unit> { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/Maybe.java | // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
| import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier; |
@Nonnull
@Deprecated
public static <A> Maybe<A> just(@Nonnull A a) {
return Maybe.of(a);
}
@Nonnull
public static <A> Maybe<A> fromNullable(@Nullable A a) {
if (a == null) {
return empty();
}
return of(a);
}
@Nullable
public A toNullable() {
return this.value;
}
public static <A> Maybe<A> join(@Nonnull Maybe<Maybe<A>> m) {
return m.flatMap((a) -> a);
}
@Nonnull
public static <A> ImmutableList<A> catMaybes(@Nonnull ImmutableList<Maybe<A>> l) {
return l.foldRight((a, b) -> a.maybe(b, c -> ImmutableList.cons(c, b)), ImmutableList.empty());
}
@Nonnull | // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/Maybe.java
import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
@Nonnull
@Deprecated
public static <A> Maybe<A> just(@Nonnull A a) {
return Maybe.of(a);
}
@Nonnull
public static <A> Maybe<A> fromNullable(@Nullable A a) {
if (a == null) {
return empty();
}
return of(a);
}
@Nullable
public A toNullable() {
return this.value;
}
public static <A> Maybe<A> join(@Nonnull Maybe<Maybe<A>> m) {
return m.flatMap((a) -> a);
}
@Nonnull
public static <A> ImmutableList<A> catMaybes(@Nonnull ImmutableList<Maybe<A>> l) {
return l.foldRight((a, b) -> a.maybe(b, c -> ImmutableList.cons(c, b)), ImmutableList.empty());
}
@Nonnull | public static <A, B> ImmutableList<B> mapMaybe(@Nonnull final F<A, B> f, @Nonnull ImmutableList<Maybe<A>> l) { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/Maybe.java | // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
| import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier; | }
@Nullable
public A toNullable() {
return this.value;
}
public static <A> Maybe<A> join(@Nonnull Maybe<Maybe<A>> m) {
return m.flatMap((a) -> a);
}
@Nonnull
public static <A> ImmutableList<A> catMaybes(@Nonnull ImmutableList<Maybe<A>> l) {
return l.foldRight((a, b) -> a.maybe(b, c -> ImmutableList.cons(c, b)), ImmutableList.empty());
}
@Nonnull
public static <A, B> ImmutableList<B> mapMaybe(@Nonnull final F<A, B> f, @Nonnull ImmutableList<Maybe<A>> l) {
return l.foldRight((a, b) -> a.maybe(b, v -> ImmutableList.cons(f.apply(v), b)), ImmutableList.empty());
}
@SuppressWarnings("BooleanParameter")
@Nonnull
public static <A> Maybe<A> iff(boolean test, @Nonnull A a) {
if (test) {
return of(a);
}
return empty();
}
@Nonnull | // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/Maybe.java
import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
}
@Nullable
public A toNullable() {
return this.value;
}
public static <A> Maybe<A> join(@Nonnull Maybe<Maybe<A>> m) {
return m.flatMap((a) -> a);
}
@Nonnull
public static <A> ImmutableList<A> catMaybes(@Nonnull ImmutableList<Maybe<A>> l) {
return l.foldRight((a, b) -> a.maybe(b, c -> ImmutableList.cons(c, b)), ImmutableList.empty());
}
@Nonnull
public static <A, B> ImmutableList<B> mapMaybe(@Nonnull final F<A, B> f, @Nonnull ImmutableList<Maybe<A>> l) {
return l.foldRight((a, b) -> a.maybe(b, v -> ImmutableList.cons(f.apply(v), b)), ImmutableList.empty());
}
@SuppressWarnings("BooleanParameter")
@Nonnull
public static <A> Maybe<A> iff(boolean test, @Nonnull A a) {
if (test) {
return of(a);
}
return empty();
}
@Nonnull | public static <A> Maybe<A> _try(@Nonnull ThrowingSupplier<A> s) { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/Maybe.java | // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
| import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier; | }
@SuppressWarnings("unchecked")
@Override
public final boolean equals(Object obj) {
return obj == this || obj instanceof Maybe && this.eq((Maybe<A>) obj);
}
@Override
public int hashCode() {
return this.value == null ? NOTHING_HASH_CODE :
HashCodeBuilder.put(this.value.hashCode(), "Just");
}
@Nonnull
public A fromJust() throws NullPointerException {
return Objects.requireNonNull(this.value);
}
@Nonnull
@Deprecated
public A just() throws NullPointerException {
return this.fromJust();
}
@Nonnull
public <B> B maybe(@Nonnull B def, @Nonnull F<A, B> f) {
return this.value == null ? def : f.apply(this.value);
}
| // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/Maybe.java
import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
}
@SuppressWarnings("unchecked")
@Override
public final boolean equals(Object obj) {
return obj == this || obj instanceof Maybe && this.eq((Maybe<A>) obj);
}
@Override
public int hashCode() {
return this.value == null ? NOTHING_HASH_CODE :
HashCodeBuilder.put(this.value.hashCode(), "Just");
}
@Nonnull
public A fromJust() throws NullPointerException {
return Objects.requireNonNull(this.value);
}
@Nonnull
@Deprecated
public A just() throws NullPointerException {
return this.fromJust();
}
@Nonnull
public <B> B maybe(@Nonnull B def, @Nonnull F<A, B> f) {
return this.value == null ? def : f.apply(this.value);
}
| public final void foreach(@Nonnull Effect<A> f) { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/Maybe.java | // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
| import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier; | if (this.value == null) {
r.run();
} else {
f.apply(this.value);
}
}
public boolean isJust() {
return this.value != null;
}
public final boolean isNothing() {
return !this.isJust();
}
@Nonnull
public ImmutableList<A> toList() {
return this.value == null ? ImmutableList.empty() : ImmutableList.from(this.value);
}
@Nonnull
public A orJust(@Nonnull A a) {
return this.value == null ? a : this.value;
}
/**
* @deprecated Use {@link #orJustLazy(Supplier)} instead.
*/
@Nonnull
@Deprecated | // Path: src/main/java/com/shapesecurity/functional/Effect.java
// @FunctionalInterface
// public interface Effect<A> extends F<A, Unit> {
// void e(@Nonnull A a);
//
// @Nonnull
// default Unit apply(@Nonnull A a) {
// this.e(a);
// return Unit.unit;
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/ThrowingSupplier.java
// @FunctionalInterface
// public interface ThrowingSupplier<A> {
// A get() throws Exception;
// }
//
// Path: src/main/java/com/shapesecurity/functional/Thunk.java
// public final class Thunk<A> {
// @Nonnull
// private final Supplier<A> supplier;
// // Exception on style: private nullable.
// @Nullable
// private volatile A value = null;
//
// private Thunk(@Nonnull Supplier<A> supplier) {
// this.supplier = supplier;
// }
//
// @Nonnull
// public static <A> Thunk<A> constant(@Nonnull final A value) {
// Thunk<A> t = new Thunk<>(() -> value);
// t.value = value;
// return t;
// }
//
// @Nonnull
// public static <A> Thunk<A> from(@Nonnull Supplier<A> supplier) {
// return new Thunk<>(supplier);
// }
//
// @Nonnull
// public final A get() {
// // Double locked.
// A value = this.value;
// if (value == null) {
// synchronized (this) {
// value = this.value;
// if (value == null) {
// value = this.supplier.get();
// this.value = value;
// }
// }
// }
// return value;
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/Maybe.java
import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.ThrowingSupplier;
import com.shapesecurity.functional.Thunk;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.function.Supplier;
if (this.value == null) {
r.run();
} else {
f.apply(this.value);
}
}
public boolean isJust() {
return this.value != null;
}
public final boolean isNothing() {
return !this.isJust();
}
@Nonnull
public ImmutableList<A> toList() {
return this.value == null ? ImmutableList.empty() : ImmutableList.from(this.value);
}
@Nonnull
public A orJust(@Nonnull A a) {
return this.value == null ? a : this.value;
}
/**
* @deprecated Use {@link #orJustLazy(Supplier)} instead.
*/
@Nonnull
@Deprecated | public A orJustLazy(@Nonnull Thunk<A> a) { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/NonEmptyImmutableList.java | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
| import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull;
import java.util.ArrayList; | @Nonnull
@Override
public Maybe<ImmutableList<T>> maybeTail() {
return Maybe.of(this.tail);
}
@Nonnull
@Override
public Maybe<ImmutableList<T>> maybeInit() {
return Maybe.of(this.init());
}
@Nonnull
public T last() {
NonEmptyImmutableList<T> other = this;
while (true) {
if (other.tail instanceof NonEmptyImmutableList) {
other = ((NonEmptyImmutableList<T>) other.tail);
} else {
return other.head;
}
}
}
@Nonnull
public ImmutableList<T> init() {
return fromBounded(this.toObjectArray(), 0, this.length - 1);
}
@Override | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/NonEmptyImmutableList.java
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull;
import java.util.ArrayList;
@Nonnull
@Override
public Maybe<ImmutableList<T>> maybeTail() {
return Maybe.of(this.tail);
}
@Nonnull
@Override
public Maybe<ImmutableList<T>> maybeInit() {
return Maybe.of(this.init());
}
@Nonnull
public T last() {
NonEmptyImmutableList<T> other = this;
while (true) {
if (other.tail instanceof NonEmptyImmutableList) {
other = ((NonEmptyImmutableList<T>) other.tail);
} else {
return other.head;
}
}
}
@Nonnull
public ImmutableList<T> init() {
return fromBounded(this.toObjectArray(), 0, this.length - 1);
}
@Override | public int count(@Nonnull F<T, Boolean> f) { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/NonEmptyImmutableList.java | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
| import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull;
import java.util.ArrayList; | @Override
public boolean every(@Nonnull F<T, Boolean> f) {
NonEmptyImmutableList<T> list = this;
while (true) {
if (!f.apply(list.head)) {
return false;
}
if (list.tail instanceof Nil) {
return true;
}
list = ((NonEmptyImmutableList<T>) list.tail);
}
}
@Override
public boolean contains(@Nonnull T a) {
NonEmptyImmutableList<T> list = this;
while (true) {
if (list.head == a) {
return true;
}
if (list.tail instanceof Nil) {
return false;
}
list = ((NonEmptyImmutableList<T>) list.tail);
}
}
@Nonnull
@Override | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/NonEmptyImmutableList.java
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull;
import java.util.ArrayList;
@Override
public boolean every(@Nonnull F<T, Boolean> f) {
NonEmptyImmutableList<T> list = this;
while (true) {
if (!f.apply(list.head)) {
return false;
}
if (list.tail instanceof Nil) {
return true;
}
list = ((NonEmptyImmutableList<T>) list.tail);
}
}
@Override
public boolean contains(@Nonnull T a) {
NonEmptyImmutableList<T> list = this;
while (true) {
if (list.head == a) {
return true;
}
if (list.tail instanceof Nil) {
return false;
}
list = ((NonEmptyImmutableList<T>) list.tail);
}
}
@Nonnull
@Override | public Pair<ImmutableList<T>, ImmutableList<T>> span(@Nonnull F<T, Boolean> f) { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/Tuple3.java | // Path: src/main/java/com/shapesecurity/functional/data/HashCodeBuilder.java
// @CheckReturnValue
// public final class HashCodeBuilder {
// //int is a 32 bit integer
// private static final int INITIAL_VALUE = -2128831035;
// private static final int MULT = 16777619;
// private static final int NULL_SIGIL = -1150993239;
//
// public static int init() {
// return INITIAL_VALUE;
// }
//
// public static int put(int hash, @Nullable Object os) {
// int p = os == null ? NULL_SIGIL : os.hashCode();
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
//
// public static int putChar(int hash, char p) {
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
// }
| import com.shapesecurity.functional.data.HashCodeBuilder;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull; | this.b = b;
this.c = c;
}
@Nonnull
public <A1> Tuple3<A1, B, C> mapA(@Nonnull F<A, A1> f) {
return new Tuple3<>(f.apply(this.a), this.b, this.c);
}
@Nonnull
public <B1> Tuple3<A, B1, C> mapB(@Nonnull F<B, B1> f) {
return new Tuple3<>(this.a, f.apply(this.b), this.c);
}
@Nonnull
public <C1> Tuple3<A, B, C1> mapC(@Nonnull F<C, C1> f) {
return new Tuple3<>(this.a, this.b, f.apply(this.c));
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof Tuple3 &&
((Tuple3<A, B, C>) obj).a.equals(this.a) &&
((Tuple3<A, B, C>) obj).b.equals(this.b) &&
((Tuple3<A, B, C>) obj).c.equals(this.c);
}
@Override
public int hashCode() { | // Path: src/main/java/com/shapesecurity/functional/data/HashCodeBuilder.java
// @CheckReturnValue
// public final class HashCodeBuilder {
// //int is a 32 bit integer
// private static final int INITIAL_VALUE = -2128831035;
// private static final int MULT = 16777619;
// private static final int NULL_SIGIL = -1150993239;
//
// public static int init() {
// return INITIAL_VALUE;
// }
//
// public static int put(int hash, @Nullable Object os) {
// int p = os == null ? NULL_SIGIL : os.hashCode();
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
//
// public static int putChar(int hash, char p) {
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
// }
// Path: src/main/java/com/shapesecurity/functional/Tuple3.java
import com.shapesecurity.functional.data.HashCodeBuilder;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
this.b = b;
this.c = c;
}
@Nonnull
public <A1> Tuple3<A1, B, C> mapA(@Nonnull F<A, A1> f) {
return new Tuple3<>(f.apply(this.a), this.b, this.c);
}
@Nonnull
public <B1> Tuple3<A, B1, C> mapB(@Nonnull F<B, B1> f) {
return new Tuple3<>(this.a, f.apply(this.b), this.c);
}
@Nonnull
public <C1> Tuple3<A, B, C1> mapC(@Nonnull F<C, C1> f) {
return new Tuple3<>(this.a, this.b, f.apply(this.c));
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof Tuple3 &&
((Tuple3<A, B, C>) obj).a.equals(this.a) &&
((Tuple3<A, B, C>) obj).b.equals(this.b) &&
((Tuple3<A, B, C>) obj).c.equals(this.c);
}
@Override
public int hashCode() { | int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Tuple3"); |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/Pair.java | // Path: src/main/java/com/shapesecurity/functional/data/HashCodeBuilder.java
// @CheckReturnValue
// public final class HashCodeBuilder {
// //int is a 32 bit integer
// private static final int INITIAL_VALUE = -2128831035;
// private static final int MULT = 16777619;
// private static final int NULL_SIGIL = -1150993239;
//
// public static int init() {
// return INITIAL_VALUE;
// }
//
// public static int put(int hash, @Nullable Object os) {
// int p = os == null ? NULL_SIGIL : os.hashCode();
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
//
// public static int putChar(int hash, char p) {
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
// }
| import com.shapesecurity.functional.data.HashCodeBuilder;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull; | return new Pair<>(f.apply(this.left), this.right);
}
@Nonnull
@Deprecated
public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
return this.mapLeft(f);
}
@Nonnull
public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
return new Pair<>(this.left, f.apply(this.right));
}
@Nonnull
@Deprecated
public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
return this.mapRight(f);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof Pair &&
((Pair<A, B>) obj).left.equals(this.left) &&
((Pair<A, B>) obj).right.equals(this.right);
}
@Override
public int hashCode() { | // Path: src/main/java/com/shapesecurity/functional/data/HashCodeBuilder.java
// @CheckReturnValue
// public final class HashCodeBuilder {
// //int is a 32 bit integer
// private static final int INITIAL_VALUE = -2128831035;
// private static final int MULT = 16777619;
// private static final int NULL_SIGIL = -1150993239;
//
// public static int init() {
// return INITIAL_VALUE;
// }
//
// public static int put(int hash, @Nullable Object os) {
// int p = os == null ? NULL_SIGIL : os.hashCode();
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
//
// public static int putChar(int hash, char p) {
// hash = hash * MULT ^ (p & 255);
// p >>>= 8;
// hash = hash * MULT ^ (p & 255);
// return hash;
// }
// }
// Path: src/main/java/com/shapesecurity/functional/Pair.java
import com.shapesecurity.functional.data.HashCodeBuilder;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
return new Pair<>(f.apply(this.left), this.right);
}
@Nonnull
@Deprecated
public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
return this.mapLeft(f);
}
@Nonnull
public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
return new Pair<>(this.left, f.apply(this.right));
}
@Nonnull
@Deprecated
public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
return this.mapRight(f);
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj) {
return obj == this || obj instanceof Pair &&
((Pair<A, B>) obj).left.equals(this.left) &&
((Pair<A, B>) obj).right.equals(this.right);
}
@Override
public int hashCode() { | int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair"); |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/Nil.java | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
| import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull; | @Override
public <A> A foldRight(@Nonnull F2<? super T, A, A> f, @Nonnull A init) {
return init;
}
@Nonnull
@Override
public Maybe<T> maybeHead() {
return Maybe.empty();
}
@Nonnull
@Override
public Maybe<T> maybeLast() {
return Maybe.empty();
}
@Nonnull
@Override
public Maybe<ImmutableList<T>> maybeTail() {
return Maybe.empty();
}
@Nonnull
@Override
public Maybe<ImmutableList<T>> maybeInit() {
return Maybe.empty();
}
@Override | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/Nil.java
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull;
@Override
public <A> A foldRight(@Nonnull F2<? super T, A, A> f, @Nonnull A init) {
return init;
}
@Nonnull
@Override
public Maybe<T> maybeHead() {
return Maybe.empty();
}
@Nonnull
@Override
public Maybe<T> maybeLast() {
return Maybe.empty();
}
@Nonnull
@Override
public Maybe<ImmutableList<T>> maybeTail() {
return Maybe.empty();
}
@Nonnull
@Override
public Maybe<ImmutableList<T>> maybeInit() {
return Maybe.empty();
}
@Override | public int count(@Nonnull F<T, Boolean> f) { |
shapesecurity/shape-functional-java | src/main/java/com/shapesecurity/functional/data/Nil.java | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
| import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull; | @Override
public boolean isEmpty() {
return true;
}
@Nonnull
@Override
@SuppressWarnings("unchecked")
public <B extends T> ImmutableList<T> append(@Nonnull ImmutableList<B> defaultClause) {
// This is safe due to erasure.
return (ImmutableList<T>) defaultClause;
}
@Override
public boolean exists(@Nonnull F<T, Boolean> f) {
return false;
}
@Override
public boolean every(@Nonnull F<T, Boolean> f) {
return true;
}
@Override
public boolean contains(@Nonnull T a) {
return false;
}
@Nonnull
@Override | // Path: src/main/java/com/shapesecurity/functional/F.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F<A, R> {
// @Nonnull
// static <A extends B, B> F<A, B> id() {
// return o -> o;
// }
//
// @Nonnull
// static <A, B> F<A, B> constant(@Nonnull final B b) {
// return a -> b;
// }
//
// @Nonnull
// static <A, B, C> F2<A, B, C> uncurry(@Nonnull final F<A, F<B, C>> f) {
// return (a, b) -> f.apply(a).apply(b);
// }
//
// @Nonnull
// static <A, B, C> F<B, F<A, C>> flip(@Nonnull final F<A, F<B, C>> f) {
// return b -> a -> f.apply(a).apply(b);
// }
//
// @Nonnull
// R apply(@Nonnull A a);
//
// @Nonnull
// default <C> F<C, R> compose(@Nonnull final F<C, A> f) {
// return c -> this.apply(f.apply(c));
// }
//
//
// @Nonnull
// default <B> F<A, B> then(@Nonnull final F<R, B> f) {
// return c -> f.apply(this.apply(c));
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/F2.java
// @CheckReturnValue
// @FunctionalInterface
// public interface F2<A, B, R> {
// @Nonnull
// R apply(@Nonnull A a, @Nonnull B b);
//
// @Nonnull
// default R applyTuple(@Nonnull Pair<A, B> args) {
// return this.apply(args.left, args.right);
// }
//
// @Nonnull
// default F<B, R> curry(@Nonnull final A a) {
// return b -> this.apply(a, b);
// }
//
// @Nonnull
// default F<A, F<B, R>> curry() {
// return a -> b -> this.apply(a, b);
// }
//
// @Nonnull
// default F2<B, A, R> flip() {
// return (b, a) -> this.apply(a, b);
// }
// }
//
// Path: src/main/java/com/shapesecurity/functional/Pair.java
// @CheckReturnValue
// public final class Pair<A, B> {
// public final A left;
// public final B right;
//
// @Deprecated
// public final A a;
// @Deprecated
// public final B b;
//
// /**
// * Constructor method to utilize type inference.
// * @param left first component
// * @param right second component
// * @param <A> type of the first component
// * @param <B> type of the second component
// * @return the pair
// */
// @Nonnull
// public static <A, B> Pair<A, B> of(A left, B right) {
// return new Pair<>(left, right);
// }
//
// @Nonnull
// @Deprecated
// public static <A, B> Pair<A, B> make(A left, B right) {
// return Pair.of(left, right);
// }
//
// public Pair(A left, B right) {
// super();
// this.left = this.a = left;
// this.right = this.b = right;
//
// }
//
// public A left() {
// return this.left;
// }
//
// public B right() {
// return this.right;
// }
//
// @Nonnull
// public Pair<B, A> swap() {
// return new Pair<>(this.right, this.left);
// }
//
// @Nonnull
// public <A1, B1> Pair<A1, B1> map(@Nonnull F<A, A1> fA, @Nonnull F<B, B1> fB) {
// return new Pair<>(fA.apply(this.left), fB.apply(this.right));
// }
//
// @Nonnull
// public <A1> Pair<A1, B> mapLeft(@Nonnull F<A, A1> f) {
// return new Pair<>(f.apply(this.left), this.right);
// }
//
// @Nonnull
// @Deprecated
// public <A1> Pair<A1, B> mapA(@Nonnull F<A, A1> f) {
// return this.mapLeft(f);
// }
//
// @Nonnull
// public <B1> Pair<A, B1> mapRight(@Nonnull F<B, B1> f) {
// return new Pair<>(this.left, f.apply(this.right));
// }
//
// @Nonnull
// @Deprecated
// public <B1> Pair<A, B1> mapB(@Nonnull F<B, B1> f) {
// return this.mapRight(f);
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object obj) {
// return obj == this || obj instanceof Pair &&
// ((Pair<A, B>) obj).left.equals(this.left) &&
// ((Pair<A, B>) obj).right.equals(this.right);
// }
//
// @Override
// public int hashCode() {
// int hash = HashCodeBuilder.put(HashCodeBuilder.init(), "Pair");
// hash = HashCodeBuilder.put(hash, this.left);
// return HashCodeBuilder.put(hash, this.right);
// }
// }
// Path: src/main/java/com/shapesecurity/functional/data/Nil.java
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import javax.annotation.Nonnull;
@Override
public boolean isEmpty() {
return true;
}
@Nonnull
@Override
@SuppressWarnings("unchecked")
public <B extends T> ImmutableList<T> append(@Nonnull ImmutableList<B> defaultClause) {
// This is safe due to erasure.
return (ImmutableList<T>) defaultClause;
}
@Override
public boolean exists(@Nonnull F<T, Boolean> f) {
return false;
}
@Override
public boolean every(@Nonnull F<T, Boolean> f) {
return true;
}
@Override
public boolean contains(@Nonnull T a) {
return false;
}
@Nonnull
@Override | public Pair<ImmutableList<T>, ImmutableList<T>> span(@Nonnull F<T, Boolean> f) { |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/domain/Domain.java | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
| import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.validator.GenericValidator;
import com.plexobject.rbac.Configuration;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey; | package com.plexobject.rbac.domain;
/**
* The application defines a subject application that will define a set of
* permissions and then validates them at runtime
*
*/
@Entity
@XmlRootElement
public class Domain extends PersistentObject implements Validatable,
Identifiable<String> { | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/domain/Domain.java
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.validator.GenericValidator;
import com.plexobject.rbac.Configuration;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
package com.plexobject.rbac.domain;
/**
* The application defines a subject application that will define a set of
* permissions and then validates them at runtime
*
*/
@Entity
@XmlRootElement
public class Domain extends PersistentObject implements Validatable,
Identifiable<String> { | public static final String DEFAULT_DOMAIN_NAME = Configuration |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/web/filter/DomainOwnerFilter.java | // Path: src/main/java/com/plexobject/rbac/ServiceFactory.java
// public class ServiceFactory {
// private static RepositoryFactory REPOSITORY_FACTORY = new RepositoryFactoryImpl();
// private static PermissionManager PERMISSION_MANAGER = new PermissionManagerImpl(
// REPOSITORY_FACTORY, new JavascriptEvaluator());
//
// public static RepositoryFactory getDefaultFactory() {
// return REPOSITORY_FACTORY;
// }
//
// public static PermissionManager getPermissionManager() {
// return PERMISSION_MANAGER;
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/repository/RepositoryFactory.java
// public interface RepositoryFactory {
// /**
// *
// * @return instance of security repository
// */
// SecurityMappingRepository getSecurityMappingRepository(String domain);
//
// /**
// *
// * @return instance of domain repository to manage domains
// */
// DomainRepository getDomainRepository();
//
// /**
// *
// * @return high level domain for this application
// */
// Subject getSuperAdmin();
//
// /**
// *
// * @return high level domain for this application
// */
// Domain getDefaultDomain();
//
// /**
// *
// * @param domain
// * @return repository of roles for specific domain
// */
// RoleRepository getRoleRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of permissions for given domain
// */
// PermissionRepository getPermissionRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of security errors for given domain
// */
// SecurityErrorRepository getSecurityErrorRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of subjects for given domain
// */
// SubjectRepository getSubjectRepository(String domain);
//
// /**
// *
// * @return
// */
// SubjectRepository getDefaultSubjectRepository();
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
| import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.plexobject.rbac.ServiceFactory;
import com.plexobject.rbac.repository.RepositoryFactory;
import com.plexobject.rbac.utils.CurrentRequest;
import com.sun.jersey.spi.inject.Inject; | package com.plexobject.rbac.web.filter;
public class DomainOwnerFilter implements Filter {
private static final Logger LOGGER = Logger
.getLogger(DomainOwnerFilter.class);
@Autowired
@Inject | // Path: src/main/java/com/plexobject/rbac/ServiceFactory.java
// public class ServiceFactory {
// private static RepositoryFactory REPOSITORY_FACTORY = new RepositoryFactoryImpl();
// private static PermissionManager PERMISSION_MANAGER = new PermissionManagerImpl(
// REPOSITORY_FACTORY, new JavascriptEvaluator());
//
// public static RepositoryFactory getDefaultFactory() {
// return REPOSITORY_FACTORY;
// }
//
// public static PermissionManager getPermissionManager() {
// return PERMISSION_MANAGER;
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/repository/RepositoryFactory.java
// public interface RepositoryFactory {
// /**
// *
// * @return instance of security repository
// */
// SecurityMappingRepository getSecurityMappingRepository(String domain);
//
// /**
// *
// * @return instance of domain repository to manage domains
// */
// DomainRepository getDomainRepository();
//
// /**
// *
// * @return high level domain for this application
// */
// Subject getSuperAdmin();
//
// /**
// *
// * @return high level domain for this application
// */
// Domain getDefaultDomain();
//
// /**
// *
// * @param domain
// * @return repository of roles for specific domain
// */
// RoleRepository getRoleRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of permissions for given domain
// */
// PermissionRepository getPermissionRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of security errors for given domain
// */
// SecurityErrorRepository getSecurityErrorRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of subjects for given domain
// */
// SubjectRepository getSubjectRepository(String domain);
//
// /**
// *
// * @return
// */
// SubjectRepository getDefaultSubjectRepository();
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
// Path: src/main/java/com/plexobject/rbac/web/filter/DomainOwnerFilter.java
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.plexobject.rbac.ServiceFactory;
import com.plexobject.rbac.repository.RepositoryFactory;
import com.plexobject.rbac.utils.CurrentRequest;
import com.sun.jersey.spi.inject.Inject;
package com.plexobject.rbac.web.filter;
public class DomainOwnerFilter implements Filter {
private static final Logger LOGGER = Logger
.getLogger(DomainOwnerFilter.class);
@Autowired
@Inject | RepositoryFactory repositoryFactory = ServiceFactory.getDefaultFactory(); |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/web/filter/DomainOwnerFilter.java | // Path: src/main/java/com/plexobject/rbac/ServiceFactory.java
// public class ServiceFactory {
// private static RepositoryFactory REPOSITORY_FACTORY = new RepositoryFactoryImpl();
// private static PermissionManager PERMISSION_MANAGER = new PermissionManagerImpl(
// REPOSITORY_FACTORY, new JavascriptEvaluator());
//
// public static RepositoryFactory getDefaultFactory() {
// return REPOSITORY_FACTORY;
// }
//
// public static PermissionManager getPermissionManager() {
// return PERMISSION_MANAGER;
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/repository/RepositoryFactory.java
// public interface RepositoryFactory {
// /**
// *
// * @return instance of security repository
// */
// SecurityMappingRepository getSecurityMappingRepository(String domain);
//
// /**
// *
// * @return instance of domain repository to manage domains
// */
// DomainRepository getDomainRepository();
//
// /**
// *
// * @return high level domain for this application
// */
// Subject getSuperAdmin();
//
// /**
// *
// * @return high level domain for this application
// */
// Domain getDefaultDomain();
//
// /**
// *
// * @param domain
// * @return repository of roles for specific domain
// */
// RoleRepository getRoleRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of permissions for given domain
// */
// PermissionRepository getPermissionRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of security errors for given domain
// */
// SecurityErrorRepository getSecurityErrorRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of subjects for given domain
// */
// SubjectRepository getSubjectRepository(String domain);
//
// /**
// *
// * @return
// */
// SubjectRepository getDefaultSubjectRepository();
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
| import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.plexobject.rbac.ServiceFactory;
import com.plexobject.rbac.repository.RepositoryFactory;
import com.plexobject.rbac.utils.CurrentRequest;
import com.sun.jersey.spi.inject.Inject; | package com.plexobject.rbac.web.filter;
public class DomainOwnerFilter implements Filter {
private static final Logger LOGGER = Logger
.getLogger(DomainOwnerFilter.class);
@Autowired
@Inject | // Path: src/main/java/com/plexobject/rbac/ServiceFactory.java
// public class ServiceFactory {
// private static RepositoryFactory REPOSITORY_FACTORY = new RepositoryFactoryImpl();
// private static PermissionManager PERMISSION_MANAGER = new PermissionManagerImpl(
// REPOSITORY_FACTORY, new JavascriptEvaluator());
//
// public static RepositoryFactory getDefaultFactory() {
// return REPOSITORY_FACTORY;
// }
//
// public static PermissionManager getPermissionManager() {
// return PERMISSION_MANAGER;
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/repository/RepositoryFactory.java
// public interface RepositoryFactory {
// /**
// *
// * @return instance of security repository
// */
// SecurityMappingRepository getSecurityMappingRepository(String domain);
//
// /**
// *
// * @return instance of domain repository to manage domains
// */
// DomainRepository getDomainRepository();
//
// /**
// *
// * @return high level domain for this application
// */
// Subject getSuperAdmin();
//
// /**
// *
// * @return high level domain for this application
// */
// Domain getDefaultDomain();
//
// /**
// *
// * @param domain
// * @return repository of roles for specific domain
// */
// RoleRepository getRoleRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of permissions for given domain
// */
// PermissionRepository getPermissionRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of security errors for given domain
// */
// SecurityErrorRepository getSecurityErrorRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of subjects for given domain
// */
// SubjectRepository getSubjectRepository(String domain);
//
// /**
// *
// * @return
// */
// SubjectRepository getDefaultSubjectRepository();
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
// Path: src/main/java/com/plexobject/rbac/web/filter/DomainOwnerFilter.java
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.plexobject.rbac.ServiceFactory;
import com.plexobject.rbac.repository.RepositoryFactory;
import com.plexobject.rbac.utils.CurrentRequest;
import com.sun.jersey.spi.inject.Inject;
package com.plexobject.rbac.web.filter;
public class DomainOwnerFilter implements Filter {
private static final Logger LOGGER = Logger
.getLogger(DomainOwnerFilter.class);
@Autowired
@Inject | RepositoryFactory repositoryFactory = ServiceFactory.getDefaultFactory(); |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/web/filter/DomainOwnerFilter.java | // Path: src/main/java/com/plexobject/rbac/ServiceFactory.java
// public class ServiceFactory {
// private static RepositoryFactory REPOSITORY_FACTORY = new RepositoryFactoryImpl();
// private static PermissionManager PERMISSION_MANAGER = new PermissionManagerImpl(
// REPOSITORY_FACTORY, new JavascriptEvaluator());
//
// public static RepositoryFactory getDefaultFactory() {
// return REPOSITORY_FACTORY;
// }
//
// public static PermissionManager getPermissionManager() {
// return PERMISSION_MANAGER;
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/repository/RepositoryFactory.java
// public interface RepositoryFactory {
// /**
// *
// * @return instance of security repository
// */
// SecurityMappingRepository getSecurityMappingRepository(String domain);
//
// /**
// *
// * @return instance of domain repository to manage domains
// */
// DomainRepository getDomainRepository();
//
// /**
// *
// * @return high level domain for this application
// */
// Subject getSuperAdmin();
//
// /**
// *
// * @return high level domain for this application
// */
// Domain getDefaultDomain();
//
// /**
// *
// * @param domain
// * @return repository of roles for specific domain
// */
// RoleRepository getRoleRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of permissions for given domain
// */
// PermissionRepository getPermissionRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of security errors for given domain
// */
// SecurityErrorRepository getSecurityErrorRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of subjects for given domain
// */
// SubjectRepository getSubjectRepository(String domain);
//
// /**
// *
// * @return
// */
// SubjectRepository getDefaultSubjectRepository();
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
| import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.plexobject.rbac.ServiceFactory;
import com.plexobject.rbac.repository.RepositoryFactory;
import com.plexobject.rbac.utils.CurrentRequest;
import com.sun.jersey.spi.inject.Inject; | package com.plexobject.rbac.web.filter;
public class DomainOwnerFilter implements Filter {
private static final Logger LOGGER = Logger
.getLogger(DomainOwnerFilter.class);
@Autowired
@Inject
RepositoryFactory repositoryFactory = ServiceFactory.getDefaultFactory();
@SuppressWarnings("unused")
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
if (repositoryFactory.getDomainRepository().isSubjectOwner( | // Path: src/main/java/com/plexobject/rbac/ServiceFactory.java
// public class ServiceFactory {
// private static RepositoryFactory REPOSITORY_FACTORY = new RepositoryFactoryImpl();
// private static PermissionManager PERMISSION_MANAGER = new PermissionManagerImpl(
// REPOSITORY_FACTORY, new JavascriptEvaluator());
//
// public static RepositoryFactory getDefaultFactory() {
// return REPOSITORY_FACTORY;
// }
//
// public static PermissionManager getPermissionManager() {
// return PERMISSION_MANAGER;
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/repository/RepositoryFactory.java
// public interface RepositoryFactory {
// /**
// *
// * @return instance of security repository
// */
// SecurityMappingRepository getSecurityMappingRepository(String domain);
//
// /**
// *
// * @return instance of domain repository to manage domains
// */
// DomainRepository getDomainRepository();
//
// /**
// *
// * @return high level domain for this application
// */
// Subject getSuperAdmin();
//
// /**
// *
// * @return high level domain for this application
// */
// Domain getDefaultDomain();
//
// /**
// *
// * @param domain
// * @return repository of roles for specific domain
// */
// RoleRepository getRoleRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of permissions for given domain
// */
// PermissionRepository getPermissionRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of security errors for given domain
// */
// SecurityErrorRepository getSecurityErrorRepository(String domain);
//
// /**
// *
// * @param domain
// * @return repository of subjects for given domain
// */
// SubjectRepository getSubjectRepository(String domain);
//
// /**
// *
// * @return
// */
// SubjectRepository getDefaultSubjectRepository();
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
// Path: src/main/java/com/plexobject/rbac/web/filter/DomainOwnerFilter.java
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.plexobject.rbac.ServiceFactory;
import com.plexobject.rbac.repository.RepositoryFactory;
import com.plexobject.rbac.utils.CurrentRequest;
import com.sun.jersey.spi.inject.Inject;
package com.plexobject.rbac.web.filter;
public class DomainOwnerFilter implements Filter {
private static final Logger LOGGER = Logger
.getLogger(DomainOwnerFilter.class);
@Autowired
@Inject
RepositoryFactory repositoryFactory = ServiceFactory.getDefaultFactory();
@SuppressWarnings("unused")
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
if (repositoryFactory.getDomainRepository().isSubjectOwner( | CurrentRequest.getDomain(), CurrentRequest.getSubjectName())) { |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/utils/IDUtils.java | // Path: src/main/java/com/plexobject/rbac/domain/Identifiable.java
// public interface Identifiable<ID> {
// ID getId();
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import com.plexobject.rbac.domain.Identifiable; | package com.plexobject.rbac.utils;
public class IDUtils {
@SuppressWarnings("unchecked")
public static String getIdsAsString( | // Path: src/main/java/com/plexobject/rbac/domain/Identifiable.java
// public interface Identifiable<ID> {
// ID getId();
// }
// Path: src/main/java/com/plexobject/rbac/utils/IDUtils.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import com.plexobject.rbac.domain.Identifiable;
package com.plexobject.rbac.utils;
public class IDUtils {
@SuppressWarnings("unchecked")
public static String getIdsAsString( | Collection<? extends Identifiable> objects) { |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/service/SubjectsService.java | // Path: src/main/java/com/plexobject/rbac/domain/Subject.java
// @Entity
// @XmlRootElement
// public class Subject extends PersistentObject implements Validatable,
// Identifiable<String> {
// public static final Subject SUPER_ADMIN = new Subject(Configuration
// .getInstance()
// .getProperty("super_admin_subjectName", "super_admin"),
// PasswordUtils.getHash(Configuration.getInstance().getProperty(
// "super_admin_credentials", "changeme")));
// @PrimaryKey
// private String id;
// private String credentials;
//
// // for JPA
// Subject() {
// }
//
// @XmlElement
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// if (GenericValidator.isBlankOrNull(id)) {
// throw new IllegalArgumentException("subjectName not specified");
// }
//
// this.id = id;
// }
//
// public Subject(final String id, final String credentials) {
// setId(id);
// setCredentials(credentials);
// }
//
// public void setCredentials(String credentials) {
// this.credentials = credentials;
// }
//
// public String getCredentials() {
// return credentials;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Subject)) {
// return false;
// }
// Subject rhs = (Subject) object;
// return new EqualsBuilder().append(this.id, rhs.id).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(this.id)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("subjectName", this.id)
// .toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(id)) {
// errorsByField.put("id", "subjectName is not specified");
// }
//
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
//
// }
| import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Subject; | package com.plexobject.rbac.service;
public interface SubjectsService {
Response get(String domain, String subjectName);
Response index(String domain, String lastKey, int limit);
| // Path: src/main/java/com/plexobject/rbac/domain/Subject.java
// @Entity
// @XmlRootElement
// public class Subject extends PersistentObject implements Validatable,
// Identifiable<String> {
// public static final Subject SUPER_ADMIN = new Subject(Configuration
// .getInstance()
// .getProperty("super_admin_subjectName", "super_admin"),
// PasswordUtils.getHash(Configuration.getInstance().getProperty(
// "super_admin_credentials", "changeme")));
// @PrimaryKey
// private String id;
// private String credentials;
//
// // for JPA
// Subject() {
// }
//
// @XmlElement
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// if (GenericValidator.isBlankOrNull(id)) {
// throw new IllegalArgumentException("subjectName not specified");
// }
//
// this.id = id;
// }
//
// public Subject(final String id, final String credentials) {
// setId(id);
// setCredentials(credentials);
// }
//
// public void setCredentials(String credentials) {
// this.credentials = credentials;
// }
//
// public String getCredentials() {
// return credentials;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Subject)) {
// return false;
// }
// Subject rhs = (Subject) object;
// return new EqualsBuilder().append(this.id, rhs.id).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(this.id)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("subjectName", this.id)
// .toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(id)) {
// errorsByField.put("id", "subjectName is not specified");
// }
//
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/service/SubjectsService.java
import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Subject;
package com.plexobject.rbac.service;
public interface SubjectsService {
Response get(String domain, String subjectName);
Response index(String domain, String lastKey, int limit);
| Response put(String domain, Subject subject); |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/service/RolesService.java | // Path: src/main/java/com/plexobject/rbac/domain/Role.java
// @Entity
// @XmlRootElement
// public class Role extends PersistentObject implements Validatable,
// Identifiable<String> {
// public static final Role ANONYMOUS = new Role("anonymous");
// public static final Role SUPER_ADMIN = new Role("super_admin");
//
// @PrimaryKey
// private String id;
//
// @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Role.class)
// Set<String> parentIds = new HashSet<String>();
//
// @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Subject.class, onRelatedEntityDelete = DeleteAction.NULLIFY)
// Set<String> subjectIds = new HashSet<String>();
//
// Role() {
// }
//
// public Role(String id) {
// this(id, (Role) null);
// }
//
// public Role(String id, Role parent) {
// setId(id);
// if (parent != null) {
// addParentId(parent.getId());
// } else if (ANONYMOUS != null) {
// addParentId(ANONYMOUS.getId());
// }
// }
//
// public Role(String id, Set<String> parentIds) {
// setId(id);
// if (parentIds != null && parentIds.size() > 0) {
// setParentIds(parentIds);
// } else {
// addParentId(ANONYMOUS.getId());
// }
// }
//
// @XmlElement
// public String getId() {
// return id;
// }
//
// void setId(String id) {
// this.id = id;
// }
//
// @XmlTransient
// public Set<String> getSubjectIds() {
// return new HashSet<String>(subjectIds);
// }
//
// public void setSubjectIds(Set<String> subjectIds) {
// firePropertyChange("subjectIds", this.subjectIds, subjectIds);
//
// this.subjectIds.clear();
// this.subjectIds.addAll(subjectIds);
// }
//
// public void addSubject(String subjectName) {
// Set<String> old = getSubjectIds();
// this.subjectIds.add(subjectName);
// firePropertyChange("subjectIds", old, this.subjectIds);
//
// }
//
// public void removeSubject(String subjectName) {
// Set<String> old = getSubjectIds();
// this.subjectIds.remove(subjectName);
// firePropertyChange("subjectIds", old, this.subjectIds);
// }
//
// public void addSubject(Subject subject) {
// addSubject(subject.getId());
// }
//
// public void removeSubject(Subject subject) {
// removeSubject(subject.getId());
// }
//
// @XmlElement
// public Set<String> getParentIds() {
// return new HashSet<String>(parentIds);
// }
//
// public boolean hasParentIds() {
// return parentIds != null && parentIds.size() > 0;
// }
//
// public void setParentIds(Set<String> parentIds) {
// firePropertyChange("parentIds", this.parentIds, parentIds);
//
// this.parentIds.clear();
// this.parentIds.addAll(parentIds);
// }
//
// public void addParentId(String parentId) {
// Set<String> old = getParentIds();
// this.parentIds.add(parentId);
// firePropertyChange("parentIds", old, this.parentIds);
//
// }
//
// public void removeParentId(String parentId) {
// Set<String> old = getParentIds();
// this.parentIds.remove(parentId);
// firePropertyChange("parentIds", old, this.parentIds);
// }
//
// public void addParentId(Role parent) {
// addParentId(parent.getId());
// }
//
// public void removeParentId(Role parent) {
// removeParentId(parent.getId());
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Role)) {
// return false;
// }
// Role rhs = (Role) object;
// return new EqualsBuilder().append(this.id, rhs.id).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(this.id)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("rolename", this.id).append(
// "subjectIds", this.subjectIds).append("parentIds",
// this.parentIds).toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(id)) {
// errorsByField.put("id", "rolename is not specified");
// }
// if ((parentIds == null || parentIds.size() == 0)
// && !ANONYMOUS.getId().equals(id)) {
// addParentId(ANONYMOUS.getId());
// }
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
//
// }
| import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Role; | package com.plexobject.rbac.service;
public interface RolesService {
Response get(String domain, String rolename);
Response index(String domain, String lastKey, int limit);
| // Path: src/main/java/com/plexobject/rbac/domain/Role.java
// @Entity
// @XmlRootElement
// public class Role extends PersistentObject implements Validatable,
// Identifiable<String> {
// public static final Role ANONYMOUS = new Role("anonymous");
// public static final Role SUPER_ADMIN = new Role("super_admin");
//
// @PrimaryKey
// private String id;
//
// @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Role.class)
// Set<String> parentIds = new HashSet<String>();
//
// @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Subject.class, onRelatedEntityDelete = DeleteAction.NULLIFY)
// Set<String> subjectIds = new HashSet<String>();
//
// Role() {
// }
//
// public Role(String id) {
// this(id, (Role) null);
// }
//
// public Role(String id, Role parent) {
// setId(id);
// if (parent != null) {
// addParentId(parent.getId());
// } else if (ANONYMOUS != null) {
// addParentId(ANONYMOUS.getId());
// }
// }
//
// public Role(String id, Set<String> parentIds) {
// setId(id);
// if (parentIds != null && parentIds.size() > 0) {
// setParentIds(parentIds);
// } else {
// addParentId(ANONYMOUS.getId());
// }
// }
//
// @XmlElement
// public String getId() {
// return id;
// }
//
// void setId(String id) {
// this.id = id;
// }
//
// @XmlTransient
// public Set<String> getSubjectIds() {
// return new HashSet<String>(subjectIds);
// }
//
// public void setSubjectIds(Set<String> subjectIds) {
// firePropertyChange("subjectIds", this.subjectIds, subjectIds);
//
// this.subjectIds.clear();
// this.subjectIds.addAll(subjectIds);
// }
//
// public void addSubject(String subjectName) {
// Set<String> old = getSubjectIds();
// this.subjectIds.add(subjectName);
// firePropertyChange("subjectIds", old, this.subjectIds);
//
// }
//
// public void removeSubject(String subjectName) {
// Set<String> old = getSubjectIds();
// this.subjectIds.remove(subjectName);
// firePropertyChange("subjectIds", old, this.subjectIds);
// }
//
// public void addSubject(Subject subject) {
// addSubject(subject.getId());
// }
//
// public void removeSubject(Subject subject) {
// removeSubject(subject.getId());
// }
//
// @XmlElement
// public Set<String> getParentIds() {
// return new HashSet<String>(parentIds);
// }
//
// public boolean hasParentIds() {
// return parentIds != null && parentIds.size() > 0;
// }
//
// public void setParentIds(Set<String> parentIds) {
// firePropertyChange("parentIds", this.parentIds, parentIds);
//
// this.parentIds.clear();
// this.parentIds.addAll(parentIds);
// }
//
// public void addParentId(String parentId) {
// Set<String> old = getParentIds();
// this.parentIds.add(parentId);
// firePropertyChange("parentIds", old, this.parentIds);
//
// }
//
// public void removeParentId(String parentId) {
// Set<String> old = getParentIds();
// this.parentIds.remove(parentId);
// firePropertyChange("parentIds", old, this.parentIds);
// }
//
// public void addParentId(Role parent) {
// addParentId(parent.getId());
// }
//
// public void removeParentId(Role parent) {
// removeParentId(parent.getId());
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Role)) {
// return false;
// }
// Role rhs = (Role) object;
// return new EqualsBuilder().append(this.id, rhs.id).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(this.id)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("rolename", this.id).append(
// "subjectIds", this.subjectIds).append("parentIds",
// this.parentIds).toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(id)) {
// errorsByField.put("id", "rolename is not specified");
// }
// if ((parentIds == null || parentIds.size() == 0)
// && !ANONYMOUS.getId().equals(id)) {
// addParentId(ANONYMOUS.getId());
// }
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/service/RolesService.java
import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Role;
package com.plexobject.rbac.service;
public interface RolesService {
Response get(String domain, String rolename);
Response index(String domain, String lastKey, int limit);
| Response put(String domain, Role role); |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/service/DomainsService.java | // Path: src/main/java/com/plexobject/rbac/domain/Domain.java
// @Entity
// @XmlRootElement
// public class Domain extends PersistentObject implements Validatable,
// Identifiable<String> {
// public static final String DEFAULT_DOMAIN_NAME = Configuration
// .getInstance().getProperty("default.domain", "default");
//
// @PrimaryKey
// private String id;
// private String description;
// // @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity =
// // Subject.class, onRelatedEntityDelete = DeleteAction.NULLIFY)
// Set<String> ownerSubjectNames = new HashSet<String>();
//
// // for JPA
// Domain() {
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// public Domain(final String id, final String description) {
// setId(id);
// setDescription(description);
// }
//
// void setId(final String id) {
// if (GenericValidator.isBlankOrNull(id)) {
// throw new IllegalArgumentException("id is not specified");
// }
// this.id = id;
// }
//
// @XmlElement
// public String getId() {
// return id;
// }
//
// public Set<String> getOwnerSubjectNames() {
// return new HashSet<String>(ownerSubjectNames);
// }
//
// public void setOwnerSubjectNames(final Set<String> ownerSubjectNames) {
// firePropertyChange("ownerSubjectNames", this.ownerSubjectNames,
// ownerSubjectNames);
//
// this.ownerSubjectNames.clear();
// this.ownerSubjectNames.addAll(ownerSubjectNames);
// }
//
// public void addOwner(final String subjectName) {
// if (GenericValidator.isBlankOrNull(subjectName)) {
// throw new IllegalArgumentException("subjectName is not specified");
// }
// Set<String> old = getOwnerSubjectNames();
// this.ownerSubjectNames.add(subjectName);
// firePropertyChange("ownerSubjectNames", old, this.ownerSubjectNames);
//
// }
//
// public void addOwner(final Subject subject) {
// if (subject == null) {
// throw new IllegalArgumentException("subject is not specified");
// }
// addOwner(subject.getId());
// }
//
// public void removeOwner(final Subject subject) {
// if (subject == null) {
// throw new IllegalArgumentException("subject is not specified");
// }
// removeOwner(subject.getId());
// }
//
// public void removeOwner(final String subjectName) {
// if (GenericValidator.isBlankOrNull(subjectName)) {
// throw new IllegalArgumentException("subjectName is not specified");
// }
// Set<String> old = getOwnerSubjectNames();
// this.ownerSubjectNames.remove(subjectName);
// firePropertyChange("ownerSubjectNames", old, this.ownerSubjectNames);
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Domain)) {
// return false;
// }
// Domain rhs = (Domain) object;
// return new EqualsBuilder().append(this.id, rhs.id).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(this.id)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("name", this.id).append(
// "owners", this.ownerSubjectNames).toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(id)) {
// errorsByField.put("name", "domain id is not specified");
// }
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
//
// }
| import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Domain; | package com.plexobject.rbac.service;
public interface DomainsService {
Response get(String domain);
Response index(String lastKey, int limit);
| // Path: src/main/java/com/plexobject/rbac/domain/Domain.java
// @Entity
// @XmlRootElement
// public class Domain extends PersistentObject implements Validatable,
// Identifiable<String> {
// public static final String DEFAULT_DOMAIN_NAME = Configuration
// .getInstance().getProperty("default.domain", "default");
//
// @PrimaryKey
// private String id;
// private String description;
// // @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity =
// // Subject.class, onRelatedEntityDelete = DeleteAction.NULLIFY)
// Set<String> ownerSubjectNames = new HashSet<String>();
//
// // for JPA
// Domain() {
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return description;
// }
//
// public Domain(final String id, final String description) {
// setId(id);
// setDescription(description);
// }
//
// void setId(final String id) {
// if (GenericValidator.isBlankOrNull(id)) {
// throw new IllegalArgumentException("id is not specified");
// }
// this.id = id;
// }
//
// @XmlElement
// public String getId() {
// return id;
// }
//
// public Set<String> getOwnerSubjectNames() {
// return new HashSet<String>(ownerSubjectNames);
// }
//
// public void setOwnerSubjectNames(final Set<String> ownerSubjectNames) {
// firePropertyChange("ownerSubjectNames", this.ownerSubjectNames,
// ownerSubjectNames);
//
// this.ownerSubjectNames.clear();
// this.ownerSubjectNames.addAll(ownerSubjectNames);
// }
//
// public void addOwner(final String subjectName) {
// if (GenericValidator.isBlankOrNull(subjectName)) {
// throw new IllegalArgumentException("subjectName is not specified");
// }
// Set<String> old = getOwnerSubjectNames();
// this.ownerSubjectNames.add(subjectName);
// firePropertyChange("ownerSubjectNames", old, this.ownerSubjectNames);
//
// }
//
// public void addOwner(final Subject subject) {
// if (subject == null) {
// throw new IllegalArgumentException("subject is not specified");
// }
// addOwner(subject.getId());
// }
//
// public void removeOwner(final Subject subject) {
// if (subject == null) {
// throw new IllegalArgumentException("subject is not specified");
// }
// removeOwner(subject.getId());
// }
//
// public void removeOwner(final String subjectName) {
// if (GenericValidator.isBlankOrNull(subjectName)) {
// throw new IllegalArgumentException("subjectName is not specified");
// }
// Set<String> old = getOwnerSubjectNames();
// this.ownerSubjectNames.remove(subjectName);
// firePropertyChange("ownerSubjectNames", old, this.ownerSubjectNames);
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Domain)) {
// return false;
// }
// Domain rhs = (Domain) object;
// return new EqualsBuilder().append(this.id, rhs.id).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(this.id)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("name", this.id).append(
// "owners", this.ownerSubjectNames).toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(id)) {
// errorsByField.put("name", "domain id is not specified");
// }
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/service/DomainsService.java
import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Domain;
package com.plexobject.rbac.service;
public interface DomainsService {
Response get(String domain);
Response index(String lastKey, int limit);
| Response put(Domain domain); |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/jmx/JMXRemoteConnector.java | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
| import java.io.Closeable;
import javax.management.JMRuntimeException;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import com.plexobject.rbac.Configuration; | /**
* @see java.lang.Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (!(object instanceof JMXRemoteConnector)) {
return false;
}
JMXRemoteConnector rhs = (JMXRemoteConnector) object;
return new EqualsBuilder().append(this.url, rhs.url).isEquals();
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return new HashCodeBuilder(786529047, 1924536713).append(url)
.toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new ToStringBuilder(this).append("url", this.url).toString();
}
JMXRemoteConnector() { | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/jmx/JMXRemoteConnector.java
import java.io.Closeable;
import javax.management.JMRuntimeException;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import com.plexobject.rbac.Configuration;
/**
* @see java.lang.Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (!(object instanceof JMXRemoteConnector)) {
return false;
}
JMXRemoteConnector rhs = (JMXRemoteConnector) object;
return new EqualsBuilder().append(this.url, rhs.url).isEquals();
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return new HashCodeBuilder(786529047, 1924536713).append(url)
.toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new ToStringBuilder(this).append("url", this.url).toString();
}
JMXRemoteConnector() { | this(Configuration.getInstance().getProperty("weseed.jmx.rmi.host", |
bhatti/PlexRBAC | src/test/java/com/plexobject/rbac/eval/simple/SimpleEvaluatorTest.java | // Path: src/main/java/com/plexobject/rbac/eval/PredicateEvaluator.java
// public interface PredicateEvaluator {
// public boolean evaluate(String expression, Map<String, Object> args);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/IDUtils.java
// public class IDUtils {
// @SuppressWarnings("unchecked")
// public static String getIdsAsString(
// Collection<? extends Identifiable> objects) {
// StringBuilder sb = new StringBuilder("[");
// for (Identifiable o : objects) {
// if (sb.length() > 1) {
// sb.append(",");
// }
// sb.append("\"" + o.getId() + "\"");
// }
// sb.append("]");
// return sb.toString();
// }
//
// public static Collection<Integer> getIdsAsIntegers(
// Collection<? extends Identifiable<Integer>> objects) {
// Collection<Integer> ids = new ArrayList<Integer>();
// for (Identifiable<Integer> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Collection<String> getIdsAsString(
// Collection<? extends Identifiable<String>> objects) {
// Collection<String> ids = new ArrayList<String>();
// for (Identifiable<String> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Map<String, Object> toMap(final Object... keyValues) {
// Map<String, Object> map = new HashMap<String, Object>();
// for (int i = 0; i < keyValues.length - 1; i += 2) {
// map.put(keyValues[i].toString(), keyValues[i + 1]);
// }
// return map;
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import com.plexobject.rbac.eval.PredicateEvaluator;
import com.plexobject.rbac.utils.IDUtils; | package com.plexobject.rbac.eval.simple;
public class SimpleEvaluatorTest {
PredicateEvaluator evaluator = new SimpleEvaluator();
@Test
public void testGetSetContext() {
String expr = "amount <= 500 && dept == 'SALES' && time between 8:00am..5:00pm";
| // Path: src/main/java/com/plexobject/rbac/eval/PredicateEvaluator.java
// public interface PredicateEvaluator {
// public boolean evaluate(String expression, Map<String, Object> args);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/IDUtils.java
// public class IDUtils {
// @SuppressWarnings("unchecked")
// public static String getIdsAsString(
// Collection<? extends Identifiable> objects) {
// StringBuilder sb = new StringBuilder("[");
// for (Identifiable o : objects) {
// if (sb.length() > 1) {
// sb.append(",");
// }
// sb.append("\"" + o.getId() + "\"");
// }
// sb.append("]");
// return sb.toString();
// }
//
// public static Collection<Integer> getIdsAsIntegers(
// Collection<? extends Identifiable<Integer>> objects) {
// Collection<Integer> ids = new ArrayList<Integer>();
// for (Identifiable<Integer> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Collection<String> getIdsAsString(
// Collection<? extends Identifiable<String>> objects) {
// Collection<String> ids = new ArrayList<String>();
// for (Identifiable<String> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Map<String, Object> toMap(final Object... keyValues) {
// Map<String, Object> map = new HashMap<String, Object>();
// for (int i = 0; i < keyValues.length - 1; i += 2) {
// map.put(keyValues[i].toString(), keyValues[i + 1]);
// }
// return map;
// }
// }
// Path: src/test/java/com/plexobject/rbac/eval/simple/SimpleEvaluatorTest.java
import org.junit.Assert;
import org.junit.Test;
import com.plexobject.rbac.eval.PredicateEvaluator;
import com.plexobject.rbac.utils.IDUtils;
package com.plexobject.rbac.eval.simple;
public class SimpleEvaluatorTest {
PredicateEvaluator evaluator = new SimpleEvaluator();
@Test
public void testGetSetContext() {
String expr = "amount <= 500 && dept == 'SALES' && time between 8:00am..5:00pm";
| Assert.assertTrue(evaluator.evaluate(expr, IDUtils.toMap("amount", |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/utils/PasswordUtils.java | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
| import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.plexobject.rbac.Configuration; | package com.plexobject.rbac.utils;
public class PasswordUtils {
private static final byte[] KEY_BYTES = new byte[] { 0x73, 0x2f, 0x2d,
0x33, (byte) 0xc8, 0x01, 0x73, 0x2b, 0x72, 0x06, 0x75, 0x6c,
(byte) 0xbd, 0x44, (byte) 0xf9, (byte) 0xc1, (byte) 0xc1, 0x03,
(byte) 0xdd, (byte) 0xd9, 0x7c, 0x7c, (byte) 0xbe, (byte) 0x8e }; | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/utils/PasswordUtils.java
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.plexobject.rbac.Configuration;
package com.plexobject.rbac.utils;
public class PasswordUtils {
private static final byte[] KEY_BYTES = new byte[] { 0x73, 0x2f, 0x2d,
0x33, (byte) 0xc8, 0x01, 0x73, 0x2b, 0x72, 0x06, 0x75, 0x6c,
(byte) 0xbd, 0x44, (byte) 0xf9, (byte) 0xc1, (byte) 0xc1, 0x03,
(byte) 0xdd, (byte) 0xd9, 0x7c, 0x7c, (byte) 0xbe, (byte) 0x8e }; | private static final String ENCRYPTION_PASSWORD = Configuration |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/metric/Timing.java | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
| import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.log4j.Logger;
import com.plexobject.rbac.Configuration; | package com.plexobject.rbac.metric;
/**
* This class collects timing data but it's not thread safe.
*
* @author Shahzad Bhatti
*
*/
public class Timing {
private static final Logger LOGGER = Logger.getLogger(Timing.class);
private static final long ONE_MILL_SEC = 1000000L;
private static final long LOGGING_THRESHOLD_IN_NANOSECS = ONE_MILL_SEC | // Path: src/main/java/com/plexobject/rbac/Configuration.java
// public class Configuration {
// private static final String RESOURCE_NAME = "application.properties";
// private static final String CONFIG_DATABASE_KEY = "config.db.name";
// private static final String PAGE_SIZE = "page.size";
// private static final int MAX_PAGE_SIZE = 256;
// private static final String DEFAULT_CONFIG_DATABASE = "the_config";
// private static final Logger LOGGER = Logger.getLogger(Configuration.class);
// private static Configuration instance = new Configuration();
//
// private final Properties properties = new Properties();
//
// Configuration() {
// try {
// InputStream in = getClass().getClassLoader().getResourceAsStream(
// RESOURCE_NAME);
// if (in == null) {
// throw new RuntimeException("Failed to find " + RESOURCE_NAME);
// }
// properties.load(in);
// properties.putAll(System.getProperties());
//
// } catch (IOException e) {
// LOGGER.error("Failed to load " + RESOURCE_NAME, e);
// }
// // subject can override any property via command-line system-arguments
//
// properties.putAll(System.getProperties());
//
// }
//
// public static Configuration getInstance() {
// return instance;
// }
//
// public String getConfigDatabase() {
// return getProperty(CONFIG_DATABASE_KEY, DEFAULT_CONFIG_DATABASE);
// }
//
// public int getPageSize() {
// return getInteger(PAGE_SIZE, MAX_PAGE_SIZE);
// }
//
// public String getProperty(final String key) {
// return getProperty(key, null);
// }
//
// public String getProperty(final String key, final String def) {
// return properties.getProperty(key, def);
// }
//
// public int getInteger(final String key) {
// return getInteger(key, 0);
// }
//
// public int getInteger(final String key, final int def) {
// return Integer.parseInt(getProperty(key, String.valueOf(def)));
// }
//
// public double getDouble(final String key) {
// return getDouble(key, 0);
// }
//
// public double getDouble(final String key, final double def) {
// return Double.valueOf(getProperty(key, String.valueOf(def)))
// .doubleValue();
// }
//
// public boolean getBoolean(final String key) {
// return getBoolean(key, false);
// }
//
// public boolean getBoolean(final String key, final boolean def) {
// return Boolean.valueOf(getProperty(key, String.valueOf(def)))
// .booleanValue();
// }
//
// public long getLong(final String key) {
// return getLong(key, 0);
// }
//
// public long getLong(final String key, long def) {
// return Long.valueOf(getProperty(key, String.valueOf(def)));
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/metric/Timing.java
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.log4j.Logger;
import com.plexobject.rbac.Configuration;
package com.plexobject.rbac.metric;
/**
* This class collects timing data but it's not thread safe.
*
* @author Shahzad Bhatti
*
*/
public class Timing {
private static final Logger LOGGER = Logger.getLogger(Timing.class);
private static final long ONE_MILL_SEC = 1000000L;
private static final long LOGGING_THRESHOLD_IN_NANOSECS = ONE_MILL_SEC | * Configuration.getInstance().getInteger( |
bhatti/PlexRBAC | src/test/java/com/plexobject/rbac/eval/js/JavascriptEvaluatorTest.java | // Path: src/main/java/com/plexobject/rbac/eval/PredicateEvaluator.java
// public interface PredicateEvaluator {
// public boolean evaluate(String expression, Map<String, Object> args);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/IDUtils.java
// public class IDUtils {
// @SuppressWarnings("unchecked")
// public static String getIdsAsString(
// Collection<? extends Identifiable> objects) {
// StringBuilder sb = new StringBuilder("[");
// for (Identifiable o : objects) {
// if (sb.length() > 1) {
// sb.append(",");
// }
// sb.append("\"" + o.getId() + "\"");
// }
// sb.append("]");
// return sb.toString();
// }
//
// public static Collection<Integer> getIdsAsIntegers(
// Collection<? extends Identifiable<Integer>> objects) {
// Collection<Integer> ids = new ArrayList<Integer>();
// for (Identifiable<Integer> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Collection<String> getIdsAsString(
// Collection<? extends Identifiable<String>> objects) {
// Collection<String> ids = new ArrayList<String>();
// for (Identifiable<String> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Map<String, Object> toMap(final Object... keyValues) {
// Map<String, Object> map = new HashMap<String, Object>();
// for (int i = 0; i < keyValues.length - 1; i += 2) {
// map.put(keyValues[i].toString(), keyValues[i + 1]);
// }
// return map;
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import com.plexobject.rbac.eval.PredicateEvaluator;
import com.plexobject.rbac.utils.IDUtils; | package com.plexobject.rbac.eval.js;
public class JavascriptEvaluatorTest {
PredicateEvaluator evaluator = new JavascriptEvaluator();
@Test
public void testGetSetContext() {
String expr = "var time=new Date(2010, 0, 1, 12, 0, 0, 0);\namount <= 500 && dept == 'SALES' && time.getHours() >= 8 && time.getHours() <= 17";
| // Path: src/main/java/com/plexobject/rbac/eval/PredicateEvaluator.java
// public interface PredicateEvaluator {
// public boolean evaluate(String expression, Map<String, Object> args);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/IDUtils.java
// public class IDUtils {
// @SuppressWarnings("unchecked")
// public static String getIdsAsString(
// Collection<? extends Identifiable> objects) {
// StringBuilder sb = new StringBuilder("[");
// for (Identifiable o : objects) {
// if (sb.length() > 1) {
// sb.append(",");
// }
// sb.append("\"" + o.getId() + "\"");
// }
// sb.append("]");
// return sb.toString();
// }
//
// public static Collection<Integer> getIdsAsIntegers(
// Collection<? extends Identifiable<Integer>> objects) {
// Collection<Integer> ids = new ArrayList<Integer>();
// for (Identifiable<Integer> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Collection<String> getIdsAsString(
// Collection<? extends Identifiable<String>> objects) {
// Collection<String> ids = new ArrayList<String>();
// for (Identifiable<String> o : objects) {
// ids.add(o.getId());
// }
// return ids;
// }
//
// public static Map<String, Object> toMap(final Object... keyValues) {
// Map<String, Object> map = new HashMap<String, Object>();
// for (int i = 0; i < keyValues.length - 1; i += 2) {
// map.put(keyValues[i].toString(), keyValues[i + 1]);
// }
// return map;
// }
// }
// Path: src/test/java/com/plexobject/rbac/eval/js/JavascriptEvaluatorTest.java
import org.junit.Assert;
import org.junit.Test;
import com.plexobject.rbac.eval.PredicateEvaluator;
import com.plexobject.rbac.utils.IDUtils;
package com.plexobject.rbac.eval.js;
public class JavascriptEvaluatorTest {
PredicateEvaluator evaluator = new JavascriptEvaluator();
@Test
public void testGetSetContext() {
String expr = "var time=new Date(2010, 0, 1, 12, 0, 0, 0);\namount <= 500 && dept == 'SALES' && time.getHours() >= 8 && time.getHours() <= 17";
| Assert.assertTrue(evaluator.evaluate(expr, IDUtils.toMap("amount", |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/cache/CachedMap.java | // Path: src/main/java/com/plexobject/rbac/domain/Pair.java
// public class Pair<FIRST, SECOND> implements java.io.Serializable {
// private static final long serialVersionUID = 1L;
// public FIRST first;
// public SECOND second;
//
// public Pair(FIRST first, SECOND second) {
// this.first = first;
// this.second = second;
// }
//
// public FIRST getFirst() {
// return first;
// }
//
// public void setFirst(FIRST first) {
// this.first = first;
// }
//
// public SECOND getSecond() {
// return second;
// }
//
// public void setSecond(SECOND second) {
// this.second = second;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Pair)) {
// return false;
// }
// Pair<FIRST, SECOND> rhs = (Pair<FIRST, SECOND>) object;
//
// EqualsBuilder eqBuilder = new EqualsBuilder();
// eqBuilder.append(first, rhs.first);
// eqBuilder.append(second, rhs.second);
//
// return eqBuilder.isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(first).append(
// second).toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(first).append(second)
// .toString();
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/TimeUtils.java
// public class TimeUtils {
// public interface TimeSource {
// Date getCurrentTime();
// }
//
// private static TimeSource TIME_SOURCE = new TimeSource() {
// @Override
// public Date getCurrentTime() {
// return new Date();
// }
// };
//
// public static Date getCurrentTime() {
// return TIME_SOURCE.getCurrentTime();
// }
//
// public static long getCurrentTimeMillis() {
// return getCurrentTime().getTime();
// }
//
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.log4j.Logger;
import com.plexobject.rbac.domain.Pair;
import com.plexobject.rbac.utils.TimeUtils; | package com.plexobject.rbac.cache;
/**
* CacheMap - provides lightweight caching based on LRU size and timeout and
* asynchronous reloads.
*
*/
public class CachedMap<K, V> implements Map<K, V>, CacheFlushable {
private static final Logger LOGGER = Logger.getLogger(CachedMap.class);
private final static int MAX_THREADS = 2; // for all cache items across VM
final static int MAX_ITEMS = 1000; // max size
private final static int EXPIRES_IN_SECS = 0; // indefinite
private final static ExecutorService executorService = Executors
.newFixedThreadPool(MAX_THREADS);
class FixedSizeLruLinkedTreeMap<KK, VV> extends LinkedHashMap<KK, VV> {
private static final long serialVersionUID = 1L;
private final int maxSize;
public FixedSizeLruLinkedTreeMap(int initialCapacity, float loadFactor,
int maxSize) {
super(initialCapacity, loadFactor, true);
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<KK, VV> eldest) {
return super.size() > maxSize;
}
}
final long expiresInSecs;
private final CacheLoader<K, V> cacheLoader; | // Path: src/main/java/com/plexobject/rbac/domain/Pair.java
// public class Pair<FIRST, SECOND> implements java.io.Serializable {
// private static final long serialVersionUID = 1L;
// public FIRST first;
// public SECOND second;
//
// public Pair(FIRST first, SECOND second) {
// this.first = first;
// this.second = second;
// }
//
// public FIRST getFirst() {
// return first;
// }
//
// public void setFirst(FIRST first) {
// this.first = first;
// }
//
// public SECOND getSecond() {
// return second;
// }
//
// public void setSecond(SECOND second) {
// this.second = second;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Pair)) {
// return false;
// }
// Pair<FIRST, SECOND> rhs = (Pair<FIRST, SECOND>) object;
//
// EqualsBuilder eqBuilder = new EqualsBuilder();
// eqBuilder.append(first, rhs.first);
// eqBuilder.append(second, rhs.second);
//
// return eqBuilder.isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(first).append(
// second).toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(first).append(second)
// .toString();
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/TimeUtils.java
// public class TimeUtils {
// public interface TimeSource {
// Date getCurrentTime();
// }
//
// private static TimeSource TIME_SOURCE = new TimeSource() {
// @Override
// public Date getCurrentTime() {
// return new Date();
// }
// };
//
// public static Date getCurrentTime() {
// return TIME_SOURCE.getCurrentTime();
// }
//
// public static long getCurrentTimeMillis() {
// return getCurrentTime().getTime();
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/cache/CachedMap.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.log4j.Logger;
import com.plexobject.rbac.domain.Pair;
import com.plexobject.rbac.utils.TimeUtils;
package com.plexobject.rbac.cache;
/**
* CacheMap - provides lightweight caching based on LRU size and timeout and
* asynchronous reloads.
*
*/
public class CachedMap<K, V> implements Map<K, V>, CacheFlushable {
private static final Logger LOGGER = Logger.getLogger(CachedMap.class);
private final static int MAX_THREADS = 2; // for all cache items across VM
final static int MAX_ITEMS = 1000; // max size
private final static int EXPIRES_IN_SECS = 0; // indefinite
private final static ExecutorService executorService = Executors
.newFixedThreadPool(MAX_THREADS);
class FixedSizeLruLinkedTreeMap<KK, VV> extends LinkedHashMap<KK, VV> {
private static final long serialVersionUID = 1L;
private final int maxSize;
public FixedSizeLruLinkedTreeMap(int initialCapacity, float loadFactor,
int maxSize) {
super(initialCapacity, loadFactor, true);
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<KK, VV> eldest) {
return super.size() > maxSize;
}
}
final long expiresInSecs;
private final CacheLoader<K, V> cacheLoader; | private final Map<K, Pair<Long, V>> map; |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/cache/CachedMap.java | // Path: src/main/java/com/plexobject/rbac/domain/Pair.java
// public class Pair<FIRST, SECOND> implements java.io.Serializable {
// private static final long serialVersionUID = 1L;
// public FIRST first;
// public SECOND second;
//
// public Pair(FIRST first, SECOND second) {
// this.first = first;
// this.second = second;
// }
//
// public FIRST getFirst() {
// return first;
// }
//
// public void setFirst(FIRST first) {
// this.first = first;
// }
//
// public SECOND getSecond() {
// return second;
// }
//
// public void setSecond(SECOND second) {
// this.second = second;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Pair)) {
// return false;
// }
// Pair<FIRST, SECOND> rhs = (Pair<FIRST, SECOND>) object;
//
// EqualsBuilder eqBuilder = new EqualsBuilder();
// eqBuilder.append(first, rhs.first);
// eqBuilder.append(second, rhs.second);
//
// return eqBuilder.isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(first).append(
// second).toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(first).append(second)
// .toString();
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/TimeUtils.java
// public class TimeUtils {
// public interface TimeSource {
// Date getCurrentTime();
// }
//
// private static TimeSource TIME_SOURCE = new TimeSource() {
// @Override
// public Date getCurrentTime() {
// return new Date();
// }
// };
//
// public static Date getCurrentTime() {
// return TIME_SOURCE.getCurrentTime();
// }
//
// public static long getCurrentTimeMillis() {
// return getCurrentTime().getTime();
// }
//
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.log4j.Logger;
import com.plexobject.rbac.domain.Pair;
import com.plexobject.rbac.utils.TimeUtils; | }
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
for (Map.Entry<K, V> e : entrySet()) {
if (value == e.getValue()
|| (value != null && value.equals(e.getValue()))) {
return true;
}
}
return false;
}
@Override
public V put(K key, V value) { | // Path: src/main/java/com/plexobject/rbac/domain/Pair.java
// public class Pair<FIRST, SECOND> implements java.io.Serializable {
// private static final long serialVersionUID = 1L;
// public FIRST first;
// public SECOND second;
//
// public Pair(FIRST first, SECOND second) {
// this.first = first;
// this.second = second;
// }
//
// public FIRST getFirst() {
// return first;
// }
//
// public void setFirst(FIRST first) {
// this.first = first;
// }
//
// public SECOND getSecond() {
// return second;
// }
//
// public void setSecond(SECOND second) {
// this.second = second;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @SuppressWarnings("unchecked")
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Pair)) {
// return false;
// }
// Pair<FIRST, SECOND> rhs = (Pair<FIRST, SECOND>) object;
//
// EqualsBuilder eqBuilder = new EqualsBuilder();
// eqBuilder.append(first, rhs.first);
// eqBuilder.append(second, rhs.second);
//
// return eqBuilder.isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(first).append(
// second).toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(first).append(second)
// .toString();
// }
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/TimeUtils.java
// public class TimeUtils {
// public interface TimeSource {
// Date getCurrentTime();
// }
//
// private static TimeSource TIME_SOURCE = new TimeSource() {
// @Override
// public Date getCurrentTime() {
// return new Date();
// }
// };
//
// public static Date getCurrentTime() {
// return TIME_SOURCE.getCurrentTime();
// }
//
// public static long getCurrentTimeMillis() {
// return getCurrentTime().getTime();
// }
//
// }
// Path: src/main/java/com/plexobject/rbac/cache/CachedMap.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.log4j.Logger;
import com.plexobject.rbac.domain.Pair;
import com.plexobject.rbac.utils.TimeUtils;
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
for (Map.Entry<K, V> e : entrySet()) {
if (value == e.getValue()
|| (value != null && value.equals(e.getValue()))) {
return true;
}
}
return false;
}
@Override
public V put(K key, V value) { | Pair<Long, V> previous = map.put(key, new Pair<Long, V>(TimeUtils |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/service/PermissionsService.java | // Path: src/main/java/com/plexobject/rbac/domain/Permission.java
// @Entity
// @XmlRootElement
// public class Permission extends PersistentObject implements Validatable,
// Identifiable<Integer> {
//
// @PrimaryKey(sequence = "permission_seq")
// private Integer id;
//
// @SecondaryKey(relate = Relationship.MANY_TO_ONE)
// private String operation; // can be string or regular expression
// @SecondaryKey(relate = Relationship.MANY_TO_ONE)
// private String target;
// private String expression;
//
// @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Role.class, onRelatedEntityDelete = DeleteAction.NULLIFY)
// Set<String> roleIds = new HashSet<String>();
//
// // for JPA
// Permission() {
// }
//
// public Permission(final String operation, final String target,
// final String expression) {
// setOperation(operation);
// setTarget(target);
// setExpression(expression);
// }
//
// void setId(Integer id) {
// this.id = id;
// }
//
// @XmlElement
// public Integer getId() {
// return id;
// }
//
// /**
// * The operation is action like read/write/update/delete or regular
// * expression
// *
// * @return
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * This method matches operation by equality or regular expression
// *
// * @param action
// * @return
// */
// public boolean implies(final String op, final String tgt) {
// if (GenericValidator.isBlankOrNull(op)) {
// return false;
// }
// if (GenericValidator.isBlankOrNull(tgt)) {
// return false;
// }
//
// return (operation.equalsIgnoreCase(op) || op.toLowerCase().matches(
// operation))
// && (target.equalsIgnoreCase(tgt) || tgt.toLowerCase().matches(
// target));
// }
//
// /**
// * The target is object that is being acted upon such as file, row in the
// * database
// *
// * @return
// */
// public String getTarget() {
// return target;
// }
//
// public void setOperation(String operation) {
// if (GenericValidator.isBlankOrNull(operation)) {
// throw new IllegalArgumentException("operation not specified");
// }
// if (operation.equals("*")) {
// operation = ".*";
// }
// firePropertyChange("operation", this.operation, operation);
//
// this.operation = operation.toLowerCase();
// }
//
// public void setTarget(String target) {
// if (GenericValidator.isBlankOrNull(target)) {
// throw new IllegalArgumentException("target not specified");
// }
// firePropertyChange("target", this.target, target);
//
// this.target = target;
// }
//
// /**
// *
// * @return
// */
// public String getExpression() {
// return expression;
// }
//
// public void setExpression(final String expression) {
// firePropertyChange("expression", this.expression, expression);
//
// this.expression = expression;
// }
//
// @XmlTransient
// public Set<String> getRoleIds() {
// return new HashSet<String>(roleIds);
// }
//
// public void setRoleIds(Set<String> roleIds) {
// firePropertyChange("roleIds", this.roleIds, roleIds);
//
// this.roleIds.clear();
// this.roleIds.addAll(roleIds);
// }
//
// public void addRole(Role role) {
// Set<String> old = getRoleIds();
// this.roleIds.add(role.getId());
// firePropertyChange("roleIds", old, this.roleIds);
// }
//
// public void removeRole(Role role) {
// Set<String> old = getRoleIds();
// this.roleIds.remove(role.getId());
// firePropertyChange("roleIds", old, this.roleIds);
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Permission)) {
// return false;
// }
// Permission rhs = (Permission) object;
// return new EqualsBuilder().append(this.operation, rhs.operation)
// .append(this.target, rhs.target).append(this.expression,
// rhs.expression).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713)
// .append(this.operation).append(this.target).toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("id", this.id).append(
// "operation", this.operation).append("target", target).append(
// "expression", this.expression).append("roleIds", this.roleIds)
// .toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(operation)) {
// errorsByField.put("operation", "operation is not specified");
// }
// if (GenericValidator.isBlankOrNull(target)) {
// errorsByField.put("target", "target is not specified");
// }
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
// }
| import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Permission; | package com.plexobject.rbac.service;
public interface PermissionsService {
/**
*
* @param domain
* @param id
* @return
*/
Response get(String domain, Integer id);
/**
*
* @param domain
* @param lastKey
* @param limit
* @return
*/
Response index(String domain, Integer lastKey, int limit);
/**
*
* @param domain
* @param permission
* @return
*/ | // Path: src/main/java/com/plexobject/rbac/domain/Permission.java
// @Entity
// @XmlRootElement
// public class Permission extends PersistentObject implements Validatable,
// Identifiable<Integer> {
//
// @PrimaryKey(sequence = "permission_seq")
// private Integer id;
//
// @SecondaryKey(relate = Relationship.MANY_TO_ONE)
// private String operation; // can be string or regular expression
// @SecondaryKey(relate = Relationship.MANY_TO_ONE)
// private String target;
// private String expression;
//
// @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Role.class, onRelatedEntityDelete = DeleteAction.NULLIFY)
// Set<String> roleIds = new HashSet<String>();
//
// // for JPA
// Permission() {
// }
//
// public Permission(final String operation, final String target,
// final String expression) {
// setOperation(operation);
// setTarget(target);
// setExpression(expression);
// }
//
// void setId(Integer id) {
// this.id = id;
// }
//
// @XmlElement
// public Integer getId() {
// return id;
// }
//
// /**
// * The operation is action like read/write/update/delete or regular
// * expression
// *
// * @return
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * This method matches operation by equality or regular expression
// *
// * @param action
// * @return
// */
// public boolean implies(final String op, final String tgt) {
// if (GenericValidator.isBlankOrNull(op)) {
// return false;
// }
// if (GenericValidator.isBlankOrNull(tgt)) {
// return false;
// }
//
// return (operation.equalsIgnoreCase(op) || op.toLowerCase().matches(
// operation))
// && (target.equalsIgnoreCase(tgt) || tgt.toLowerCase().matches(
// target));
// }
//
// /**
// * The target is object that is being acted upon such as file, row in the
// * database
// *
// * @return
// */
// public String getTarget() {
// return target;
// }
//
// public void setOperation(String operation) {
// if (GenericValidator.isBlankOrNull(operation)) {
// throw new IllegalArgumentException("operation not specified");
// }
// if (operation.equals("*")) {
// operation = ".*";
// }
// firePropertyChange("operation", this.operation, operation);
//
// this.operation = operation.toLowerCase();
// }
//
// public void setTarget(String target) {
// if (GenericValidator.isBlankOrNull(target)) {
// throw new IllegalArgumentException("target not specified");
// }
// firePropertyChange("target", this.target, target);
//
// this.target = target;
// }
//
// /**
// *
// * @return
// */
// public String getExpression() {
// return expression;
// }
//
// public void setExpression(final String expression) {
// firePropertyChange("expression", this.expression, expression);
//
// this.expression = expression;
// }
//
// @XmlTransient
// public Set<String> getRoleIds() {
// return new HashSet<String>(roleIds);
// }
//
// public void setRoleIds(Set<String> roleIds) {
// firePropertyChange("roleIds", this.roleIds, roleIds);
//
// this.roleIds.clear();
// this.roleIds.addAll(roleIds);
// }
//
// public void addRole(Role role) {
// Set<String> old = getRoleIds();
// this.roleIds.add(role.getId());
// firePropertyChange("roleIds", old, this.roleIds);
// }
//
// public void removeRole(Role role) {
// Set<String> old = getRoleIds();
// this.roleIds.remove(role.getId());
// firePropertyChange("roleIds", old, this.roleIds);
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Permission)) {
// return false;
// }
// Permission rhs = (Permission) object;
// return new EqualsBuilder().append(this.operation, rhs.operation)
// .append(this.target, rhs.target).append(this.expression,
// rhs.expression).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713)
// .append(this.operation).append(this.target).toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("id", this.id).append(
// "operation", this.operation).append("target", target).append(
// "expression", this.expression).append("roleIds", this.roleIds)
// .toString();
// }
//
// @Override
// public void validate() throws ValidationException {
// final Map<String, String> errorsByField = new HashMap<String, String>();
// if (GenericValidator.isBlankOrNull(operation)) {
// errorsByField.put("operation", "operation is not specified");
// }
// if (GenericValidator.isBlankOrNull(target)) {
// errorsByField.put("target", "target is not specified");
// }
// if (errorsByField.size() > 0) {
// throw new ValidationException(errorsByField);
// }
// }
// }
// Path: src/main/java/com/plexobject/rbac/service/PermissionsService.java
import javax.ws.rs.core.Response;
import com.plexobject.rbac.domain.Permission;
package com.plexobject.rbac.service;
public interface PermissionsService {
/**
*
* @param domain
* @param id
* @return
*/
Response get(String domain, Integer id);
/**
*
* @param domain
* @param lastKey
* @param limit
* @return
*/
Response index(String domain, Integer lastKey, int limit);
/**
*
* @param domain
* @param permission
* @return
*/ | Response post(String domain, Permission permission); |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/http/RestClient.java | // Path: src/main/java/com/plexobject/rbac/domain/Tuple.java
// public class Tuple {
// final Object[] objects;
//
// public Tuple(Object... objects) {
// if (null == objects) {
// throw new NullPointerException("no objects");
// }
//
// this.objects = objects;
// }
//
// public int size() {
// return objects.length;
// }
//
// @SuppressWarnings("unchecked")
// public <T> T get(int i) {
// return (T) objects[i];
// }
//
// @SuppressWarnings("unchecked")
// public <T> T first() {
// return (T) get(0);
// }
//
// @SuppressWarnings("unchecked")
// public <T> T second() {
// return (T) get(1);
// }
//
// @SuppressWarnings("unchecked")
// public <T> T third() {
// return (T) get(2);
// }
//
// @SuppressWarnings("unchecked")
// public <T> T last() {
// return (T) get(objects.length - 1);
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Tuple)) {
// return false;
// }
// Tuple rhs = (Tuple) object;
// if (objects.length != rhs.objects.length) {
// return false;
// }
// EqualsBuilder eqBuilder = new EqualsBuilder();
// for (int i = 0; i < objects.length; i++) {
// eqBuilder.append(objects[i], rhs.objects[i]);
// }
// return eqBuilder.isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// HashCodeBuilder hashBuilder = new HashCodeBuilder(786529047, 1924536713);
// for (int i = 0; i < objects.length; i++) {
// hashBuilder.append(objects[i]);
// }
// return hashBuilder.toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// ToStringBuilder strBuilder = new ToStringBuilder(this);
// for (int i = 0; i < objects.length; i++) {
// strBuilder.append(objects[i]);
// }
// return strBuilder.toString();
// }
// }
| import java.io.IOException;
import com.plexobject.rbac.domain.Tuple; | package com.plexobject.rbac.http;
public interface RestClient {
public static int OK = 200;
public static int OK_MIN = 200;
public static int OK_MAX = 299;
public static int OK_CREATED = 201;
public static int OK_ACCEPTED = 202;
public static int REDIRECT_PERMANENTLY = 301;
public static int REDIRECT_FOUND = 302;
public static int CLIENT_ERROR_BAD_REQUEST = 400;
public static int CLIENT_ERROR_UNAUTHORIZED = 401;
public static int CLIENT_ERROR_FORBIDDEN = 403;
public static int CLIENT_ERROR_NOT_FOUND = 404;
public static int CLIENT_ERROR_TIMEOUT = 408;
public static int CLIENT_ERROR_CONFLICT = 409;
public static int CLIENT_ERROR_PRECONDITION = 412;
public static int SERVER_INTERNAL_ERROR = 500;
public static int SERVICE_UNAVAILABLE = 503;
| // Path: src/main/java/com/plexobject/rbac/domain/Tuple.java
// public class Tuple {
// final Object[] objects;
//
// public Tuple(Object... objects) {
// if (null == objects) {
// throw new NullPointerException("no objects");
// }
//
// this.objects = objects;
// }
//
// public int size() {
// return objects.length;
// }
//
// @SuppressWarnings("unchecked")
// public <T> T get(int i) {
// return (T) objects[i];
// }
//
// @SuppressWarnings("unchecked")
// public <T> T first() {
// return (T) get(0);
// }
//
// @SuppressWarnings("unchecked")
// public <T> T second() {
// return (T) get(1);
// }
//
// @SuppressWarnings("unchecked")
// public <T> T third() {
// return (T) get(2);
// }
//
// @SuppressWarnings("unchecked")
// public <T> T last() {
// return (T) get(objects.length - 1);
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof Tuple)) {
// return false;
// }
// Tuple rhs = (Tuple) object;
// if (objects.length != rhs.objects.length) {
// return false;
// }
// EqualsBuilder eqBuilder = new EqualsBuilder();
// for (int i = 0; i < objects.length; i++) {
// eqBuilder.append(objects[i], rhs.objects[i]);
// }
// return eqBuilder.isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// HashCodeBuilder hashBuilder = new HashCodeBuilder(786529047, 1924536713);
// for (int i = 0; i < objects.length; i++) {
// hashBuilder.append(objects[i]);
// }
// return hashBuilder.toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// ToStringBuilder strBuilder = new ToStringBuilder(this);
// for (int i = 0; i < objects.length; i++) {
// strBuilder.append(objects[i]);
// }
// return strBuilder.toString();
// }
// }
// Path: src/main/java/com/plexobject/rbac/http/RestClient.java
import java.io.IOException;
import com.plexobject.rbac.domain.Tuple;
package com.plexobject.rbac.http;
public interface RestClient {
public static int OK = 200;
public static int OK_MIN = 200;
public static int OK_MAX = 299;
public static int OK_CREATED = 201;
public static int OK_ACCEPTED = 202;
public static int REDIRECT_PERMANENTLY = 301;
public static int REDIRECT_FOUND = 302;
public static int CLIENT_ERROR_BAD_REQUEST = 400;
public static int CLIENT_ERROR_UNAUTHORIZED = 401;
public static int CLIENT_ERROR_FORBIDDEN = 403;
public static int CLIENT_ERROR_NOT_FOUND = 404;
public static int CLIENT_ERROR_TIMEOUT = 408;
public static int CLIENT_ERROR_CONFLICT = 409;
public static int CLIENT_ERROR_PRECONDITION = 412;
public static int SERVER_INTERNAL_ERROR = 500;
public static int SERVICE_UNAVAILABLE = 503;
| Tuple get(final String path) throws IOException; |
bhatti/PlexRBAC | src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java | // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
| import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest; | @Override
public List<PathSegment> getPathSegments(boolean arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public MultivaluedMap<String, String> getQueryParameters() {
return new TestMultivaluedMap();
}
@Override
public MultivaluedMap<String, String> getQueryParameters(boolean arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public URI getRequestUri() {
// TODO Auto-generated method stub
return null;
}
@Override
public UriBuilder getRequestUriBuilder() {
// TODO Auto-generated method stub
return null;
}
};
| // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
// Path: src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest;
@Override
public List<PathSegment> getPathSegments(boolean arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public MultivaluedMap<String, String> getQueryParameters() {
return new TestMultivaluedMap();
}
@Override
public MultivaluedMap<String, String> getQueryParameters(boolean arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public URI getRequestUri() {
// TODO Auto-generated method stub
return null;
}
@Override
public UriBuilder getRequestUriBuilder() {
// TODO Auto-generated method stub
return null;
}
};
| AuthorizationService service; |
bhatti/PlexRBAC | src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java | // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
| import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest; |
@Override
public MultivaluedMap<String, String> getQueryParameters() {
return new TestMultivaluedMap();
}
@Override
public MultivaluedMap<String, String> getQueryParameters(boolean arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public URI getRequestUri() {
// TODO Auto-generated method stub
return null;
}
@Override
public UriBuilder getRequestUriBuilder() {
// TODO Auto-generated method stub
return null;
}
};
AuthorizationService service;
TestMultivaluedMap map;
@Before
public void setUp() throws Exception { | // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
// Path: src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest;
@Override
public MultivaluedMap<String, String> getQueryParameters() {
return new TestMultivaluedMap();
}
@Override
public MultivaluedMap<String, String> getQueryParameters(boolean arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public URI getRequestUri() {
// TODO Auto-generated method stub
return null;
}
@Override
public UriBuilder getRequestUriBuilder() {
// TODO Auto-generated method stub
return null;
}
};
AuthorizationService service;
TestMultivaluedMap map;
@Before
public void setUp() throws Exception { | CurrentRequest.startRequest(APP_NAME, USER_NAME, "127.0.0.1"); |
bhatti/PlexRBAC | src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java | // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
| import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest; | @Before
public void setUp() throws Exception {
CurrentRequest.startRequest(APP_NAME, USER_NAME, "127.0.0.1");
map = new TestMultivaluedMap();
service = new AuthorizationServiceImpl();
((AuthorizationServiceImpl) service)
.setPermissionManager(((AuthorizationServiceImpl) service)
.getPermissionManager());
}
@After
public void tearDown() throws Exception {
}
@Test
public final void testAuthorizeFailed() throws Exception {
((AuthorizationServiceImpl) service).afterPropertiesSet();
String domain = "default";
String operation = "op";
String target = "xx";
UriInfo ui = new TestUriInfo();
Response response = service.authorize(ui, domain, operation, target);
assertEquals(401, response.getStatus());
assertEquals("denied", response.getEntity());
}
@Test
public final void testAuthorize() throws Exception { | // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
// Path: src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest;
@Before
public void setUp() throws Exception {
CurrentRequest.startRequest(APP_NAME, USER_NAME, "127.0.0.1");
map = new TestMultivaluedMap();
service = new AuthorizationServiceImpl();
((AuthorizationServiceImpl) service)
.setPermissionManager(((AuthorizationServiceImpl) service)
.getPermissionManager());
}
@After
public void tearDown() throws Exception {
}
@Test
public final void testAuthorizeFailed() throws Exception {
((AuthorizationServiceImpl) service).afterPropertiesSet();
String domain = "default";
String operation = "op";
String target = "xx";
UriInfo ui = new TestUriInfo();
Response response = service.authorize(ui, domain, operation, target);
assertEquals(401, response.getStatus());
assertEquals("denied", response.getEntity());
}
@Test
public final void testAuthorize() throws Exception { | PermissionManager mgr = EasyMock.createMock(PermissionManager.class); |
bhatti/PlexRBAC | src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java | // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
| import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest; | ((AuthorizationServiceImpl) service)
.setPermissionManager(((AuthorizationServiceImpl) service)
.getPermissionManager());
}
@After
public void tearDown() throws Exception {
}
@Test
public final void testAuthorizeFailed() throws Exception {
((AuthorizationServiceImpl) service).afterPropertiesSet();
String domain = "default";
String operation = "op";
String target = "xx";
UriInfo ui = new TestUriInfo();
Response response = service.authorize(ui, domain, operation, target);
assertEquals(401, response.getStatus());
assertEquals("denied", response.getEntity());
}
@Test
public final void testAuthorize() throws Exception {
PermissionManager mgr = EasyMock.createMock(PermissionManager.class);
((AuthorizationServiceImpl) service).setPermissionManager(mgr);
String domain = "mydomain";
String operation = "myoperation";
String target = "mytarget";
UriInfo ui = new TestUriInfo(); | // Path: src/main/java/com/plexobject/rbac/security/PermissionManager.java
// public interface PermissionManager {
//
// void check(PermissionRequest request) throws SecurityException;
//
// }
//
// Path: src/main/java/com/plexobject/rbac/security/PermissionRequest.java
// public class PermissionRequest {
// private final String domain;
// private final String subjectName;
// private final String operation;
// private final String target;
// private final Map<String, Object> subjectContext = new TreeMap<String, Object>();
//
// public PermissionRequest(final String domain, final String subjectName,
// final String operation, final String target,
// final Map<String, Object> subjectContext) {
// this.domain = domain;
// this.subjectName = subjectName;
// this.operation = operation;
// this.target = target;
// if (subjectContext != null) {
// this.subjectContext.putAll(subjectContext);
// }
// }
//
// public String getDomain() {
// return domain;
// }
//
// /**
// * @return the subjectName
// */
// public String getSubjectName() {
// return subjectName;
// }
//
// /**
// * @return the operation
// */
// public String getOperation() {
// return operation;
// }
//
// /**
// * @return the target
// */
// public String getTarget() {
// return target;
// }
//
// /**
// * @return the subjectContext
// */
// public Map<String, Object> getSubjectContext() {
// return subjectContext;
// }
//
// /**
// * @see java.lang.Object#equals(Object)
// */
// @Override
// public boolean equals(Object object) {
// if (!(object instanceof PermissionRequest)) {
// return false;
// }
// PermissionRequest rhs = (PermissionRequest) object;
// return new EqualsBuilder().append(this.domain, domain).append(
// this.subjectName, rhs.subjectName).append(this.operation,
// rhs.operation).append(this.target, rhs.target).append(
// this.subjectContext, rhs.subjectContext).isEquals();
// }
//
// /**
// * @see java.lang.Object#hashCode()
// */
// @Override
// public int hashCode() {
// return new HashCodeBuilder(786529047, 1924536713).append(domain)
// .append(subjectName).append(operation).append(target)
// .toHashCode();
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append(domain).append(subjectName)
// .append(operation).append(target).append(subjectContext)
// .toString();
// }
//
// }
//
// Path: src/main/java/com/plexobject/rbac/service/AuthorizationService.java
// public interface AuthorizationService {
// Response authorize(final UriInfo ui, final String domain,
// final String operation, final String target);
// }
//
// Path: src/main/java/com/plexobject/rbac/utils/CurrentRequest.java
// public class CurrentRequest {
// private static final ThreadLocal<String> domain = new ThreadLocal<String>();
// private static final ThreadLocal<String> subjectName = new ThreadLocal<String>();
// private static final ThreadLocal<String> ipAddress = new ThreadLocal<String>();
//
// public static void startRequest(final String domain, final String subjectName,
// final String ipAddress) {
// CurrentRequest.domain.set(domain);
// CurrentRequest.subjectName.set(subjectName);
// CurrentRequest.ipAddress.set(ipAddress);
// }
//
// public static void setSubjectName(String subjectName) {
// CurrentRequest.subjectName.set(subjectName);
// }
//
// public static void endRequest() {
// CurrentRequest.domain.set(null);
// CurrentRequest.subjectName.set(null);
// CurrentRequest.ipAddress.set(null);
// }
//
// public static String getDomain() {
// return domain.get();
// }
//
// public static String getSubjectName() {
// return subjectName.get();
// }
//
// public static String getIPAddress() {
// return ipAddress.get();
// }
// }
// Path: src/test/java/com/plexobject/rbac/service/impl/AuthorizationServiceImplTest.java
import static org.junit.Assert.assertEquals;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.plexobject.rbac.security.PermissionManager;
import com.plexobject.rbac.security.PermissionRequest;
import com.plexobject.rbac.service.AuthorizationService;
import com.plexobject.rbac.utils.CurrentRequest;
((AuthorizationServiceImpl) service)
.setPermissionManager(((AuthorizationServiceImpl) service)
.getPermissionManager());
}
@After
public void tearDown() throws Exception {
}
@Test
public final void testAuthorizeFailed() throws Exception {
((AuthorizationServiceImpl) service).afterPropertiesSet();
String domain = "default";
String operation = "op";
String target = "xx";
UriInfo ui = new TestUriInfo();
Response response = service.authorize(ui, domain, operation, target);
assertEquals(401, response.getStatus());
assertEquals("denied", response.getEntity());
}
@Test
public final void testAuthorize() throws Exception {
PermissionManager mgr = EasyMock.createMock(PermissionManager.class);
((AuthorizationServiceImpl) service).setPermissionManager(mgr);
String domain = "mydomain";
String operation = "myoperation";
String target = "mytarget";
UriInfo ui = new TestUriInfo(); | PermissionRequest request = new PermissionRequest(domain, "shahbhat", |
timschlechter/swagger-for-elasticsearch | src/main/java/net/itimothy/elasticsearch/restapispec/OfficialRestApiSpecDataProvider.java | // Path: src/main/java/net/itimothy/elasticsearch/restapispec/model/RestApiSpecData.java
// public class RestApiSpecData extends HashMap<String, Api> {
// }
| import com.google.gson.Gson;
import net.itimothy.elasticsearch.restapispec.model.Api;
import net.itimothy.elasticsearch.restapispec.model.RestApiSpecData;
import org.apache.commons.io.IOUtils;
import org.elasticsearch.Version;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; | package net.itimothy.elasticsearch.restapispec;
public class OfficialRestApiSpecDataProvider {
// TODO: caching
public Map<String, Api> getData(Version version) {
final HashMap<String, Api> data = new HashMap<>();
try {
final Gson gson = new Gson();
final String path = String.format(
"rest-api-spec/%s.%s",
version.major,
version.minor
);
for (InputStream stream : getFiles(path)) {
final String json = IOUtils.toString(stream, "UTF-8");
try {
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
public Void run() { | // Path: src/main/java/net/itimothy/elasticsearch/restapispec/model/RestApiSpecData.java
// public class RestApiSpecData extends HashMap<String, Api> {
// }
// Path: src/main/java/net/itimothy/elasticsearch/restapispec/OfficialRestApiSpecDataProvider.java
import com.google.gson.Gson;
import net.itimothy.elasticsearch.restapispec.model.Api;
import net.itimothy.elasticsearch.restapispec.model.RestApiSpecData;
import org.apache.commons.io.IOUtils;
import org.elasticsearch.Version;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
package net.itimothy.elasticsearch.restapispec;
public class OfficialRestApiSpecDataProvider {
// TODO: caching
public Map<String, Api> getData(Version version) {
final HashMap<String, Api> data = new HashMap<>();
try {
final Gson gson = new Gson();
final String path = String.format(
"rest-api-spec/%s.%s",
version.major,
version.minor
);
for (InputStream stream : getFiles(path)) {
final String json = IOUtils.toString(stream, "UTF-8");
try {
AccessController.doPrivileged(
new PrivilegedAction<Void>() {
public Void run() { | RestApiSpecData restApiSpecData = gson.fromJson(json, RestApiSpecData.class); |
timschlechter/swagger-for-elasticsearch | src/main/java/net/itimothy/elasticsearch/routes/RoutesProvider.java | // Path: src/main/java/net/itimothy/util/CollectionUtil.java
// public class CollectionUtil {
//
// /**
// * Sorts the specified list according to the order induced by comparing the keys extracted by the given
// * {keyExtractor}
// *
// * @param items List of items to sort
// * @param keyExtractor The function which produces the value to compare
// */
// public static <T, K extends Comparable> void sort(List<T> items, final Function<T, K> keyExtractor) {
// if (items == null) {
// return;
// }
//
// java.util.Collections.sort(
// items,
// new Comparator<T>() {
// @Override
// public int compare(T o1, T o2) {
// K key1 = o1 != null ? keyExtractor.apply(o1) : null;
// K key2 = o2 != null ? keyExtractor.apply(o2) : null;
//
// if (key1 == key2) {
// return 0;
// }
//
// if (key1 == null) {
// return -1;
// }
//
// if (key2 == null) {
// return 1;
// }
//
// return key1.compareTo(key2);
// }
// }
// );
// }
// }
| import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.google.common.base.Function;
import net.itimothy.elasticsearch.routes.model.*;
import net.itimothy.util.CollectionUtil;
import net.itimothy.util.SimpleCache;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.Version;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import static java.util.Arrays.asList; | );
Collections.sort(allIndices);
return allIndices;
}
}
);
}
protected List<String> getAllAliases() {
return cache.getOrResolve("getAllAliases",
new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
List<String> allAliases = new ArrayList<String>();
ImmutableOpenMap<String, List<AliasMetaData>> indexAliasesMap = client.admin().indices()
.prepareGetAliases()
.get()
.getAliases();
for (ObjectCursor<List<AliasMetaData>> listObjectCursor : indexAliasesMap.values()) {
for (AliasMetaData aliasMetaData : listObjectCursor.value) {
if (!allAliases.contains(aliasMetaData.alias())) {
allAliases.add(aliasMetaData.alias());
}
}
}
| // Path: src/main/java/net/itimothy/util/CollectionUtil.java
// public class CollectionUtil {
//
// /**
// * Sorts the specified list according to the order induced by comparing the keys extracted by the given
// * {keyExtractor}
// *
// * @param items List of items to sort
// * @param keyExtractor The function which produces the value to compare
// */
// public static <T, K extends Comparable> void sort(List<T> items, final Function<T, K> keyExtractor) {
// if (items == null) {
// return;
// }
//
// java.util.Collections.sort(
// items,
// new Comparator<T>() {
// @Override
// public int compare(T o1, T o2) {
// K key1 = o1 != null ? keyExtractor.apply(o1) : null;
// K key2 = o2 != null ? keyExtractor.apply(o2) : null;
//
// if (key1 == key2) {
// return 0;
// }
//
// if (key1 == null) {
// return -1;
// }
//
// if (key2 == null) {
// return 1;
// }
//
// return key1.compareTo(key2);
// }
// }
// );
// }
// }
// Path: src/main/java/net/itimothy/elasticsearch/routes/RoutesProvider.java
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.google.common.base.Function;
import net.itimothy.elasticsearch.routes.model.*;
import net.itimothy.util.CollectionUtil;
import net.itimothy.util.SimpleCache;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.Version;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import static java.util.Arrays.asList;
);
Collections.sort(allIndices);
return allIndices;
}
}
);
}
protected List<String> getAllAliases() {
return cache.getOrResolve("getAllAliases",
new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
List<String> allAliases = new ArrayList<String>();
ImmutableOpenMap<String, List<AliasMetaData>> indexAliasesMap = client.admin().indices()
.prepareGetAliases()
.get()
.getAliases();
for (ObjectCursor<List<AliasMetaData>> listObjectCursor : indexAliasesMap.values()) {
for (AliasMetaData aliasMetaData : listObjectCursor.value) {
if (!allAliases.contains(aliasMetaData.alias())) {
allAliases.add(aliasMetaData.alias());
}
}
}
| CollectionUtil.sort(allAliases, new Function<String, Comparable>() { |
nVisium/MoneyX | src/main/java/com/nvisium/androidnv/api/repository/EventMembershipRepository.java | // Path: src/main/java/com/nvisium/androidnv/api/model/EventMembership.java
// @Entity
// @Table(name = "eventMemberships")
// public class EventMembership {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Version
// private Long version;
//
// @Column(name = "eventId")
// private Long eventId;
//
// @Column(name = "user")
// private Long user;
//
// @Column(name = "amount")
// private BigDecimal amount;
//
// @Column(name = "created")
// private java.util.Date created;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getEventId() {
// return eventId;
// }
//
// public void setEventId(Long eventId) {
// this.eventId = eventId;
// }
//
// public Long getUser() {
// return user;
// }
//
// public void setUser(Long user) {
// this.user = user;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public java.util.Date getCreated() {
// return created;
// }
//
// public void setCreated(java.util.Date created) {
// this.created = created;
// }
//
// public void populateEventMembership(Long eventId, Long user,
// BigDecimal amount, java.util.Date created) {
// this.eventId = eventId;
// this.user = user;
// this.amount = amount;
// this.created = created;
// }
// }
| import java.math.BigDecimal;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.nvisium.androidnv.api.model.EventMembership; | package com.nvisium.androidnv.api.repository;
@Repository
@Qualifier(value = "eventMembershipRepository")
public interface EventMembershipRepository extends | // Path: src/main/java/com/nvisium/androidnv/api/model/EventMembership.java
// @Entity
// @Table(name = "eventMemberships")
// public class EventMembership {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Version
// private Long version;
//
// @Column(name = "eventId")
// private Long eventId;
//
// @Column(name = "user")
// private Long user;
//
// @Column(name = "amount")
// private BigDecimal amount;
//
// @Column(name = "created")
// private java.util.Date created;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getEventId() {
// return eventId;
// }
//
// public void setEventId(Long eventId) {
// this.eventId = eventId;
// }
//
// public Long getUser() {
// return user;
// }
//
// public void setUser(Long user) {
// this.user = user;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public java.util.Date getCreated() {
// return created;
// }
//
// public void setCreated(java.util.Date created) {
// this.created = created;
// }
//
// public void populateEventMembership(Long eventId, Long user,
// BigDecimal amount, java.util.Date created) {
// this.eventId = eventId;
// this.user = user;
// this.amount = amount;
// this.created = created;
// }
// }
// Path: src/main/java/com/nvisium/androidnv/api/repository/EventMembershipRepository.java
import java.math.BigDecimal;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.nvisium.androidnv.api.model.EventMembership;
package com.nvisium.androidnv.api.repository;
@Repository
@Qualifier(value = "eventMembershipRepository")
public interface EventMembershipRepository extends | CrudRepository<EventMembership, Long> { |
nVisium/MoneyX | src/main/java/com/nvisium/androidnv/api/repository/EventRepository.java | // Path: src/main/java/com/nvisium/androidnv/api/model/Event.java
// @Entity
// @Table(name = "events")
// public class Event {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Version
// private Long version;
//
// // TODO: Actually associate this with a user, not just an id that we have to reference...see Payment Model.
// //@ManyToOne(targetEntity=User.class)
// //@JoinColumn(name = "owner")
// //private User owner;
// @Column(name = "owner")
// private Long owner;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "amount")
// private BigDecimal amount;
//
// @Column(name = "completed")
// private Boolean completed;
//
// @Column(name = "hidden")
// private Boolean hidden;
//
// @Column(name = "created")
// @Temporal(TemporalType.TIMESTAMP)
// private java.util.Date created;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getOwner() {
// return owner;
// }
//
// public void setOwner(Long owner) {
// this.owner = owner;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public Boolean getCompleted() {
// return completed;
// }
//
// public void setCompleted(Boolean completed) {
// this.completed = completed;
// }
//
// public Boolean getHidden() {
// return hidden;
// }
//
// public void setHidden(Boolean hidden) {
// this.hidden = hidden;
// }
//
// public java.util.Date getCreated() {
// return created;
// }
//
// public void setCreated(java.util.Date created) {
// this.created = created;
// }
//
// public void populateEvent(Long owner, String name, BigDecimal amount,
// java.util.Date created, Boolean hidden) {
// this.owner = owner;
// this.name = name;
// this.amount = amount;
// this.created = created;
// this.completed = false;
// this.hidden = hidden;
// }
// }
| import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.nvisium.androidnv.api.model.Event; | package com.nvisium.androidnv.api.repository;
@Repository
@Qualifier(value = "eventRepository") | // Path: src/main/java/com/nvisium/androidnv/api/model/Event.java
// @Entity
// @Table(name = "events")
// public class Event {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Version
// private Long version;
//
// // TODO: Actually associate this with a user, not just an id that we have to reference...see Payment Model.
// //@ManyToOne(targetEntity=User.class)
// //@JoinColumn(name = "owner")
// //private User owner;
// @Column(name = "owner")
// private Long owner;
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "amount")
// private BigDecimal amount;
//
// @Column(name = "completed")
// private Boolean completed;
//
// @Column(name = "hidden")
// private Boolean hidden;
//
// @Column(name = "created")
// @Temporal(TemporalType.TIMESTAMP)
// private java.util.Date created;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public Long getVersion() {
// return version;
// }
//
// public void setVersion(Long version) {
// this.version = version;
// }
//
// public Long getOwner() {
// return owner;
// }
//
// public void setOwner(Long owner) {
// this.owner = owner;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// public void setAmount(BigDecimal amount) {
// this.amount = amount;
// }
//
// public Boolean getCompleted() {
// return completed;
// }
//
// public void setCompleted(Boolean completed) {
// this.completed = completed;
// }
//
// public Boolean getHidden() {
// return hidden;
// }
//
// public void setHidden(Boolean hidden) {
// this.hidden = hidden;
// }
//
// public java.util.Date getCreated() {
// return created;
// }
//
// public void setCreated(java.util.Date created) {
// this.created = created;
// }
//
// public void populateEvent(Long owner, String name, BigDecimal amount,
// java.util.Date created, Boolean hidden) {
// this.owner = owner;
// this.name = name;
// this.amount = amount;
// this.created = created;
// this.completed = false;
// this.hidden = hidden;
// }
// }
// Path: src/main/java/com/nvisium/androidnv/api/repository/EventRepository.java
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.nvisium.androidnv.api.model.Event;
package com.nvisium.androidnv.api.repository;
@Repository
@Qualifier(value = "eventRepository") | public interface EventRepository extends CrudRepository<Event, Long> { |
nVisium/MoneyX | src/main/java/com/nvisium/androidnv/api/security/SecurityUtils.java | // Path: src/main/java/com/nvisium/androidnv/api/model/NvUserDetails.java
// public class NvUserDetails implements UserDetails {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private User user;
// List<GrantedAuthority> authorities;
//
// public NvUserDetails(User user, List<GrantedAuthority> authorities) {
// super();
// this.user = user;
// this.authorities = authorities;
// }
//
// public Collection<? extends GrantedAuthority> getAuthorities() {
// return authorities;
// }
//
// public String getPassword() {
// return user.getPassword();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
//
// public boolean isAccountNonExpired() {
// return user.isAccountNonExpired();
// }
//
// public boolean isAccountNonLocked() {
// return user.isAccountNonLocked();
// }
//
// public boolean isCredentialsNonExpired() {
// return user.isCredentialsNonExpired();
// }
//
// public boolean isEnabled() {
// return user.isEnabled();
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public static long getSerialversionuid() {
// return serialVersionUID;
// }
//
// public void setAuthorities(List<GrantedAuthority> authorities) {
// this.authorities = authorities;
// }
//
// }
| import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.nvisium.androidnv.api.model.NvUserDetails; | package com.nvisium.androidnv.api.security;
@Component
public class SecurityUtils {
| // Path: src/main/java/com/nvisium/androidnv/api/model/NvUserDetails.java
// public class NvUserDetails implements UserDetails {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private User user;
// List<GrantedAuthority> authorities;
//
// public NvUserDetails(User user, List<GrantedAuthority> authorities) {
// super();
// this.user = user;
// this.authorities = authorities;
// }
//
// public Collection<? extends GrantedAuthority> getAuthorities() {
// return authorities;
// }
//
// public String getPassword() {
// return user.getPassword();
// }
//
// public String getUsername() {
// return user.getUsername();
// }
//
// public boolean isAccountNonExpired() {
// return user.isAccountNonExpired();
// }
//
// public boolean isAccountNonLocked() {
// return user.isAccountNonLocked();
// }
//
// public boolean isCredentialsNonExpired() {
// return user.isCredentialsNonExpired();
// }
//
// public boolean isEnabled() {
// return user.isEnabled();
// }
//
// public User getUser() {
// return user;
// }
//
// public void setUser(User user) {
// this.user = user;
// }
//
// public static long getSerialversionuid() {
// return serialVersionUID;
// }
//
// public void setAuthorities(List<GrantedAuthority> authorities) {
// this.authorities = authorities;
// }
//
// }
// Path: src/main/java/com/nvisium/androidnv/api/security/SecurityUtils.java
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.nvisium.androidnv.api.model.NvUserDetails;
package com.nvisium.androidnv.api.security;
@Component
public class SecurityUtils {
| public NvUserDetails getSecurityContext() { |
nVisium/MoneyX | src/main/java/com/nvisium/androidnv/api/security/SecurityConfiguration.java | // Path: src/main/java/com/nvisium/androidnv/api/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// public UserDetails loadUserByUsername(String username);
//
// public User loadUserById(Long id);
//
// public User loadUser(String username);
//
// public void addRegularUser(String username, String password, String email,
// String answer, String firstname, String lastname);
//
// public boolean isAnswerValid(String username, String answer);
//
// public boolean validateCredentials(String username, String password);
//
// public void logout();
//
// public boolean validateCurrentPassword(String password);
//
// public void updatePasswordById(String password);
//
// public void updateAnswerById(String answer);
//
// public void updatePasswordByUsername(String username, String password);
//
// public void updateUser(String username, String firstname, String lastname, String email);
//
// public boolean doesUserExist(String username);
//
// public List<User> getPublicUsers();
//
// public void credit(Long id, BigDecimal amount);
//
// public boolean debit(Long id, BigDecimal amount);
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.web.savedrequest.NullRequestCache;
import com.nvisium.androidnv.api.service.UserService; | package com.nvisium.androidnv.api.security;
@Configuration
@EnableWebMvcSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired | // Path: src/main/java/com/nvisium/androidnv/api/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// public UserDetails loadUserByUsername(String username);
//
// public User loadUserById(Long id);
//
// public User loadUser(String username);
//
// public void addRegularUser(String username, String password, String email,
// String answer, String firstname, String lastname);
//
// public boolean isAnswerValid(String username, String answer);
//
// public boolean validateCredentials(String username, String password);
//
// public void logout();
//
// public boolean validateCurrentPassword(String password);
//
// public void updatePasswordById(String password);
//
// public void updateAnswerById(String answer);
//
// public void updatePasswordByUsername(String username, String password);
//
// public void updateUser(String username, String firstname, String lastname, String email);
//
// public boolean doesUserExist(String username);
//
// public List<User> getPublicUsers();
//
// public void credit(Long id, BigDecimal amount);
//
// public boolean debit(Long id, BigDecimal amount);
// }
// Path: src/main/java/com/nvisium/androidnv/api/security/SecurityConfiguration.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.web.savedrequest.NullRequestCache;
import com.nvisium.androidnv.api.service.UserService;
package com.nvisium.androidnv.api.security;
@Configuration
@EnableWebMvcSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired | UserService userService; |
nVisium/MoneyX | src/main/java/com/nvisium/androidnv/api/service/impl/AdminServiceImpl.java | // Path: src/main/java/com/nvisium/androidnv/api/service/AdminService.java
// public interface AdminService {
//
// }
| import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.nvisium.androidnv.api.service.AdminService; | package com.nvisium.androidnv.api.service.impl;
@Service
@Qualifier("adminService") | // Path: src/main/java/com/nvisium/androidnv/api/service/AdminService.java
// public interface AdminService {
//
// }
// Path: src/main/java/com/nvisium/androidnv/api/service/impl/AdminServiceImpl.java
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.nvisium.androidnv.api.service.AdminService;
package com.nvisium.androidnv.api.service.impl;
@Service
@Qualifier("adminService") | public class AdminServiceImpl implements AdminService { |
nVisium/MoneyX | src/main/java/com/nvisium/androidnv/api/security/MvcInitializer.java | // Path: src/main/java/com/nvisium/androidnv/api/MvcConfig.java
// @Configuration
// @EnableWebMvc
// public class MvcConfig extends WebMvcAutoConfigurationAdapter{
//
// @Bean
// ServletRegistrationBean h2servletRegistration(){
// ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
// registrationBean.addUrlMappings("/console/*");
// return registrationBean;
// }
//
// @Bean
// @Override
// public InternalResourceViewResolver defaultViewResolver() {
// InternalResourceViewResolver resolver = new InternalResourceViewResolver();
// resolver.setPrefix("/WEB-INF/views/");
// resolver.setSuffix(".jsp");
// return resolver;
// }
//
// @Bean
// public AuthenticationProvider daoAuthenticationProvider() {
// DaoAuthenticationProvider impl = new DaoAuthenticationProvider();
// impl.setUserDetailsService(new UserServiceImpl());
// impl.setHideUserNotFoundExceptions(false) ;
// return impl;
// }
//
// }
| import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.nvisium.androidnv.api.MvcConfig; | package com.nvisium.androidnv.api.security;
public class MvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SecurityConfiguration.class,
HttpSessionConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() { | // Path: src/main/java/com/nvisium/androidnv/api/MvcConfig.java
// @Configuration
// @EnableWebMvc
// public class MvcConfig extends WebMvcAutoConfigurationAdapter{
//
// @Bean
// ServletRegistrationBean h2servletRegistration(){
// ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
// registrationBean.addUrlMappings("/console/*");
// return registrationBean;
// }
//
// @Bean
// @Override
// public InternalResourceViewResolver defaultViewResolver() {
// InternalResourceViewResolver resolver = new InternalResourceViewResolver();
// resolver.setPrefix("/WEB-INF/views/");
// resolver.setSuffix(".jsp");
// return resolver;
// }
//
// @Bean
// public AuthenticationProvider daoAuthenticationProvider() {
// DaoAuthenticationProvider impl = new DaoAuthenticationProvider();
// impl.setUserDetailsService(new UserServiceImpl());
// impl.setHideUserNotFoundExceptions(false) ;
// return impl;
// }
//
// }
// Path: src/main/java/com/nvisium/androidnv/api/security/MvcInitializer.java
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.nvisium.androidnv.api.MvcConfig;
package com.nvisium.androidnv.api.security;
public class MvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SecurityConfiguration.class,
HttpSessionConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() { | return new Class[] { MvcConfig.class }; |
nVisium/MoneyX | src/main/java/com/nvisium/androidnv/api/MvcConfig.java | // Path: src/main/java/com/nvisium/androidnv/api/service/impl/UserServiceImpl.java
// @Service
// @Qualifier("userService")
// public class UserServiceImpl implements UserService {
//
// @Autowired
// private UserRepository accountRepository;
//
// @Autowired
// private SecurityUtils security;
//
// /*
// * Inserts a new user
// */
// public void addRegularUser(String username, String password, String email,
// String answer, String firstname, String lastname) {
// com.nvisium.androidnv.api.model.User user = new com.nvisium.androidnv.api.model.User();
// user.addAccountInfo(username, password, email, answer, firstname,
// lastname);
// accountRepository.save(user);
// }
//
// public boolean validateCredentials(String username, String password) {
// return (!(accountRepository.findByUsernameAndPassword(username,
// password) == null));
// }
//
// @Transactional
// public void logout() {
// // TODO: purge from redis...for now, who cares, tokens live forever!!
// // VULN
// }
//
// public boolean validateCurrentPassword(String password) {
// return (accountRepository.findUserByIdAndPassword(
// security.getCurrentUserId(), password) != null);
// }
//
// @Transactional
// public void updatePasswordById(String password) {
// accountRepository.updatePasswordById(password,
// security.getCurrentUserId());
// }
//
// public boolean doesUserExist(String username) {
// return accountRepository.findByUsername(username) != null;
// }
//
// @Transactional(readOnly = true)
// public UserDetails loadUserByUsername(String username) {
//
// com.nvisium.androidnv.api.model.User user = accountRepository
// .getUserModelByUsername(username);
// List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles());
// return new NvUserDetails(user, authorities);
// }
//
// private List<GrantedAuthority> buildUserAuthority(Set<Role> roles) {
//
// Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
//
// // Build user's authorities
// for (Role role : roles) {
// setAuths.add(new SimpleGrantedAuthority(role.getRoleName()));
// }
// return new ArrayList<GrantedAuthority>(setAuths);
// }
//
// @Transactional
// public User loadUserById(Long id) {
// return accountRepository.findById(id);
// }
//
// @Transactional
// public User loadUser(String username) {
// return accountRepository.getUserModelByUsername(username);
// }
//
// @Transactional
// public void updateUser(String username, String firstname, String lastname, String email) {
// accountRepository.updateUserProfile(username,firstname,lastname,email);
// }
//
// public List<User> getPublicUsers() {
// return accountRepository.getUsersByPrivacyDisabled();
// }
//
// public void credit(Long id, BigDecimal amount) {
//
// BigDecimal newAmount = loadUserById(id).getBalance().add(amount);
// accountRepository.updateBalance(id, newAmount);
// }
//
// public boolean debit(Long id, BigDecimal amount) {
// User u = accountRepository.findById(id);
// if (u.getBalance().compareTo(amount) != -1) {
// credit(id, amount.negate());
//
// return true;
// }
// return false;
// }
//
// public boolean isAnswerValid(String username, String answer) {
// if (accountRepository.getAnswerByUsername(username).equals(answer))
// return true;
// else
// return false;
// }
//
// @Transactional
// public void updatePasswordByUsername(String username, String password) {
// accountRepository.updatePasswordByUsername(username, password);
// }
//
// public void updateAnswerById(String answer) {
// accountRepository.updateAnswerById(answer, security.getCurrentUserId());
//
// }
// }
| import org.h2.server.web.WebServlet;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.nvisium.androidnv.api.service.impl.UserServiceImpl; | package com.nvisium.androidnv.api;
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcAutoConfigurationAdapter{
@Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
@Bean
@Override
public InternalResourceViewResolver defaultViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider impl = new DaoAuthenticationProvider(); | // Path: src/main/java/com/nvisium/androidnv/api/service/impl/UserServiceImpl.java
// @Service
// @Qualifier("userService")
// public class UserServiceImpl implements UserService {
//
// @Autowired
// private UserRepository accountRepository;
//
// @Autowired
// private SecurityUtils security;
//
// /*
// * Inserts a new user
// */
// public void addRegularUser(String username, String password, String email,
// String answer, String firstname, String lastname) {
// com.nvisium.androidnv.api.model.User user = new com.nvisium.androidnv.api.model.User();
// user.addAccountInfo(username, password, email, answer, firstname,
// lastname);
// accountRepository.save(user);
// }
//
// public boolean validateCredentials(String username, String password) {
// return (!(accountRepository.findByUsernameAndPassword(username,
// password) == null));
// }
//
// @Transactional
// public void logout() {
// // TODO: purge from redis...for now, who cares, tokens live forever!!
// // VULN
// }
//
// public boolean validateCurrentPassword(String password) {
// return (accountRepository.findUserByIdAndPassword(
// security.getCurrentUserId(), password) != null);
// }
//
// @Transactional
// public void updatePasswordById(String password) {
// accountRepository.updatePasswordById(password,
// security.getCurrentUserId());
// }
//
// public boolean doesUserExist(String username) {
// return accountRepository.findByUsername(username) != null;
// }
//
// @Transactional(readOnly = true)
// public UserDetails loadUserByUsername(String username) {
//
// com.nvisium.androidnv.api.model.User user = accountRepository
// .getUserModelByUsername(username);
// List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles());
// return new NvUserDetails(user, authorities);
// }
//
// private List<GrantedAuthority> buildUserAuthority(Set<Role> roles) {
//
// Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
//
// // Build user's authorities
// for (Role role : roles) {
// setAuths.add(new SimpleGrantedAuthority(role.getRoleName()));
// }
// return new ArrayList<GrantedAuthority>(setAuths);
// }
//
// @Transactional
// public User loadUserById(Long id) {
// return accountRepository.findById(id);
// }
//
// @Transactional
// public User loadUser(String username) {
// return accountRepository.getUserModelByUsername(username);
// }
//
// @Transactional
// public void updateUser(String username, String firstname, String lastname, String email) {
// accountRepository.updateUserProfile(username,firstname,lastname,email);
// }
//
// public List<User> getPublicUsers() {
// return accountRepository.getUsersByPrivacyDisabled();
// }
//
// public void credit(Long id, BigDecimal amount) {
//
// BigDecimal newAmount = loadUserById(id).getBalance().add(amount);
// accountRepository.updateBalance(id, newAmount);
// }
//
// public boolean debit(Long id, BigDecimal amount) {
// User u = accountRepository.findById(id);
// if (u.getBalance().compareTo(amount) != -1) {
// credit(id, amount.negate());
//
// return true;
// }
// return false;
// }
//
// public boolean isAnswerValid(String username, String answer) {
// if (accountRepository.getAnswerByUsername(username).equals(answer))
// return true;
// else
// return false;
// }
//
// @Transactional
// public void updatePasswordByUsername(String username, String password) {
// accountRepository.updatePasswordByUsername(username, password);
// }
//
// public void updateAnswerById(String answer) {
// accountRepository.updateAnswerById(answer, security.getCurrentUserId());
//
// }
// }
// Path: src/main/java/com/nvisium/androidnv/api/MvcConfig.java
import org.h2.server.web.WebServlet;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.nvisium.androidnv.api.service.impl.UserServiceImpl;
package com.nvisium.androidnv.api;
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcAutoConfigurationAdapter{
@Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
@Bean
@Override
public InternalResourceViewResolver defaultViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider impl = new DaoAuthenticationProvider(); | impl.setUserDetailsService(new UserServiceImpl()); |
mosscode/ach | src/main/java/com/moss/ach/file/TraceNumber.java | // Path: src/main/java/com/moss/ach/file/format/FieldUtil.java
// public class FieldUtil {
//
// public static String getName(Field<?> field) {
//
// String[] parts = field.getClass().getName().split("\\.");
// String className = parts[parts.length - 1];
// String name = className.substring(0, 1).toLowerCase() + className.substring(1);
//
// if (name.endsWith("Field")) {
// name = name.substring(0, name.length() - "Field".length());
// }
//
// return name;
// }
//
// public static String leftPad(String s, char c, int length) {
//
// int count = length - s.length();
//
// if (count < 1) {
// return s;
// }
//
// StringBuilder sb = new StringBuilder();
//
// for (int i=0; i<count; i++) {
// sb.append(c);
// }
//
// sb.append(s);
//
// return sb.toString();
// }
//
// public static String rightPad(String s, char c, int length) {
//
// int count = length - s.length();
//
// if (count < 1) {
// return s;
// }
//
// StringBuilder sb = new StringBuilder();
//
// sb.append(s);
//
// for (int i=0; i<count; i++) {
// sb.append(c);
// }
//
// return sb.toString();
// }
//
// public static String leftStrip(String s, char c) {
//
// int count = 0;
//
// for (int i=0; i<s.length(); i++) {
// if (s.charAt(i) != c) {
// break;
// }
// count++;
// }
//
// return s.substring(count);
// }
// }
| import com.moss.usbanknumbers.RoutingNumber;
import com.moss.usbanknumbers.RoutingNumberException;
import com.moss.ach.file.format.FieldUtil; | /**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of ach.
*
* ach is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* ach is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ach; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package com.moss.ach.file;
/**
* A trace number, assigned by the ODFI in ascending sequence, is included
* in each Entry Detail Record, Corporate Entry Detail Record, and
* Addenda Record. Trace Numbers uniquely identify each entry within a
* batch in an ACH input file. In association with the Batch Number,
* Transmission (File Creation) Date, and File ID Modifier, the Trace
* Number uniquely identifies an entry within a given file. For addenda
* Records, the Trace Number will be identical to the Trace Number in the
* associated Entry Detail Record, since the Trace Number is associated
* with an entry or item rather than a physical record.
*
* (..more on page OR 81..)
*/
public class TraceNumber {
private final RoutingNumber routingNumber;
private final long sequenceNumber;
public TraceNumber(RoutingNumber routingNumber, long sequenceNumber) throws TraceNumberException {
if (routingNumber == null) {
throw new NullPointerException();
}
if (sequenceNumber < 0) {
throw new TraceNumberException("The entry detail sequence number must be a number greater than or equal to zero");
}
String value = Long.toString(sequenceNumber);
if (value.length() > 7) {
throw new TraceNumberException("The entry detail sequence number must be less than or equal to seven digits.");
}
this.sequenceNumber = sequenceNumber;
this.routingNumber = routingNumber;
}
public TraceNumber(String value) throws TraceNumberException {
RoutingNumber routingNumber;
try {
routingNumber = RoutingNumber.fromNoChecksum(value.substring(0, 8));
}
catch (RoutingNumberException ex) {
throw new TraceNumberException(ex.getMessage());
}
String sequenceNumberString = value.substring(8); | // Path: src/main/java/com/moss/ach/file/format/FieldUtil.java
// public class FieldUtil {
//
// public static String getName(Field<?> field) {
//
// String[] parts = field.getClass().getName().split("\\.");
// String className = parts[parts.length - 1];
// String name = className.substring(0, 1).toLowerCase() + className.substring(1);
//
// if (name.endsWith("Field")) {
// name = name.substring(0, name.length() - "Field".length());
// }
//
// return name;
// }
//
// public static String leftPad(String s, char c, int length) {
//
// int count = length - s.length();
//
// if (count < 1) {
// return s;
// }
//
// StringBuilder sb = new StringBuilder();
//
// for (int i=0; i<count; i++) {
// sb.append(c);
// }
//
// sb.append(s);
//
// return sb.toString();
// }
//
// public static String rightPad(String s, char c, int length) {
//
// int count = length - s.length();
//
// if (count < 1) {
// return s;
// }
//
// StringBuilder sb = new StringBuilder();
//
// sb.append(s);
//
// for (int i=0; i<count; i++) {
// sb.append(c);
// }
//
// return sb.toString();
// }
//
// public static String leftStrip(String s, char c) {
//
// int count = 0;
//
// for (int i=0; i<s.length(); i++) {
// if (s.charAt(i) != c) {
// break;
// }
// count++;
// }
//
// return s.substring(count);
// }
// }
// Path: src/main/java/com/moss/ach/file/TraceNumber.java
import com.moss.usbanknumbers.RoutingNumber;
import com.moss.usbanknumbers.RoutingNumberException;
import com.moss.ach.file.format.FieldUtil;
/**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of ach.
*
* ach is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* ach is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ach; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package com.moss.ach.file;
/**
* A trace number, assigned by the ODFI in ascending sequence, is included
* in each Entry Detail Record, Corporate Entry Detail Record, and
* Addenda Record. Trace Numbers uniquely identify each entry within a
* batch in an ACH input file. In association with the Batch Number,
* Transmission (File Creation) Date, and File ID Modifier, the Trace
* Number uniquely identifies an entry within a given file. For addenda
* Records, the Trace Number will be identical to the Trace Number in the
* associated Entry Detail Record, since the Trace Number is associated
* with an entry or item rather than a physical record.
*
* (..more on page OR 81..)
*/
public class TraceNumber {
private final RoutingNumber routingNumber;
private final long sequenceNumber;
public TraceNumber(RoutingNumber routingNumber, long sequenceNumber) throws TraceNumberException {
if (routingNumber == null) {
throw new NullPointerException();
}
if (sequenceNumber < 0) {
throw new TraceNumberException("The entry detail sequence number must be a number greater than or equal to zero");
}
String value = Long.toString(sequenceNumber);
if (value.length() > 7) {
throw new TraceNumberException("The entry detail sequence number must be less than or equal to seven digits.");
}
this.sequenceNumber = sequenceNumber;
this.routingNumber = routingNumber;
}
public TraceNumber(String value) throws TraceNumberException {
RoutingNumber routingNumber;
try {
routingNumber = RoutingNumber.fromNoChecksum(value.substring(0, 8));
}
catch (RoutingNumberException ex) {
throw new TraceNumberException(ex.getMessage());
}
String sequenceNumberString = value.substring(8); | sequenceNumberString = FieldUtil.leftStrip(sequenceNumberString, '0'); |
mosscode/ach | src/main/java/com/moss/ach/file/format/FileCreationTimeField.java | // Path: src/main/java/com/moss/ach/file/SimpleDateException.java
// @SuppressWarnings("serial")
// public class SimpleDateException extends Exception {
//
// public SimpleDateException(String msg) {
// super(msg);
// }
// }
//
// Path: src/main/java/com/moss/ach/file/SimpleTime.java
// public class SimpleTime {
//
// int hours;
// int minutes;
//
// public SimpleTime(int hours, int minutes) throws SimpleTimeException {
//
// if (hours < 0 || hours > 23) {
// throw new SimpleTimeException("The hours value is invalid");
// }
//
// if (minutes < 0 || minutes > 59) {
// throw new SimpleTimeException("The minutes value is invalid");
// }
//
// this.hours = hours;
// this.minutes = minutes;
// }
//
// public int getHours() {
// return hours;
// }
//
// public int getMinutes() {
// return minutes;
// }
//
// public boolean equals(Object o) {
// return
// o != null
// &&
// o instanceof SimpleTime
// &&
// ((SimpleTime)o).hours == hours
// &&
// ((SimpleTime)o).minutes == minutes;
// }
// }
//
// Path: src/main/java/com/moss/ach/file/SimpleTimeException.java
// @SuppressWarnings("serial")
// public class SimpleTimeException extends Exception {
//
// public SimpleTimeException(String msg) {
// super(msg);
// }
// }
| import com.moss.ach.file.SimpleTime;
import com.moss.ach.file.SimpleTimeException;
import com.moss.ach.file.SimpleDateException; | /**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of ach.
*
* ach is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* ach is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ach; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package com.moss.ach.file.format;
class FileCreationTimeField implements Field<SimpleTime> {
public String getFormat() {
return null;
}
public int getLength() {
return 4;
}
public RequirementType getRequirementType() {
return RequirementType.OPTIONAL;
}
public SimpleTime parse(char[] value) throws InvalidFormatException {
String stringValue = new String(value);
try {
int hours = Integer.parseInt(stringValue.substring(0, 2));
int minutes = Integer.parseInt(stringValue.substring(2, 4));
return new SimpleTime(hours, minutes);
}
catch (NumberFormatException ex) {
throw new InvalidFormatException(ex.getMessage());
} | // Path: src/main/java/com/moss/ach/file/SimpleDateException.java
// @SuppressWarnings("serial")
// public class SimpleDateException extends Exception {
//
// public SimpleDateException(String msg) {
// super(msg);
// }
// }
//
// Path: src/main/java/com/moss/ach/file/SimpleTime.java
// public class SimpleTime {
//
// int hours;
// int minutes;
//
// public SimpleTime(int hours, int minutes) throws SimpleTimeException {
//
// if (hours < 0 || hours > 23) {
// throw new SimpleTimeException("The hours value is invalid");
// }
//
// if (minutes < 0 || minutes > 59) {
// throw new SimpleTimeException("The minutes value is invalid");
// }
//
// this.hours = hours;
// this.minutes = minutes;
// }
//
// public int getHours() {
// return hours;
// }
//
// public int getMinutes() {
// return minutes;
// }
//
// public boolean equals(Object o) {
// return
// o != null
// &&
// o instanceof SimpleTime
// &&
// ((SimpleTime)o).hours == hours
// &&
// ((SimpleTime)o).minutes == minutes;
// }
// }
//
// Path: src/main/java/com/moss/ach/file/SimpleTimeException.java
// @SuppressWarnings("serial")
// public class SimpleTimeException extends Exception {
//
// public SimpleTimeException(String msg) {
// super(msg);
// }
// }
// Path: src/main/java/com/moss/ach/file/format/FileCreationTimeField.java
import com.moss.ach.file.SimpleTime;
import com.moss.ach.file.SimpleTimeException;
import com.moss.ach.file.SimpleDateException;
/**
* Copyright (C) 2013, Moss Computing Inc.
*
* This file is part of ach.
*
* ach is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* ach is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ach; see the file COPYING. If not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this library, you may extend
* this exception to your version of the library, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
package com.moss.ach.file.format;
class FileCreationTimeField implements Field<SimpleTime> {
public String getFormat() {
return null;
}
public int getLength() {
return 4;
}
public RequirementType getRequirementType() {
return RequirementType.OPTIONAL;
}
public SimpleTime parse(char[] value) throws InvalidFormatException {
String stringValue = new String(value);
try {
int hours = Integer.parseInt(stringValue.substring(0, 2));
int minutes = Integer.parseInt(stringValue.substring(2, 4));
return new SimpleTime(hours, minutes);
}
catch (NumberFormatException ex) {
throw new InvalidFormatException(ex.getMessage());
} | catch (SimpleTimeException ex) { |
jeffsvajlenko/BigCloneEval | src/tasks/RegisterTool.java | // Path: src/database/Tools.java
// public class Tools {
//
// public static boolean exists(long id) throws SQLException {
// Tool tool = getTool(id);
// if(tool == null) {
// return false;
// } else {
// return true;
// }
// }
//
// public static void dropall() throws SQLException {
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// String sql = "DROP ALL OBJECTS";
// stmt.execute(sql);
// stmt.close();
// conn.close();
// }
//
// public static void init() throws SQLException {
// dropall();
// String sql = "CREATE TABLE tools ( name character varying NOT NULL, description character varying NOT NULL, id identity NOT NULL);";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// stmt.executeUpdate(sql);
// stmt.close();
// conn.close();
// }
//
// public static boolean deleteToolAndData(long id) throws SQLException {
//
// // Remove Tool
// String sql = "DELETE FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// int num = stmt.executeUpdate(sql);
// conn.close();
// if(num == 0) {
// return false;
// }
//
// // Remove Table
// sql = "DROP TABLE tool_" + id + "_clones";
// stmt.execute(sql);
// conn.close();
// return true;
// }
//
// public static List<Tool> getTools() throws SQLException {
// List<Tool> retval = new LinkedList<Tool>();
// String sql = "SELECT id, name, description FROM tools ORDER BY id";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// while(rs.next()) {
// retval.add(new Tool(rs.getLong(1), rs.getString(2), rs.getString(3)));
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static Tool getTool(long id) throws SQLException {
// Tool retval;
// String sql = "SELECT id, name, description FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// if(rs.next()) {
// retval = new Tool(rs.getLong(1), rs.getString(2), rs.getString(3));
// } else {
// retval = null;
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static long addTool(String name, String description) throws SQLException {
// // Add Tool
// String sql = "INSERT INTO tools (name, description) VALUES (?,?)";
// Connection conn = ToolsDB.getConnection();
// PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// stmt.setString(1, name);
// stmt.setString(2, description);
// stmt.executeUpdate();
// ResultSet rs = stmt.getGeneratedKeys();
// rs.next();
// long id = rs.getLong(1);
// rs.close();
// stmt.close();
//
// // Add Clones Table and its index
// Statement stmt2 = conn.createStatement();
// sql = "CREATE TABLE tool_" + id + "_clones (type1 character varying NOT NULL, name1 character varying NOT NULL, startline1 integer NOT NULL, endline1 integer NOT NULL, type2 character varying NOT NULL, name2 character varying NOT NULL, startline2 integer NOT NULL, endline2 integer NOT NULL);";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, startline1, endline1, type2, name2, startline2, endline2)";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, type2, name2)";
// stmt2.execute(sql);
// stmt2.close();
//
// conn.close();
// return id;
// }
//
// }
| import java.sql.SQLException;
import java.util.concurrent.Callable;
import database.Tools;
import picocli.CommandLine; | package tasks;
//import java.util.Scanner;
@CommandLine.Command(
name = "registerTool",
description = "Registers a clone detection tool with the framework. " +
"Requires a name and description of the tool, which is stored in the tools database. " +
"Returns a unique identifier for the tool for indicating the target tool for the other commands. " +
"Name and description are for reference by the user.",
mixinStandardHelpOptions = true,
versionProvider = util.Version.class)
public class RegisterTool implements Callable<Void> {
@CommandLine.Option(
names = {"-n", "--name"},
required = true,
description = "A name for the tool. Use quotes to allow spaces and special characters.",
paramLabel = "<string>"
)
private String name;
@CommandLine.Option(
names = {"-d", "--description"},
required = true,
description = "A description for the tool. Use quotes to allow spaces and special characters.",
paramLabel = "<string>"
)
private String description;
public static void main(String[] args) {
new CommandLine(new RegisterTool()).execute(args);
}
public Void call() {
try { | // Path: src/database/Tools.java
// public class Tools {
//
// public static boolean exists(long id) throws SQLException {
// Tool tool = getTool(id);
// if(tool == null) {
// return false;
// } else {
// return true;
// }
// }
//
// public static void dropall() throws SQLException {
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// String sql = "DROP ALL OBJECTS";
// stmt.execute(sql);
// stmt.close();
// conn.close();
// }
//
// public static void init() throws SQLException {
// dropall();
// String sql = "CREATE TABLE tools ( name character varying NOT NULL, description character varying NOT NULL, id identity NOT NULL);";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// stmt.executeUpdate(sql);
// stmt.close();
// conn.close();
// }
//
// public static boolean deleteToolAndData(long id) throws SQLException {
//
// // Remove Tool
// String sql = "DELETE FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// int num = stmt.executeUpdate(sql);
// conn.close();
// if(num == 0) {
// return false;
// }
//
// // Remove Table
// sql = "DROP TABLE tool_" + id + "_clones";
// stmt.execute(sql);
// conn.close();
// return true;
// }
//
// public static List<Tool> getTools() throws SQLException {
// List<Tool> retval = new LinkedList<Tool>();
// String sql = "SELECT id, name, description FROM tools ORDER BY id";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// while(rs.next()) {
// retval.add(new Tool(rs.getLong(1), rs.getString(2), rs.getString(3)));
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static Tool getTool(long id) throws SQLException {
// Tool retval;
// String sql = "SELECT id, name, description FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// if(rs.next()) {
// retval = new Tool(rs.getLong(1), rs.getString(2), rs.getString(3));
// } else {
// retval = null;
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static long addTool(String name, String description) throws SQLException {
// // Add Tool
// String sql = "INSERT INTO tools (name, description) VALUES (?,?)";
// Connection conn = ToolsDB.getConnection();
// PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// stmt.setString(1, name);
// stmt.setString(2, description);
// stmt.executeUpdate();
// ResultSet rs = stmt.getGeneratedKeys();
// rs.next();
// long id = rs.getLong(1);
// rs.close();
// stmt.close();
//
// // Add Clones Table and its index
// Statement stmt2 = conn.createStatement();
// sql = "CREATE TABLE tool_" + id + "_clones (type1 character varying NOT NULL, name1 character varying NOT NULL, startline1 integer NOT NULL, endline1 integer NOT NULL, type2 character varying NOT NULL, name2 character varying NOT NULL, startline2 integer NOT NULL, endline2 integer NOT NULL);";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, startline1, endline1, type2, name2, startline2, endline2)";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, type2, name2)";
// stmt2.execute(sql);
// stmt2.close();
//
// conn.close();
// return id;
// }
//
// }
// Path: src/tasks/RegisterTool.java
import java.sql.SQLException;
import java.util.concurrent.Callable;
import database.Tools;
import picocli.CommandLine;
package tasks;
//import java.util.Scanner;
@CommandLine.Command(
name = "registerTool",
description = "Registers a clone detection tool with the framework. " +
"Requires a name and description of the tool, which is stored in the tools database. " +
"Returns a unique identifier for the tool for indicating the target tool for the other commands. " +
"Name and description are for reference by the user.",
mixinStandardHelpOptions = true,
versionProvider = util.Version.class)
public class RegisterTool implements Callable<Void> {
@CommandLine.Option(
names = {"-n", "--name"},
required = true,
description = "A name for the tool. Use quotes to allow spaces and special characters.",
paramLabel = "<string>"
)
private String name;
@CommandLine.Option(
names = {"-d", "--description"},
required = true,
description = "A description for the tool. Use quotes to allow spaces and special characters.",
paramLabel = "<string>"
)
private String description;
public static void main(String[] args) {
new CommandLine(new RegisterTool()).execute(args);
}
public Void call() {
try { | long id = Tools.addTool(name, description); |
jeffsvajlenko/BigCloneEval | src/tasks/PartitionInput.java | // Path: src/util/FixPath.java
// public class FixPath {
//
// public static Path getAbsolutePath(Path path) {
// // User executed form commands/ directory, but working directory is ../ from there.
// // If specified a relative directory, need to base it correctly from user perspective.
// if(!path.isAbsolute()) {
// path = Paths.get("commands/").toAbsolutePath().resolve(path);
// }
// return path;
// }
//
// }
| import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
import picocli.CommandLine;
import util.FixPath;
| "your tool manually. This is automatically used with the detectClones command.",
mixinStandardHelpOptions = true,
versionProvider = util.Version.class)
public class PartitionInput implements Callable<Void> {
@CommandLine.Spec
private CommandLine.Model.CommandSpec spec;
@CommandLine.Option(
names = {"-i", "--input"},
description = "The directory of source code to partition.",
required = true,
paramLabel = "<PATH>"
)
private void setInput(Path input) {
if (!Files.exists(input))
throw new CommandLine.ParameterException(spec.commandLine(), "Input directory does not exist.");
if (!Files.isDirectory(input))
throw new CommandLine.ParameterException(spec.commandLine(), "Input must be a directory.");
this.input = input;
}
private Path input;
@CommandLine.Option(
names = {"-o", "--output"},
description = "The directory to write the subsets to (each pair of partitions).",
paramLabel = "<PATH>",
required = true
)
private void setOutput(Path output) {
| // Path: src/util/FixPath.java
// public class FixPath {
//
// public static Path getAbsolutePath(Path path) {
// // User executed form commands/ directory, but working directory is ../ from there.
// // If specified a relative directory, need to base it correctly from user perspective.
// if(!path.isAbsolute()) {
// path = Paths.get("commands/").toAbsolutePath().resolve(path);
// }
// return path;
// }
//
// }
// Path: src/tasks/PartitionInput.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
import picocli.CommandLine;
import util.FixPath;
"your tool manually. This is automatically used with the detectClones command.",
mixinStandardHelpOptions = true,
versionProvider = util.Version.class)
public class PartitionInput implements Callable<Void> {
@CommandLine.Spec
private CommandLine.Model.CommandSpec spec;
@CommandLine.Option(
names = {"-i", "--input"},
description = "The directory of source code to partition.",
required = true,
paramLabel = "<PATH>"
)
private void setInput(Path input) {
if (!Files.exists(input))
throw new CommandLine.ParameterException(spec.commandLine(), "Input directory does not exist.");
if (!Files.isDirectory(input))
throw new CommandLine.ParameterException(spec.commandLine(), "Input must be a directory.");
this.input = input;
}
private Path input;
@CommandLine.Option(
names = {"-o", "--output"},
description = "The directory to write the subsets to (each pair of partitions).",
paramLabel = "<PATH>",
required = true
)
private void setOutput(Path output) {
| output = FixPath.getAbsolutePath(output);
|
jeffsvajlenko/BigCloneEval | src/evaluate/ToolEvaluator.java | // Path: src/cloneMatchingAlgorithms/CloneMatcher.java
// public interface CloneMatcher {
// public boolean isDetected(Clone clone) throws SQLException;
// public void close() throws SQLException;
//
// public static String getTableName(long toolid) {
// return "tool_" + toolid + "_clones";
// }
//
// public static CloneMatcher load(long toolid, String clazz, String params) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// //long time = System.currentTimeMillis();
// Class<?> mClass = Class.forName("cloneMatchingAlgorithms." + clazz);
// Constructor<?> constructor = mClass.getConstructor(long.class, String.class);
// CloneMatcher matcher = (CloneMatcher) constructor.newInstance(toolid, params);
// //time = System.currentTimeMillis() - time;
// //System.out.println("TIME: " + time);
// return matcher;
// }
//
// }
//
// Path: src/database/Functionalities.java
// public class Functionalities {
// public static Set<Long> getFunctionalityIds() throws SQLException {
// String sql = "select id from functionalities";
// Set<Long> ids = new HashSet<Long>();
//
// Connection conn = BigCloneBenchDB.getConnection();
// Statement statement = conn.createStatement();
// ResultSet rs = statement.executeQuery(sql);
// while(rs.next()) ids.add(rs.getLong("id"));
// rs.close();
// statement.close();
// conn.close();
//
// return ids;
// }
//
// public static Functionality getFunctinality(long functionality_id) throws SQLException {
// Connection conn = BigCloneBenchDB.getConnection();
// Statement stmt = conn.createStatement();
//
// String sql = "SELECT id, name, description, search_heuristic FROM functionalities WHERE id = " + functionality_id;
// ResultSet rs = stmt.executeQuery(sql);
// rs.next();
// long id = rs.getLong(1);
// String name = rs.getString(2);
// String desc = rs.getString(3);
// String heuristic = rs.getString(4);
// rs.close();
// stmt.close();
// conn.close();
// return new Functionality(id, name, desc, heuristic);
// }
//
// }
| import java.io.Serializable;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import cloneMatchingAlgorithms.CloneMatcher;
import database.Functionalities; | str += " MaxSize: " + max_size;
str += "\n";
str += " MinPrettySize: " + min_pretty_size;
str += "\n";
str += " MaxPrettySize: " + max_pretty_size;
str += "\n";
str += " MinTokens: " + min_tokens;
str += "\n";
str += " MaxTokens: " + max_tokens;
str += "\n";
str += " MinJudges: " + min_judges;
str += "\n";
str += " MinConfidence: " + min_confidence;
str += "\n";
if(similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {
str += "SimilarityType: SIMILARITY_TYPE_AVG";
} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {
str += "SimilarityType: SIMILARITY_TYPE_BOTH";
} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {
str += "SimilarityType: SIMILARITY_TYPE_LINE";
} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {
str += "SimilarityType: SIMILARITY_TYPE_TOKEN";
}
str += "\n";
return str;
}
private static final long serialVersionUID = 1L;
private Long tool_id; | // Path: src/cloneMatchingAlgorithms/CloneMatcher.java
// public interface CloneMatcher {
// public boolean isDetected(Clone clone) throws SQLException;
// public void close() throws SQLException;
//
// public static String getTableName(long toolid) {
// return "tool_" + toolid + "_clones";
// }
//
// public static CloneMatcher load(long toolid, String clazz, String params) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// //long time = System.currentTimeMillis();
// Class<?> mClass = Class.forName("cloneMatchingAlgorithms." + clazz);
// Constructor<?> constructor = mClass.getConstructor(long.class, String.class);
// CloneMatcher matcher = (CloneMatcher) constructor.newInstance(toolid, params);
// //time = System.currentTimeMillis() - time;
// //System.out.println("TIME: " + time);
// return matcher;
// }
//
// }
//
// Path: src/database/Functionalities.java
// public class Functionalities {
// public static Set<Long> getFunctionalityIds() throws SQLException {
// String sql = "select id from functionalities";
// Set<Long> ids = new HashSet<Long>();
//
// Connection conn = BigCloneBenchDB.getConnection();
// Statement statement = conn.createStatement();
// ResultSet rs = statement.executeQuery(sql);
// while(rs.next()) ids.add(rs.getLong("id"));
// rs.close();
// statement.close();
// conn.close();
//
// return ids;
// }
//
// public static Functionality getFunctinality(long functionality_id) throws SQLException {
// Connection conn = BigCloneBenchDB.getConnection();
// Statement stmt = conn.createStatement();
//
// String sql = "SELECT id, name, description, search_heuristic FROM functionalities WHERE id = " + functionality_id;
// ResultSet rs = stmt.executeQuery(sql);
// rs.next();
// long id = rs.getLong(1);
// String name = rs.getString(2);
// String desc = rs.getString(3);
// String heuristic = rs.getString(4);
// rs.close();
// stmt.close();
// conn.close();
// return new Functionality(id, name, desc, heuristic);
// }
//
// }
// Path: src/evaluate/ToolEvaluator.java
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import cloneMatchingAlgorithms.CloneMatcher;
import database.Functionalities;
str += " MaxSize: " + max_size;
str += "\n";
str += " MinPrettySize: " + min_pretty_size;
str += "\n";
str += " MaxPrettySize: " + max_pretty_size;
str += "\n";
str += " MinTokens: " + min_tokens;
str += "\n";
str += " MaxTokens: " + max_tokens;
str += "\n";
str += " MinJudges: " + min_judges;
str += "\n";
str += " MinConfidence: " + min_confidence;
str += "\n";
if(similarity_type == ToolEvaluator.SIMILARITY_TYPE_AVG) {
str += "SimilarityType: SIMILARITY_TYPE_AVG";
} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_BOTH) {
str += "SimilarityType: SIMILARITY_TYPE_BOTH";
} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_LINE) {
str += "SimilarityType: SIMILARITY_TYPE_LINE";
} else if (similarity_type == ToolEvaluator.SIMILARITY_TYPE_TOKEN) {
str += "SimilarityType: SIMILARITY_TYPE_TOKEN";
}
str += "\n";
return str;
}
private static final long serialVersionUID = 1L;
private Long tool_id; | private CloneMatcher matcher; |
jeffsvajlenko/BigCloneEval | src/evaluate/ToolEvaluator.java | // Path: src/cloneMatchingAlgorithms/CloneMatcher.java
// public interface CloneMatcher {
// public boolean isDetected(Clone clone) throws SQLException;
// public void close() throws SQLException;
//
// public static String getTableName(long toolid) {
// return "tool_" + toolid + "_clones";
// }
//
// public static CloneMatcher load(long toolid, String clazz, String params) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// //long time = System.currentTimeMillis();
// Class<?> mClass = Class.forName("cloneMatchingAlgorithms." + clazz);
// Constructor<?> constructor = mClass.getConstructor(long.class, String.class);
// CloneMatcher matcher = (CloneMatcher) constructor.newInstance(toolid, params);
// //time = System.currentTimeMillis() - time;
// //System.out.println("TIME: " + time);
// return matcher;
// }
//
// }
//
// Path: src/database/Functionalities.java
// public class Functionalities {
// public static Set<Long> getFunctionalityIds() throws SQLException {
// String sql = "select id from functionalities";
// Set<Long> ids = new HashSet<Long>();
//
// Connection conn = BigCloneBenchDB.getConnection();
// Statement statement = conn.createStatement();
// ResultSet rs = statement.executeQuery(sql);
// while(rs.next()) ids.add(rs.getLong("id"));
// rs.close();
// statement.close();
// conn.close();
//
// return ids;
// }
//
// public static Functionality getFunctinality(long functionality_id) throws SQLException {
// Connection conn = BigCloneBenchDB.getConnection();
// Statement stmt = conn.createStatement();
//
// String sql = "SELECT id, name, description, search_heuristic FROM functionalities WHERE id = " + functionality_id;
// ResultSet rs = stmt.executeQuery(sql);
// rs.next();
// long id = rs.getLong(1);
// String name = rs.getString(2);
// String desc = rs.getString(3);
// String heuristic = rs.getString(4);
// rs.close();
// stmt.close();
// conn.close();
// return new Functionality(id, name, desc, heuristic);
// }
//
// }
| import java.io.Serializable;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import cloneMatchingAlgorithms.CloneMatcher;
import database.Functionalities; | numClones_type2c_intra = new HashMap<Long,Integer>();
numDetected_type2c_inter = new HashMap<Long,Integer>();
numDetected_type2c_intra = new HashMap<Long,Integer>();
numClones_type2b_inter = new HashMap<Long,Integer>();
numClones_type2b_intra = new HashMap<Long,Integer>();
numDetected_type2b_inter = new HashMap<Long,Integer>();
numDetected_type2b_intra = new HashMap<Long,Integer>();
numClones_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];
numClones_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];
numDetected_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];
numDetected_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];
numClones_false_inter = new HashMap<Long,Integer>();
numClones_false_intra = new HashMap<Long,Integer>();
numDetected_false_inter = new HashMap<Long,Integer>();
numDetected_false_intra = new HashMap<Long,Integer>();
for(int i = 0; i < 20; i++) {
numClones_type3_inter[i] = new HashMap<Long,Integer>();
numClones_type3_intra[i] = new HashMap<Long,Integer>();
numDetected_type3_inter[i] = new HashMap<Long,Integer>();
numDetected_type3_intra[i] = new HashMap<Long,Integer>();
}
| // Path: src/cloneMatchingAlgorithms/CloneMatcher.java
// public interface CloneMatcher {
// public boolean isDetected(Clone clone) throws SQLException;
// public void close() throws SQLException;
//
// public static String getTableName(long toolid) {
// return "tool_" + toolid + "_clones";
// }
//
// public static CloneMatcher load(long toolid, String clazz, String params) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// //long time = System.currentTimeMillis();
// Class<?> mClass = Class.forName("cloneMatchingAlgorithms." + clazz);
// Constructor<?> constructor = mClass.getConstructor(long.class, String.class);
// CloneMatcher matcher = (CloneMatcher) constructor.newInstance(toolid, params);
// //time = System.currentTimeMillis() - time;
// //System.out.println("TIME: " + time);
// return matcher;
// }
//
// }
//
// Path: src/database/Functionalities.java
// public class Functionalities {
// public static Set<Long> getFunctionalityIds() throws SQLException {
// String sql = "select id from functionalities";
// Set<Long> ids = new HashSet<Long>();
//
// Connection conn = BigCloneBenchDB.getConnection();
// Statement statement = conn.createStatement();
// ResultSet rs = statement.executeQuery(sql);
// while(rs.next()) ids.add(rs.getLong("id"));
// rs.close();
// statement.close();
// conn.close();
//
// return ids;
// }
//
// public static Functionality getFunctinality(long functionality_id) throws SQLException {
// Connection conn = BigCloneBenchDB.getConnection();
// Statement stmt = conn.createStatement();
//
// String sql = "SELECT id, name, description, search_heuristic FROM functionalities WHERE id = " + functionality_id;
// ResultSet rs = stmt.executeQuery(sql);
// rs.next();
// long id = rs.getLong(1);
// String name = rs.getString(2);
// String desc = rs.getString(3);
// String heuristic = rs.getString(4);
// rs.close();
// stmt.close();
// conn.close();
// return new Functionality(id, name, desc, heuristic);
// }
//
// }
// Path: src/evaluate/ToolEvaluator.java
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import cloneMatchingAlgorithms.CloneMatcher;
import database.Functionalities;
numClones_type2c_intra = new HashMap<Long,Integer>();
numDetected_type2c_inter = new HashMap<Long,Integer>();
numDetected_type2c_intra = new HashMap<Long,Integer>();
numClones_type2b_inter = new HashMap<Long,Integer>();
numClones_type2b_intra = new HashMap<Long,Integer>();
numDetected_type2b_inter = new HashMap<Long,Integer>();
numDetected_type2b_intra = new HashMap<Long,Integer>();
numClones_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];
numClones_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];
numDetected_type3_inter = (HashMap<Long,Integer>[]) new HashMap[20];
numDetected_type3_intra = (HashMap<Long,Integer>[]) new HashMap[20];
numClones_false_inter = new HashMap<Long,Integer>();
numClones_false_intra = new HashMap<Long,Integer>();
numDetected_false_inter = new HashMap<Long,Integer>();
numDetected_false_intra = new HashMap<Long,Integer>();
for(int i = 0; i < 20; i++) {
numClones_type3_inter[i] = new HashMap<Long,Integer>();
numClones_type3_intra[i] = new HashMap<Long,Integer>();
numDetected_type3_inter[i] = new HashMap<Long,Integer>();
numDetected_type3_intra[i] = new HashMap<Long,Integer>();
}
| functionality_ids = Functionalities.getFunctionalityIds(); |
jeffsvajlenko/BigCloneEval | src/tasks/Init.java | // Path: src/database/Tools.java
// public class Tools {
//
// public static boolean exists(long id) throws SQLException {
// Tool tool = getTool(id);
// if(tool == null) {
// return false;
// } else {
// return true;
// }
// }
//
// public static void dropall() throws SQLException {
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// String sql = "DROP ALL OBJECTS";
// stmt.execute(sql);
// stmt.close();
// conn.close();
// }
//
// public static void init() throws SQLException {
// dropall();
// String sql = "CREATE TABLE tools ( name character varying NOT NULL, description character varying NOT NULL, id identity NOT NULL);";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// stmt.executeUpdate(sql);
// stmt.close();
// conn.close();
// }
//
// public static boolean deleteToolAndData(long id) throws SQLException {
//
// // Remove Tool
// String sql = "DELETE FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// int num = stmt.executeUpdate(sql);
// conn.close();
// if(num == 0) {
// return false;
// }
//
// // Remove Table
// sql = "DROP TABLE tool_" + id + "_clones";
// stmt.execute(sql);
// conn.close();
// return true;
// }
//
// public static List<Tool> getTools() throws SQLException {
// List<Tool> retval = new LinkedList<Tool>();
// String sql = "SELECT id, name, description FROM tools ORDER BY id";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// while(rs.next()) {
// retval.add(new Tool(rs.getLong(1), rs.getString(2), rs.getString(3)));
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static Tool getTool(long id) throws SQLException {
// Tool retval;
// String sql = "SELECT id, name, description FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// if(rs.next()) {
// retval = new Tool(rs.getLong(1), rs.getString(2), rs.getString(3));
// } else {
// retval = null;
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static long addTool(String name, String description) throws SQLException {
// // Add Tool
// String sql = "INSERT INTO tools (name, description) VALUES (?,?)";
// Connection conn = ToolsDB.getConnection();
// PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// stmt.setString(1, name);
// stmt.setString(2, description);
// stmt.executeUpdate();
// ResultSet rs = stmt.getGeneratedKeys();
// rs.next();
// long id = rs.getLong(1);
// rs.close();
// stmt.close();
//
// // Add Clones Table and its index
// Statement stmt2 = conn.createStatement();
// sql = "CREATE TABLE tool_" + id + "_clones (type1 character varying NOT NULL, name1 character varying NOT NULL, startline1 integer NOT NULL, endline1 integer NOT NULL, type2 character varying NOT NULL, name2 character varying NOT NULL, startline2 integer NOT NULL, endline2 integer NOT NULL);";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, startline1, endline1, type2, name2, startline2, endline2)";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, type2, name2)";
// stmt2.execute(sql);
// stmt2.close();
//
// conn.close();
// return id;
// }
//
// }
| import java.sql.SQLException;
import java.util.concurrent.Callable;
import database.Tools;
import picocli.CommandLine;
| package tasks;
@CommandLine.Command(
name = "init",
description = "This command initializes the tools database. It is used on first-time setup. " +
"It can also be used to restore the tools database to its original condition. " +
"This will delete any tools, and their clones, from the database, and restart the ID increment to 1.%n" +
"This may take some time to execute as the database is compacted.",
mixinStandardHelpOptions = true,
versionProvider = util.Version.class)
public class Init implements Callable<Void> {
public static void main(String[] args) {
new CommandLine(new Init()).execute(args);
}
@Override
public Void call()throws SQLException {
| // Path: src/database/Tools.java
// public class Tools {
//
// public static boolean exists(long id) throws SQLException {
// Tool tool = getTool(id);
// if(tool == null) {
// return false;
// } else {
// return true;
// }
// }
//
// public static void dropall() throws SQLException {
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// String sql = "DROP ALL OBJECTS";
// stmt.execute(sql);
// stmt.close();
// conn.close();
// }
//
// public static void init() throws SQLException {
// dropall();
// String sql = "CREATE TABLE tools ( name character varying NOT NULL, description character varying NOT NULL, id identity NOT NULL);";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// stmt.executeUpdate(sql);
// stmt.close();
// conn.close();
// }
//
// public static boolean deleteToolAndData(long id) throws SQLException {
//
// // Remove Tool
// String sql = "DELETE FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// int num = stmt.executeUpdate(sql);
// conn.close();
// if(num == 0) {
// return false;
// }
//
// // Remove Table
// sql = "DROP TABLE tool_" + id + "_clones";
// stmt.execute(sql);
// conn.close();
// return true;
// }
//
// public static List<Tool> getTools() throws SQLException {
// List<Tool> retval = new LinkedList<Tool>();
// String sql = "SELECT id, name, description FROM tools ORDER BY id";
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// while(rs.next()) {
// retval.add(new Tool(rs.getLong(1), rs.getString(2), rs.getString(3)));
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static Tool getTool(long id) throws SQLException {
// Tool retval;
// String sql = "SELECT id, name, description FROM tools WHERE id = " + id;
// Connection conn = ToolsDB.getConnection();
// Statement stmt = conn.createStatement();
// ResultSet rs = stmt.executeQuery(sql);
// if(rs.next()) {
// retval = new Tool(rs.getLong(1), rs.getString(2), rs.getString(3));
// } else {
// retval = null;
// }
// rs.close();
// stmt.close();
// conn.close();
// return retval;
// }
//
// public static long addTool(String name, String description) throws SQLException {
// // Add Tool
// String sql = "INSERT INTO tools (name, description) VALUES (?,?)";
// Connection conn = ToolsDB.getConnection();
// PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// stmt.setString(1, name);
// stmt.setString(2, description);
// stmt.executeUpdate();
// ResultSet rs = stmt.getGeneratedKeys();
// rs.next();
// long id = rs.getLong(1);
// rs.close();
// stmt.close();
//
// // Add Clones Table and its index
// Statement stmt2 = conn.createStatement();
// sql = "CREATE TABLE tool_" + id + "_clones (type1 character varying NOT NULL, name1 character varying NOT NULL, startline1 integer NOT NULL, endline1 integer NOT NULL, type2 character varying NOT NULL, name2 character varying NOT NULL, startline2 integer NOT NULL, endline2 integer NOT NULL);";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, startline1, endline1, type2, name2, startline2, endline2)";
// stmt2.execute(sql);
// sql = "CREATE INDEX ON tool_" + id + "_clones (type1, name1, type2, name2)";
// stmt2.execute(sql);
// stmt2.close();
//
// conn.close();
// return id;
// }
//
// }
// Path: src/tasks/Init.java
import java.sql.SQLException;
import java.util.concurrent.Callable;
import database.Tools;
import picocli.CommandLine;
package tasks;
@CommandLine.Command(
name = "init",
description = "This command initializes the tools database. It is used on first-time setup. " +
"It can also be used to restore the tools database to its original condition. " +
"This will delete any tools, and their clones, from the database, and restart the ID increment to 1.%n" +
"This may take some time to execute as the database is compacted.",
mixinStandardHelpOptions = true,
versionProvider = util.Version.class)
public class Init implements Callable<Void> {
public static void main(String[] args) {
new CommandLine(new Init()).execute(args);
}
@Override
public Void call()throws SQLException {
| Tools.init();
|
danikula/aibolit | sample/src/main/java/com/danikula/aibolit/test/support/MutableListAdapter.java | // Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.danikula.aibolit.Validate; | package com.danikula.aibolit.test.support;
public abstract class MutableListAdapter<T> extends BaseAdapter {
private static final int UNDEFINED_LAYOUT_ID = -1;
private Context context;
private int layoutId;
private List<T> objects = new ArrayList<T>();
public MutableListAdapter(Context context, int layoutId) { | // Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
// Path: sample/src/main/java/com/danikula/aibolit/test/support/MutableListAdapter.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.danikula.aibolit.Validate;
package com.danikula.aibolit.test.support;
public abstract class MutableListAdapter<T> extends BaseAdapter {
private static final int UNDEFINED_LAYOUT_ID = -1;
private Context context;
private int layoutId;
private List<T> objects = new ArrayList<T>();
public MutableListAdapter(Context context, int layoutId) { | Validate.notNull(context, "Context should not be null"); |
danikula/aibolit | library/src/main/java/com/danikula/aibolit/injector/InjectorRegister.java | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/ServicesResolver.java
// public interface ServicesResolver {
//
// /**
// * Resolves application service by class
// *
// * @param serviceClass Class service's class
// * @return Object application service
// */
// Object resolve(Class<?> serviceClass);
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
| import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.ServicesResolver;
import com.danikula.aibolit.Validate;
import com.danikula.aibolit.annotation.InjectArrayAdapter;
import com.danikula.aibolit.annotation.InjectOnCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnClickListener;
import com.danikula.aibolit.annotation.InjectOnCreateContextMenuListener;
import com.danikula.aibolit.annotation.InjectOnEditorActionListener;
import com.danikula.aibolit.annotation.InjectOnFocusChangeListener;
import com.danikula.aibolit.annotation.InjectOnItemClickListener;
import com.danikula.aibolit.annotation.InjectOnItemSelectedListener;
import com.danikula.aibolit.annotation.InjectOnKeyListener;
import com.danikula.aibolit.annotation.InjectOnLongClickListener;
import com.danikula.aibolit.annotation.InjectOnRadioGroupCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnTextChangedListener;
import com.danikula.aibolit.annotation.InjectOnTouchListener;
import com.danikula.aibolit.annotation.InjectResource;
import com.danikula.aibolit.annotation.InjectService;
import com.danikula.aibolit.annotation.InjectSystemService;
import com.danikula.aibolit.annotation.InjectView; | /*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
public class InjectorRegister {
private static final Map<Class<? extends Annotation>, AbstractInjector<?>> INJECTORS_REGISTER;
| // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/ServicesResolver.java
// public interface ServicesResolver {
//
// /**
// * Resolves application service by class
// *
// * @param serviceClass Class service's class
// * @return Object application service
// */
// Object resolve(Class<?> serviceClass);
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
// Path: library/src/main/java/com/danikula/aibolit/injector/InjectorRegister.java
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.ServicesResolver;
import com.danikula.aibolit.Validate;
import com.danikula.aibolit.annotation.InjectArrayAdapter;
import com.danikula.aibolit.annotation.InjectOnCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnClickListener;
import com.danikula.aibolit.annotation.InjectOnCreateContextMenuListener;
import com.danikula.aibolit.annotation.InjectOnEditorActionListener;
import com.danikula.aibolit.annotation.InjectOnFocusChangeListener;
import com.danikula.aibolit.annotation.InjectOnItemClickListener;
import com.danikula.aibolit.annotation.InjectOnItemSelectedListener;
import com.danikula.aibolit.annotation.InjectOnKeyListener;
import com.danikula.aibolit.annotation.InjectOnLongClickListener;
import com.danikula.aibolit.annotation.InjectOnRadioGroupCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnTextChangedListener;
import com.danikula.aibolit.annotation.InjectOnTouchListener;
import com.danikula.aibolit.annotation.InjectResource;
import com.danikula.aibolit.annotation.InjectService;
import com.danikula.aibolit.annotation.InjectSystemService;
import com.danikula.aibolit.annotation.InjectView;
/*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
public class InjectorRegister {
private static final Map<Class<? extends Annotation>, AbstractInjector<?>> INJECTORS_REGISTER;
| private static final List<ServicesResolver> SERVICES_RESOLVERS; |
danikula/aibolit | library/src/main/java/com/danikula/aibolit/injector/InjectorRegister.java | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/ServicesResolver.java
// public interface ServicesResolver {
//
// /**
// * Resolves application service by class
// *
// * @param serviceClass Class service's class
// * @return Object application service
// */
// Object resolve(Class<?> serviceClass);
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
| import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.ServicesResolver;
import com.danikula.aibolit.Validate;
import com.danikula.aibolit.annotation.InjectArrayAdapter;
import com.danikula.aibolit.annotation.InjectOnCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnClickListener;
import com.danikula.aibolit.annotation.InjectOnCreateContextMenuListener;
import com.danikula.aibolit.annotation.InjectOnEditorActionListener;
import com.danikula.aibolit.annotation.InjectOnFocusChangeListener;
import com.danikula.aibolit.annotation.InjectOnItemClickListener;
import com.danikula.aibolit.annotation.InjectOnItemSelectedListener;
import com.danikula.aibolit.annotation.InjectOnKeyListener;
import com.danikula.aibolit.annotation.InjectOnLongClickListener;
import com.danikula.aibolit.annotation.InjectOnRadioGroupCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnTextChangedListener;
import com.danikula.aibolit.annotation.InjectOnTouchListener;
import com.danikula.aibolit.annotation.InjectResource;
import com.danikula.aibolit.annotation.InjectService;
import com.danikula.aibolit.annotation.InjectSystemService;
import com.danikula.aibolit.annotation.InjectView; | SERVICES_RESOLVERS = new LinkedList<ServicesResolver>();
INJECTORS_REGISTER = new HashMap<Class<? extends Annotation>, AbstractInjector<?>>();
INJECTORS_REGISTER.put(InjectView.class, new ViewInjector());
INJECTORS_REGISTER.put(InjectResource.class, new ResourceInjector());
INJECTORS_REGISTER.put(InjectArrayAdapter.class, new ArrayAdapterInjector());
INJECTORS_REGISTER.put(InjectSystemService.class, new SystemServiceInjector());
INJECTORS_REGISTER.put(InjectService.class, new ServiceInjector(SERVICES_RESOLVERS));
INJECTORS_REGISTER.put(InjectOnClickListener.class, new OnClickListenerInjector());
INJECTORS_REGISTER.put(InjectOnLongClickListener.class, new OnLongClickListenerInjector());
INJECTORS_REGISTER.put(InjectOnItemClickListener.class, new OnItemClickListenerInjector());
INJECTORS_REGISTER.put(InjectOnItemSelectedListener.class, new OnItemSelectedListenerInjector());
INJECTORS_REGISTER.put(InjectOnTouchListener.class, new OnTouchListenerInjector());
INJECTORS_REGISTER.put(InjectOnKeyListener.class, new OnKeyListenerInjector());
INJECTORS_REGISTER.put(InjectOnFocusChangeListener.class, new OnFocusChangeListenerInjector());
INJECTORS_REGISTER.put(InjectOnCreateContextMenuListener.class, new OnCreateContextMenuListenerInjector());
INJECTORS_REGISTER.put(InjectOnTextChangedListener.class, new OnTextChangedListenerInjector());
INJECTORS_REGISTER.put(InjectOnCheckedChangeListener.class, new OnCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnRadioGroupCheckedChangeListener.class, new OnRadioGroupCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnEditorActionListener.class, new OnEditorActionListenerInjector());
}
public static boolean contains(Class<? extends Annotation> annotationClass) {
return INJECTORS_REGISTER.containsKey(annotationClass);
}
public static AbstractFieldInjector<Annotation> getFieldInjector(Class<? extends Annotation> annotationClass) {
AbstractInjector<?> abstractInjector = INJECTORS_REGISTER.get(annotationClass);
if (!(abstractInjector instanceof AbstractFieldInjector)){ | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/ServicesResolver.java
// public interface ServicesResolver {
//
// /**
// * Resolves application service by class
// *
// * @param serviceClass Class service's class
// * @return Object application service
// */
// Object resolve(Class<?> serviceClass);
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
// Path: library/src/main/java/com/danikula/aibolit/injector/InjectorRegister.java
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.ServicesResolver;
import com.danikula.aibolit.Validate;
import com.danikula.aibolit.annotation.InjectArrayAdapter;
import com.danikula.aibolit.annotation.InjectOnCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnClickListener;
import com.danikula.aibolit.annotation.InjectOnCreateContextMenuListener;
import com.danikula.aibolit.annotation.InjectOnEditorActionListener;
import com.danikula.aibolit.annotation.InjectOnFocusChangeListener;
import com.danikula.aibolit.annotation.InjectOnItemClickListener;
import com.danikula.aibolit.annotation.InjectOnItemSelectedListener;
import com.danikula.aibolit.annotation.InjectOnKeyListener;
import com.danikula.aibolit.annotation.InjectOnLongClickListener;
import com.danikula.aibolit.annotation.InjectOnRadioGroupCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnTextChangedListener;
import com.danikula.aibolit.annotation.InjectOnTouchListener;
import com.danikula.aibolit.annotation.InjectResource;
import com.danikula.aibolit.annotation.InjectService;
import com.danikula.aibolit.annotation.InjectSystemService;
import com.danikula.aibolit.annotation.InjectView;
SERVICES_RESOLVERS = new LinkedList<ServicesResolver>();
INJECTORS_REGISTER = new HashMap<Class<? extends Annotation>, AbstractInjector<?>>();
INJECTORS_REGISTER.put(InjectView.class, new ViewInjector());
INJECTORS_REGISTER.put(InjectResource.class, new ResourceInjector());
INJECTORS_REGISTER.put(InjectArrayAdapter.class, new ArrayAdapterInjector());
INJECTORS_REGISTER.put(InjectSystemService.class, new SystemServiceInjector());
INJECTORS_REGISTER.put(InjectService.class, new ServiceInjector(SERVICES_RESOLVERS));
INJECTORS_REGISTER.put(InjectOnClickListener.class, new OnClickListenerInjector());
INJECTORS_REGISTER.put(InjectOnLongClickListener.class, new OnLongClickListenerInjector());
INJECTORS_REGISTER.put(InjectOnItemClickListener.class, new OnItemClickListenerInjector());
INJECTORS_REGISTER.put(InjectOnItemSelectedListener.class, new OnItemSelectedListenerInjector());
INJECTORS_REGISTER.put(InjectOnTouchListener.class, new OnTouchListenerInjector());
INJECTORS_REGISTER.put(InjectOnKeyListener.class, new OnKeyListenerInjector());
INJECTORS_REGISTER.put(InjectOnFocusChangeListener.class, new OnFocusChangeListenerInjector());
INJECTORS_REGISTER.put(InjectOnCreateContextMenuListener.class, new OnCreateContextMenuListenerInjector());
INJECTORS_REGISTER.put(InjectOnTextChangedListener.class, new OnTextChangedListenerInjector());
INJECTORS_REGISTER.put(InjectOnCheckedChangeListener.class, new OnCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnRadioGroupCheckedChangeListener.class, new OnRadioGroupCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnEditorActionListener.class, new OnEditorActionListenerInjector());
}
public static boolean contains(Class<? extends Annotation> annotationClass) {
return INJECTORS_REGISTER.containsKey(annotationClass);
}
public static AbstractFieldInjector<Annotation> getFieldInjector(Class<? extends Annotation> annotationClass) {
AbstractInjector<?> abstractInjector = INJECTORS_REGISTER.get(annotationClass);
if (!(abstractInjector instanceof AbstractFieldInjector)){ | throw new InjectingException("There is no registered AbstractFieldInjector for annotation class " + annotationClass.getName()); |
danikula/aibolit | library/src/main/java/com/danikula/aibolit/injector/InjectorRegister.java | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/ServicesResolver.java
// public interface ServicesResolver {
//
// /**
// * Resolves application service by class
// *
// * @param serviceClass Class service's class
// * @return Object application service
// */
// Object resolve(Class<?> serviceClass);
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
| import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.ServicesResolver;
import com.danikula.aibolit.Validate;
import com.danikula.aibolit.annotation.InjectArrayAdapter;
import com.danikula.aibolit.annotation.InjectOnCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnClickListener;
import com.danikula.aibolit.annotation.InjectOnCreateContextMenuListener;
import com.danikula.aibolit.annotation.InjectOnEditorActionListener;
import com.danikula.aibolit.annotation.InjectOnFocusChangeListener;
import com.danikula.aibolit.annotation.InjectOnItemClickListener;
import com.danikula.aibolit.annotation.InjectOnItemSelectedListener;
import com.danikula.aibolit.annotation.InjectOnKeyListener;
import com.danikula.aibolit.annotation.InjectOnLongClickListener;
import com.danikula.aibolit.annotation.InjectOnRadioGroupCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnTextChangedListener;
import com.danikula.aibolit.annotation.InjectOnTouchListener;
import com.danikula.aibolit.annotation.InjectResource;
import com.danikula.aibolit.annotation.InjectService;
import com.danikula.aibolit.annotation.InjectSystemService;
import com.danikula.aibolit.annotation.InjectView; | INJECTORS_REGISTER.put(InjectOnKeyListener.class, new OnKeyListenerInjector());
INJECTORS_REGISTER.put(InjectOnFocusChangeListener.class, new OnFocusChangeListenerInjector());
INJECTORS_REGISTER.put(InjectOnCreateContextMenuListener.class, new OnCreateContextMenuListenerInjector());
INJECTORS_REGISTER.put(InjectOnTextChangedListener.class, new OnTextChangedListenerInjector());
INJECTORS_REGISTER.put(InjectOnCheckedChangeListener.class, new OnCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnRadioGroupCheckedChangeListener.class, new OnRadioGroupCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnEditorActionListener.class, new OnEditorActionListenerInjector());
}
public static boolean contains(Class<? extends Annotation> annotationClass) {
return INJECTORS_REGISTER.containsKey(annotationClass);
}
public static AbstractFieldInjector<Annotation> getFieldInjector(Class<? extends Annotation> annotationClass) {
AbstractInjector<?> abstractInjector = INJECTORS_REGISTER.get(annotationClass);
if (!(abstractInjector instanceof AbstractFieldInjector)){
throw new InjectingException("There is no registered AbstractFieldInjector for annotation class " + annotationClass.getName());
}
return (AbstractFieldInjector<Annotation>) abstractInjector;
}
public static AbstractMethodInjector<Annotation> getMethodInjector(Class<? extends Annotation> annotationClass) {
AbstractInjector<?> abstractInjector = INJECTORS_REGISTER.get(annotationClass);
if (!(abstractInjector instanceof AbstractMethodInjector)){
throw new InjectingException("There is no registered AbstractMethodInjector for annotation class " + annotationClass.getName());
}
return (AbstractMethodInjector<Annotation>) abstractInjector;
}
public static void addServicesResolver(ServicesResolver serviceResolver){ | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/ServicesResolver.java
// public interface ServicesResolver {
//
// /**
// * Resolves application service by class
// *
// * @param serviceClass Class service's class
// * @return Object application service
// */
// Object resolve(Class<?> serviceClass);
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/Validate.java
// public class Validate {
//
// /**
// * Checks variable on <code>null</code>
// *
// * @param object Object variable to be checked
// * @param message String message of exception to be throwed if parameter is <code>null</code>
// * @throws IllegalArgumentException if <code>object</code> is <code>null</code>
// */
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// /**
// * Checks contition on <code>true</code>
// *
// * @param condition boolean condition to check
// * @param message String message of exception to be throwed if condition is not <code>true</code>
// * @throws IllegalArgumentException if <code>condition</code> is not <code>true</code>
// */
// public static void checkTrue(boolean condition, String message) {
// if (!condition) {
// throw new IllegalArgumentException(message);
// }
// }
//
// }
// Path: library/src/main/java/com/danikula/aibolit/injector/InjectorRegister.java
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.ServicesResolver;
import com.danikula.aibolit.Validate;
import com.danikula.aibolit.annotation.InjectArrayAdapter;
import com.danikula.aibolit.annotation.InjectOnCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnClickListener;
import com.danikula.aibolit.annotation.InjectOnCreateContextMenuListener;
import com.danikula.aibolit.annotation.InjectOnEditorActionListener;
import com.danikula.aibolit.annotation.InjectOnFocusChangeListener;
import com.danikula.aibolit.annotation.InjectOnItemClickListener;
import com.danikula.aibolit.annotation.InjectOnItemSelectedListener;
import com.danikula.aibolit.annotation.InjectOnKeyListener;
import com.danikula.aibolit.annotation.InjectOnLongClickListener;
import com.danikula.aibolit.annotation.InjectOnRadioGroupCheckedChangeListener;
import com.danikula.aibolit.annotation.InjectOnTextChangedListener;
import com.danikula.aibolit.annotation.InjectOnTouchListener;
import com.danikula.aibolit.annotation.InjectResource;
import com.danikula.aibolit.annotation.InjectService;
import com.danikula.aibolit.annotation.InjectSystemService;
import com.danikula.aibolit.annotation.InjectView;
INJECTORS_REGISTER.put(InjectOnKeyListener.class, new OnKeyListenerInjector());
INJECTORS_REGISTER.put(InjectOnFocusChangeListener.class, new OnFocusChangeListenerInjector());
INJECTORS_REGISTER.put(InjectOnCreateContextMenuListener.class, new OnCreateContextMenuListenerInjector());
INJECTORS_REGISTER.put(InjectOnTextChangedListener.class, new OnTextChangedListenerInjector());
INJECTORS_REGISTER.put(InjectOnCheckedChangeListener.class, new OnCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnRadioGroupCheckedChangeListener.class, new OnRadioGroupCheckedChangeInjector());
INJECTORS_REGISTER.put(InjectOnEditorActionListener.class, new OnEditorActionListenerInjector());
}
public static boolean contains(Class<? extends Annotation> annotationClass) {
return INJECTORS_REGISTER.containsKey(annotationClass);
}
public static AbstractFieldInjector<Annotation> getFieldInjector(Class<? extends Annotation> annotationClass) {
AbstractInjector<?> abstractInjector = INJECTORS_REGISTER.get(annotationClass);
if (!(abstractInjector instanceof AbstractFieldInjector)){
throw new InjectingException("There is no registered AbstractFieldInjector for annotation class " + annotationClass.getName());
}
return (AbstractFieldInjector<Annotation>) abstractInjector;
}
public static AbstractMethodInjector<Annotation> getMethodInjector(Class<? extends Annotation> annotationClass) {
AbstractInjector<?> abstractInjector = INJECTORS_REGISTER.get(annotationClass);
if (!(abstractInjector instanceof AbstractMethodInjector)){
throw new InjectingException("There is no registered AbstractMethodInjector for annotation class " + annotationClass.getName());
}
return (AbstractMethodInjector<Annotation>) abstractInjector;
}
public static void addServicesResolver(ServicesResolver serviceResolver){ | Validate.notNull(serviceResolver, "InjectionResolver must be not null"); |
danikula/aibolit | library/src/main/java/com/danikula/aibolit/injector/AbstractMethodInjector.java | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/InjectionContext.java
// public interface InjectionContext {
//
// View getRootView();
//
// Context getAndroidContext();
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/MethodInvocationHandler.java
// public class MethodInvocationHandler implements InvocationHandler {
//
// private Object methodOwner;
//
// private Method targetMethod;
//
// private Method sourceMethod;
//
// /**
// * Constructs invokation handler.
// *
// * @param methodOwner Object object that contains fields or methods that should be injected
// * @param sourceMethod Method method to be called
// * @param targetMethod Method method of listener
// */
// public MethodInvocationHandler(Object methodOwner, Method sourceMethod, Method targetMethod) {
// this.methodOwner = methodOwner;
// this.targetMethod = targetMethod;
// this.sourceMethod = sourceMethod;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// if (method.getName().equals(targetMethod.getName())) {
// sourceMethod.setAccessible(true);
// return sourceMethod.invoke(methodOwner, args);
// }
// // call only one target method, ignore other
// return null;
// }
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import android.view.View;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.InjectionContext;
import com.danikula.aibolit.MethodInvocationHandler; | /*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
/**
* Injects event handler
*
* @author Alexey Danilov
*
* @param <A> type of corresponding annotation
*/
public abstract class AbstractMethodInjector<A extends Annotation> extends AbstractInjector<A> {
/**
* Injects event handler
* @param methodOwner Objects object that contain method
* @param injectionContext InjectionContext object to be used for retrieving information about injection context
* @param sourceMethod method to be invoked as event handler
* @param annotation T annotation fir providing data for injection
*/
public abstract void doInjection(Object methodOwner, InjectionContext injectionContext, Method sourceMethod, A annotation);
protected void checkIsViewAssignable(Class<? extends View> expectedClass, Class<? extends View> actualClass) {
if (!expectedClass.isAssignableFrom(actualClass)) {
String errorPattern = "Injecting is allowable only for view with type %s, but not for %s"; | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/InjectionContext.java
// public interface InjectionContext {
//
// View getRootView();
//
// Context getAndroidContext();
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/MethodInvocationHandler.java
// public class MethodInvocationHandler implements InvocationHandler {
//
// private Object methodOwner;
//
// private Method targetMethod;
//
// private Method sourceMethod;
//
// /**
// * Constructs invokation handler.
// *
// * @param methodOwner Object object that contains fields or methods that should be injected
// * @param sourceMethod Method method to be called
// * @param targetMethod Method method of listener
// */
// public MethodInvocationHandler(Object methodOwner, Method sourceMethod, Method targetMethod) {
// this.methodOwner = methodOwner;
// this.targetMethod = targetMethod;
// this.sourceMethod = sourceMethod;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// if (method.getName().equals(targetMethod.getName())) {
// sourceMethod.setAccessible(true);
// return sourceMethod.invoke(methodOwner, args);
// }
// // call only one target method, ignore other
// return null;
// }
// }
// Path: library/src/main/java/com/danikula/aibolit/injector/AbstractMethodInjector.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import android.view.View;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.InjectionContext;
import com.danikula.aibolit.MethodInvocationHandler;
/*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
/**
* Injects event handler
*
* @author Alexey Danilov
*
* @param <A> type of corresponding annotation
*/
public abstract class AbstractMethodInjector<A extends Annotation> extends AbstractInjector<A> {
/**
* Injects event handler
* @param methodOwner Objects object that contain method
* @param injectionContext InjectionContext object to be used for retrieving information about injection context
* @param sourceMethod method to be invoked as event handler
* @param annotation T annotation fir providing data for injection
*/
public abstract void doInjection(Object methodOwner, InjectionContext injectionContext, Method sourceMethod, A annotation);
protected void checkIsViewAssignable(Class<? extends View> expectedClass, Class<? extends View> actualClass) {
if (!expectedClass.isAssignableFrom(actualClass)) {
String errorPattern = "Injecting is allowable only for view with type %s, but not for %s"; | throw new InjectingException(String.format(errorPattern, expectedClass.getName(), actualClass.getName())); |
danikula/aibolit | library/src/main/java/com/danikula/aibolit/injector/AbstractMethodInjector.java | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/InjectionContext.java
// public interface InjectionContext {
//
// View getRootView();
//
// Context getAndroidContext();
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/MethodInvocationHandler.java
// public class MethodInvocationHandler implements InvocationHandler {
//
// private Object methodOwner;
//
// private Method targetMethod;
//
// private Method sourceMethod;
//
// /**
// * Constructs invokation handler.
// *
// * @param methodOwner Object object that contains fields or methods that should be injected
// * @param sourceMethod Method method to be called
// * @param targetMethod Method method of listener
// */
// public MethodInvocationHandler(Object methodOwner, Method sourceMethod, Method targetMethod) {
// this.methodOwner = methodOwner;
// this.targetMethod = targetMethod;
// this.sourceMethod = sourceMethod;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// if (method.getName().equals(targetMethod.getName())) {
// sourceMethod.setAccessible(true);
// return sourceMethod.invoke(methodOwner, args);
// }
// // call only one target method, ignore other
// return null;
// }
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import android.view.View;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.InjectionContext;
import com.danikula.aibolit.MethodInvocationHandler; | protected void checkMethodSignature(Method sourceMethod, Method targetMethod) {
Class<?>[] sourceMethodArgTypes = sourceMethod.getParameterTypes();
Class<?>[] targetMethodArgTypes = targetMethod.getParameterTypes();
if (!Arrays.equals(sourceMethodArgTypes, targetMethodArgTypes)) {
throw new InjectingException(String.format("Method has incorrect parameters: %s. Expected: %s",
Arrays.toString(targetMethodArgTypes), Arrays.toString(sourceMethodArgTypes)));
}
if (!sourceMethod.getReturnType().equals(targetMethod.getReturnType())) {
throw new InjectingException(String.format("Method has incorrect return type: %s. Expected: %s",
targetMethod.getReturnType(), sourceMethod.getReturnType()));
}
}
protected Method getMethod(Class<?> methodOwner, String methodName, Class<?>[] argsTypes, Method sourceMethod) {
String errorPattern = "Error getting method named '%s' from class %s";
try {
Method method = methodOwner.getMethod(methodName, argsTypes);
checkMethodSignature(method, sourceMethod);
return method;
}
catch (SecurityException e) {
throw new IllegalArgumentException(String.format(errorPattern, methodName, methodOwner.getName()), e);
}
catch (NoSuchMethodException e) {
throw new IllegalArgumentException(String.format(errorPattern, methodName, methodOwner.getName()), e);
}
}
protected <H> H createInvokationProxy(Class<H> proxyClass, Object methodOwner, Method sourceMethod, Method targetMethod) { | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/InjectionContext.java
// public interface InjectionContext {
//
// View getRootView();
//
// Context getAndroidContext();
//
// }
//
// Path: library/src/main/java/com/danikula/aibolit/MethodInvocationHandler.java
// public class MethodInvocationHandler implements InvocationHandler {
//
// private Object methodOwner;
//
// private Method targetMethod;
//
// private Method sourceMethod;
//
// /**
// * Constructs invokation handler.
// *
// * @param methodOwner Object object that contains fields or methods that should be injected
// * @param sourceMethod Method method to be called
// * @param targetMethod Method method of listener
// */
// public MethodInvocationHandler(Object methodOwner, Method sourceMethod, Method targetMethod) {
// this.methodOwner = methodOwner;
// this.targetMethod = targetMethod;
// this.sourceMethod = sourceMethod;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// if (method.getName().equals(targetMethod.getName())) {
// sourceMethod.setAccessible(true);
// return sourceMethod.invoke(methodOwner, args);
// }
// // call only one target method, ignore other
// return null;
// }
// }
// Path: library/src/main/java/com/danikula/aibolit/injector/AbstractMethodInjector.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import android.view.View;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.InjectionContext;
import com.danikula.aibolit.MethodInvocationHandler;
protected void checkMethodSignature(Method sourceMethod, Method targetMethod) {
Class<?>[] sourceMethodArgTypes = sourceMethod.getParameterTypes();
Class<?>[] targetMethodArgTypes = targetMethod.getParameterTypes();
if (!Arrays.equals(sourceMethodArgTypes, targetMethodArgTypes)) {
throw new InjectingException(String.format("Method has incorrect parameters: %s. Expected: %s",
Arrays.toString(targetMethodArgTypes), Arrays.toString(sourceMethodArgTypes)));
}
if (!sourceMethod.getReturnType().equals(targetMethod.getReturnType())) {
throw new InjectingException(String.format("Method has incorrect return type: %s. Expected: %s",
targetMethod.getReturnType(), sourceMethod.getReturnType()));
}
}
protected Method getMethod(Class<?> methodOwner, String methodName, Class<?>[] argsTypes, Method sourceMethod) {
String errorPattern = "Error getting method named '%s' from class %s";
try {
Method method = methodOwner.getMethod(methodName, argsTypes);
checkMethodSignature(method, sourceMethod);
return method;
}
catch (SecurityException e) {
throw new IllegalArgumentException(String.format(errorPattern, methodName, methodOwner.getName()), e);
}
catch (NoSuchMethodException e) {
throw new IllegalArgumentException(String.format(errorPattern, methodName, methodOwner.getName()), e);
}
}
protected <H> H createInvokationProxy(Class<H> proxyClass, Object methodOwner, Method sourceMethod, Method targetMethod) { | MethodInvocationHandler methodInvocationHandler = new MethodInvocationHandler(methodOwner, sourceMethod, targetMethod); |
danikula/aibolit | library/src/main/java/com/danikula/aibolit/injector/AbstractInjector.java | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
| import java.lang.annotation.Annotation;
import android.view.View;
import com.danikula.aibolit.InjectingException; | /*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
/**
* Injects field or method using data from annotation
*
* @author Alexey Danilov
*
* @param <T> type of corresponding annotation
*/
public abstract class AbstractInjector<T extends Annotation> {
protected View getViewById(View viewHolder, int viewId) {
View view = viewHolder.findViewById(viewId);
if (view == null) {
String errorPattern = "There is no view with id 0x%s in view %s"; | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
// Path: library/src/main/java/com/danikula/aibolit/injector/AbstractInjector.java
import java.lang.annotation.Annotation;
import android.view.View;
import com.danikula.aibolit.InjectingException;
/*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
/**
* Injects field or method using data from annotation
*
* @author Alexey Danilov
*
* @param <T> type of corresponding annotation
*/
public abstract class AbstractInjector<T extends Annotation> {
protected View getViewById(View viewHolder, int viewId) {
View view = viewHolder.findViewById(viewId);
if (view == null) {
String errorPattern = "There is no view with id 0x%s in view %s"; | throw new InjectingException(String.format(errorPattern, Integer.toHexString(viewId), viewHolder)); |
danikula/aibolit | sample/src/main/java/com/danikula/aibolit/test/ClassicChatActivity.java | // Path: sample/src/main/java/com/danikula/aibolit/test/support/Message.java
// public class Message {
//
// private Date time;
//
// private String text;
//
// public Message(Date time, String text) {
// this.time = time;
// this.text = text;
// }
//
// public Date getTime() {
// return time;
// }
//
// public String getText() {
// return text;
// }
//
// }
//
// Path: sample/src/main/java/com/danikula/aibolit/test/support/MutableListAdapter.java
// public abstract class MutableListAdapter<T> extends BaseAdapter {
//
// private static final int UNDEFINED_LAYOUT_ID = -1;
//
// private Context context;
//
// private int layoutId;
//
// private List<T> objects = new ArrayList<T>();
//
// public MutableListAdapter(Context context, int layoutId) {
// Validate.notNull(context, "Context should not be null");
// this.context = context;
// this.layoutId = layoutId;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// View view = convertView == null ? createView(context, position) : convertView;
//
// if (isViewBindable(position)) {
// T object = getObject(position);
// bind(object, view, position);
// }
//
// return view;
// }
//
// @Override
// public int getCount() {
// return objects.size();
// }
//
// @Override
// public Object getItem(int position) {
// return getObject(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// public void setObjects(List<T> objects) {
// this.objects = new ArrayList<T>(objects == null ? Collections.<T>emptyList() : objects);
// super.notifyDataSetChanged();
// }
//
// public void addAll(List<T> newItems) {
// objects.addAll(newItems);
// super.notifyDataSetChanged();
// }
//
// public void add(T newItems) {
// objects.add(newItems);
// super.notifyDataSetChanged();
// }
//
// public void addTo(T newItems, int index) {
// objects.add(index, newItems);
// super.notifyDataSetChanged();
// }
//
// public T getObject(int position) {
// return objects.get(position);
// }
//
// public void clear() {
// setObjects(new ArrayList<T>());
// super.notifyDataSetChanged();
// }
//
// protected Context getContext() {
// return context;
// }
//
// protected View createView(Context context, int position) {
// if (layoutId == UNDEFINED_LAYOUT_ID) {
// throw new IllegalStateException("Layout identifier for row view is not specified!");
// }
// return LayoutInflater.from(context).inflate(layoutId, null);
// }
//
// protected abstract void bind(T object, View view, int position);
//
// protected boolean isViewBindable(int position) {
// return true;
// }
// }
| import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.danikula.aibolit.test.support.Message;
import com.danikula.aibolit.test.support.MutableListAdapter; |
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(getString(R.string.menu_aibolit)).setIntent(new Intent(this, AibolitChatActivity.class));
menu.add(getString(R.string.menu_test)).setIntent(new Intent(this, TestInjectActivity.class));
return super.onCreateOptionsMenu(menu);
}
private final class OnMessageTextWatcher implements TextWatcher {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String symbolsCountText = String.format(symbolsCountPattern, s.length());
symbolsCountTextVew.setText(symbolsCountText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
private final class OnSendButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
String text = messageEditText.getText().toString(); | // Path: sample/src/main/java/com/danikula/aibolit/test/support/Message.java
// public class Message {
//
// private Date time;
//
// private String text;
//
// public Message(Date time, String text) {
// this.time = time;
// this.text = text;
// }
//
// public Date getTime() {
// return time;
// }
//
// public String getText() {
// return text;
// }
//
// }
//
// Path: sample/src/main/java/com/danikula/aibolit/test/support/MutableListAdapter.java
// public abstract class MutableListAdapter<T> extends BaseAdapter {
//
// private static final int UNDEFINED_LAYOUT_ID = -1;
//
// private Context context;
//
// private int layoutId;
//
// private List<T> objects = new ArrayList<T>();
//
// public MutableListAdapter(Context context, int layoutId) {
// Validate.notNull(context, "Context should not be null");
// this.context = context;
// this.layoutId = layoutId;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// View view = convertView == null ? createView(context, position) : convertView;
//
// if (isViewBindable(position)) {
// T object = getObject(position);
// bind(object, view, position);
// }
//
// return view;
// }
//
// @Override
// public int getCount() {
// return objects.size();
// }
//
// @Override
// public Object getItem(int position) {
// return getObject(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// public void setObjects(List<T> objects) {
// this.objects = new ArrayList<T>(objects == null ? Collections.<T>emptyList() : objects);
// super.notifyDataSetChanged();
// }
//
// public void addAll(List<T> newItems) {
// objects.addAll(newItems);
// super.notifyDataSetChanged();
// }
//
// public void add(T newItems) {
// objects.add(newItems);
// super.notifyDataSetChanged();
// }
//
// public void addTo(T newItems, int index) {
// objects.add(index, newItems);
// super.notifyDataSetChanged();
// }
//
// public T getObject(int position) {
// return objects.get(position);
// }
//
// public void clear() {
// setObjects(new ArrayList<T>());
// super.notifyDataSetChanged();
// }
//
// protected Context getContext() {
// return context;
// }
//
// protected View createView(Context context, int position) {
// if (layoutId == UNDEFINED_LAYOUT_ID) {
// throw new IllegalStateException("Layout identifier for row view is not specified!");
// }
// return LayoutInflater.from(context).inflate(layoutId, null);
// }
//
// protected abstract void bind(T object, View view, int position);
//
// protected boolean isViewBindable(int position) {
// return true;
// }
// }
// Path: sample/src/main/java/com/danikula/aibolit/test/ClassicChatActivity.java
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.danikula.aibolit.test.support.Message;
import com.danikula.aibolit.test.support.MutableListAdapter;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(getString(R.string.menu_aibolit)).setIntent(new Intent(this, AibolitChatActivity.class));
menu.add(getString(R.string.menu_test)).setIntent(new Intent(this, TestInjectActivity.class));
return super.onCreateOptionsMenu(menu);
}
private final class OnMessageTextWatcher implements TextWatcher {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String symbolsCountText = String.format(symbolsCountPattern, s.length());
symbolsCountTextVew.setText(symbolsCountText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
private final class OnSendButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
String text = messageEditText.getText().toString(); | adapter.add(new Message(new Date(), text)); |
danikula/aibolit | sample/src/main/java/com/danikula/aibolit/test/ClassicChatActivity.java | // Path: sample/src/main/java/com/danikula/aibolit/test/support/Message.java
// public class Message {
//
// private Date time;
//
// private String text;
//
// public Message(Date time, String text) {
// this.time = time;
// this.text = text;
// }
//
// public Date getTime() {
// return time;
// }
//
// public String getText() {
// return text;
// }
//
// }
//
// Path: sample/src/main/java/com/danikula/aibolit/test/support/MutableListAdapter.java
// public abstract class MutableListAdapter<T> extends BaseAdapter {
//
// private static final int UNDEFINED_LAYOUT_ID = -1;
//
// private Context context;
//
// private int layoutId;
//
// private List<T> objects = new ArrayList<T>();
//
// public MutableListAdapter(Context context, int layoutId) {
// Validate.notNull(context, "Context should not be null");
// this.context = context;
// this.layoutId = layoutId;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// View view = convertView == null ? createView(context, position) : convertView;
//
// if (isViewBindable(position)) {
// T object = getObject(position);
// bind(object, view, position);
// }
//
// return view;
// }
//
// @Override
// public int getCount() {
// return objects.size();
// }
//
// @Override
// public Object getItem(int position) {
// return getObject(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// public void setObjects(List<T> objects) {
// this.objects = new ArrayList<T>(objects == null ? Collections.<T>emptyList() : objects);
// super.notifyDataSetChanged();
// }
//
// public void addAll(List<T> newItems) {
// objects.addAll(newItems);
// super.notifyDataSetChanged();
// }
//
// public void add(T newItems) {
// objects.add(newItems);
// super.notifyDataSetChanged();
// }
//
// public void addTo(T newItems, int index) {
// objects.add(index, newItems);
// super.notifyDataSetChanged();
// }
//
// public T getObject(int position) {
// return objects.get(position);
// }
//
// public void clear() {
// setObjects(new ArrayList<T>());
// super.notifyDataSetChanged();
// }
//
// protected Context getContext() {
// return context;
// }
//
// protected View createView(Context context, int position) {
// if (layoutId == UNDEFINED_LAYOUT_ID) {
// throw new IllegalStateException("Layout identifier for row view is not specified!");
// }
// return LayoutInflater.from(context).inflate(layoutId, null);
// }
//
// protected abstract void bind(T object, View view, int position);
//
// protected boolean isViewBindable(int position) {
// return true;
// }
// }
| import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.danikula.aibolit.test.support.Message;
import com.danikula.aibolit.test.support.MutableListAdapter; | symbolsCountTextVew.setText(symbolsCountText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
private final class OnSendButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
String text = messageEditText.getText().toString();
adapter.add(new Message(new Date(), text));
messageEditText.getEditableText().clear();
}
}
private final class OnClearHistoryButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
adapter.clear();
}
}
| // Path: sample/src/main/java/com/danikula/aibolit/test/support/Message.java
// public class Message {
//
// private Date time;
//
// private String text;
//
// public Message(Date time, String text) {
// this.time = time;
// this.text = text;
// }
//
// public Date getTime() {
// return time;
// }
//
// public String getText() {
// return text;
// }
//
// }
//
// Path: sample/src/main/java/com/danikula/aibolit/test/support/MutableListAdapter.java
// public abstract class MutableListAdapter<T> extends BaseAdapter {
//
// private static final int UNDEFINED_LAYOUT_ID = -1;
//
// private Context context;
//
// private int layoutId;
//
// private List<T> objects = new ArrayList<T>();
//
// public MutableListAdapter(Context context, int layoutId) {
// Validate.notNull(context, "Context should not be null");
// this.context = context;
// this.layoutId = layoutId;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
// View view = convertView == null ? createView(context, position) : convertView;
//
// if (isViewBindable(position)) {
// T object = getObject(position);
// bind(object, view, position);
// }
//
// return view;
// }
//
// @Override
// public int getCount() {
// return objects.size();
// }
//
// @Override
// public Object getItem(int position) {
// return getObject(position);
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// public void setObjects(List<T> objects) {
// this.objects = new ArrayList<T>(objects == null ? Collections.<T>emptyList() : objects);
// super.notifyDataSetChanged();
// }
//
// public void addAll(List<T> newItems) {
// objects.addAll(newItems);
// super.notifyDataSetChanged();
// }
//
// public void add(T newItems) {
// objects.add(newItems);
// super.notifyDataSetChanged();
// }
//
// public void addTo(T newItems, int index) {
// objects.add(index, newItems);
// super.notifyDataSetChanged();
// }
//
// public T getObject(int position) {
// return objects.get(position);
// }
//
// public void clear() {
// setObjects(new ArrayList<T>());
// super.notifyDataSetChanged();
// }
//
// protected Context getContext() {
// return context;
// }
//
// protected View createView(Context context, int position) {
// if (layoutId == UNDEFINED_LAYOUT_ID) {
// throw new IllegalStateException("Layout identifier for row view is not specified!");
// }
// return LayoutInflater.from(context).inflate(layoutId, null);
// }
//
// protected abstract void bind(T object, View view, int position);
//
// protected boolean isViewBindable(int position) {
// return true;
// }
// }
// Path: sample/src/main/java/com/danikula/aibolit/test/ClassicChatActivity.java
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.danikula.aibolit.test.support.Message;
import com.danikula.aibolit.test.support.MutableListAdapter;
symbolsCountTextVew.setText(symbolsCountText);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
}
private final class OnSendButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
String text = messageEditText.getText().toString();
adapter.add(new Message(new Date(), text));
messageEditText.getEditableText().clear();
}
}
private final class OnClearHistoryButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
adapter.clear();
}
}
| private class LogAdapter extends MutableListAdapter<Message> { |
danikula/aibolit | library/src/main/java/com/danikula/aibolit/injector/AbstractFieldInjector.java | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/InjectionContext.java
// public interface InjectionContext {
//
// View getRootView();
//
// Context getAndroidContext();
//
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.InjectionContext; | /*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
/**
* Injects field into object
*
* @author Alexey Danilov
*
* @param <A> type of corresponding annotation
*/
public abstract class AbstractFieldInjector<A extends Annotation> extends AbstractInjector<A> {
/**
* Injects filed into object
* @param fieldOwner Objects object that contain field
* @param injectionContext InjectionContext object to be used for retrieving information about injection context
* @param field Filed injected to be initialized
* @param annotation T annotation fir providing data for injection
*/
public abstract void doInjection(Object fieldOwner, InjectionContext injectionContext, Field field, A annotation);
protected void checkIsFieldAssignable(Field field, Class<?> fieldClass, Class<?> viewClass) {
if (!fieldClass.isAssignableFrom(viewClass)) {
String errorPatterm = "Can't cast object with type %s to field named '%s' with type %s"; | // Path: library/src/main/java/com/danikula/aibolit/InjectingException.java
// public class InjectingException extends RuntimeException {
//
// private static final long serialVersionUID = -1L;
//
// public InjectingException(String message) {
// super(message);
// }
//
// public InjectingException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public InjectingException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/com/danikula/aibolit/InjectionContext.java
// public interface InjectionContext {
//
// View getRootView();
//
// Context getAndroidContext();
//
// }
// Path: library/src/main/java/com/danikula/aibolit/injector/AbstractFieldInjector.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import com.danikula.aibolit.InjectingException;
import com.danikula.aibolit.InjectionContext;
/*
* Copyright (C) 2011 Alexey Danilov
*
* 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.danikula.aibolit.injector;
/**
* Injects field into object
*
* @author Alexey Danilov
*
* @param <A> type of corresponding annotation
*/
public abstract class AbstractFieldInjector<A extends Annotation> extends AbstractInjector<A> {
/**
* Injects filed into object
* @param fieldOwner Objects object that contain field
* @param injectionContext InjectionContext object to be used for retrieving information about injection context
* @param field Filed injected to be initialized
* @param annotation T annotation fir providing data for injection
*/
public abstract void doInjection(Object fieldOwner, InjectionContext injectionContext, Field field, A annotation);
protected void checkIsFieldAssignable(Field field, Class<?> fieldClass, Class<?> viewClass) {
if (!fieldClass.isAssignableFrom(viewClass)) {
String errorPatterm = "Can't cast object with type %s to field named '%s' with type %s"; | throw new InjectingException(String.format(errorPatterm, viewClass, field.getName(), fieldClass.getName())); |
BurstProject/burstcoin | src/java/nxt/http/GetDGSPurchases.java | // Path: src/java/nxt/db/FilteringIterator.java
// public final class FilteringIterator<T> implements Iterator<T>, Iterable<T>, AutoCloseable {
//
// public static interface Filter<T> {
// boolean ok(T t);
// }
//
// private final DbIterator<T> dbIterator;
// private final Filter<T> filter;
// private final int from;
// private final int to;
// private T next;
// private boolean hasNext;
// private boolean iterated;
// private int count;
//
// public FilteringIterator(DbIterator<T> dbIterator, Filter<T> filter) {
// this(dbIterator, filter, 0, Integer.MAX_VALUE);
// }
//
// public FilteringIterator(DbIterator<T> dbIterator, int from, int to) {
// this(dbIterator, new Filter<T>() {
// @Override
// public boolean ok(T t) {
// return true;
// }
// }, from, to);
// }
//
// public FilteringIterator(DbIterator<T> dbIterator, Filter<T> filter, int from, int to) {
// this.dbIterator = dbIterator;
// this.filter = filter;
// this.from = from;
// this.to = to;
// }
//
// @Override
// public boolean hasNext() {
// if (hasNext) {
// return true;
// }
// while (dbIterator.hasNext() && count <= to) {
// next = dbIterator.next();
// if (filter.ok(next)) {
// if (count >= from) {
// count += 1;
// hasNext = true;
// return true;
// }
// count += 1;
// }
// }
// hasNext = false;
// return false;
// }
//
// @Override
// public T next() {
// if (hasNext) {
// hasNext = false;
// return next;
// }
// while (dbIterator.hasNext() && count <= to) {
// next = dbIterator.next();
// if (filter.ok(next)) {
// if (count >= from) {
// count += 1;
// hasNext = false;
// return next;
// }
// count += 1;
// }
// }
// throw new NoSuchElementException();
// }
//
// @Override
// public void close() {
// dbIterator.close();
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// @Override
// public Iterator<T> iterator() {
// if (iterated) {
// throw new IllegalStateException("Already iterated");
// }
// iterated = true;
// return this;
// }
//
// }
| import nxt.DigitalGoodsStore;
import nxt.NxtException;
import nxt.db.DbIterator;
import nxt.db.FilteringIterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest; | package nxt.http;
public final class GetDGSPurchases extends APIServlet.APIRequestHandler {
static final GetDGSPurchases instance = new GetDGSPurchases();
private GetDGSPurchases() {
super(new APITag[] {APITag.DGS}, "seller", "buyer", "firstIndex", "lastIndex", "completed");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
long sellerId = ParameterParser.getSellerId(req);
long buyerId = ParameterParser.getBuyerId(req);
int firstIndex = ParameterParser.getFirstIndex(req);
int lastIndex = ParameterParser.getLastIndex(req);
final boolean completed = "true".equalsIgnoreCase(req.getParameter("completed"));
JSONObject response = new JSONObject();
JSONArray purchasesJSON = new JSONArray();
response.put("purchases", purchasesJSON);
if (sellerId == 0 && buyerId == 0) { | // Path: src/java/nxt/db/FilteringIterator.java
// public final class FilteringIterator<T> implements Iterator<T>, Iterable<T>, AutoCloseable {
//
// public static interface Filter<T> {
// boolean ok(T t);
// }
//
// private final DbIterator<T> dbIterator;
// private final Filter<T> filter;
// private final int from;
// private final int to;
// private T next;
// private boolean hasNext;
// private boolean iterated;
// private int count;
//
// public FilteringIterator(DbIterator<T> dbIterator, Filter<T> filter) {
// this(dbIterator, filter, 0, Integer.MAX_VALUE);
// }
//
// public FilteringIterator(DbIterator<T> dbIterator, int from, int to) {
// this(dbIterator, new Filter<T>() {
// @Override
// public boolean ok(T t) {
// return true;
// }
// }, from, to);
// }
//
// public FilteringIterator(DbIterator<T> dbIterator, Filter<T> filter, int from, int to) {
// this.dbIterator = dbIterator;
// this.filter = filter;
// this.from = from;
// this.to = to;
// }
//
// @Override
// public boolean hasNext() {
// if (hasNext) {
// return true;
// }
// while (dbIterator.hasNext() && count <= to) {
// next = dbIterator.next();
// if (filter.ok(next)) {
// if (count >= from) {
// count += 1;
// hasNext = true;
// return true;
// }
// count += 1;
// }
// }
// hasNext = false;
// return false;
// }
//
// @Override
// public T next() {
// if (hasNext) {
// hasNext = false;
// return next;
// }
// while (dbIterator.hasNext() && count <= to) {
// next = dbIterator.next();
// if (filter.ok(next)) {
// if (count >= from) {
// count += 1;
// hasNext = false;
// return next;
// }
// count += 1;
// }
// }
// throw new NoSuchElementException();
// }
//
// @Override
// public void close() {
// dbIterator.close();
// }
//
// @Override
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// @Override
// public Iterator<T> iterator() {
// if (iterated) {
// throw new IllegalStateException("Already iterated");
// }
// iterated = true;
// return this;
// }
//
// }
// Path: src/java/nxt/http/GetDGSPurchases.java
import nxt.DigitalGoodsStore;
import nxt.NxtException;
import nxt.db.DbIterator;
import nxt.db.FilteringIterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
package nxt.http;
public final class GetDGSPurchases extends APIServlet.APIRequestHandler {
static final GetDGSPurchases instance = new GetDGSPurchases();
private GetDGSPurchases() {
super(new APITag[] {APITag.DGS}, "seller", "buyer", "firstIndex", "lastIndex", "completed");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
long sellerId = ParameterParser.getSellerId(req);
long buyerId = ParameterParser.getBuyerId(req);
int firstIndex = ParameterParser.getFirstIndex(req);
int lastIndex = ParameterParser.getLastIndex(req);
final boolean completed = "true".equalsIgnoreCase(req.getParameter("completed"));
JSONObject response = new JSONObject();
JSONArray purchasesJSON = new JSONArray();
response.put("purchases", purchasesJSON);
if (sellerId == 0 && buyerId == 0) { | try (FilteringIterator<DigitalGoodsStore.Purchase> purchaseIterator = new FilteringIterator<>(DigitalGoodsStore.getAllPurchases(0, -1), |
BurstProject/burstcoin | src/java/nxt/BlockchainProcessor.java | // Path: src/java/nxt/db/DerivedDbTable.java
// public abstract class DerivedDbTable {
//
// protected final String table;
//
// protected DerivedDbTable(String table) {
// this.table = table;
// Nxt.getBlockchainProcessor().registerDerivedTable(this);
// }
//
// public void rollback(int height) {
// if (!Db.isInTransaction()) {
// throw new IllegalStateException("Not in transaction");
// }
// try (Connection con = Db.getConnection();
// PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
// pstmtDelete.setInt(1, height);
// pstmtDelete.executeUpdate();
// } catch (SQLException e) {
// throw new RuntimeException(e.toString(), e);
// }
// }
//
// public void truncate() {
// if (!Db.isInTransaction()) {
// throw new IllegalStateException("Not in transaction");
// }
// try (Connection con = Db.getConnection();
// Statement stmt = con.createStatement()) {
// stmt.executeUpdate("TRUNCATE TABLE " + table);
// } catch (SQLException e) {
// throw new RuntimeException(e.toString(), e);
// }
// }
//
// public void trim(int height) {
// //nothing to trim
// }
//
// }
| import nxt.db.DerivedDbTable;
import nxt.peer.Peer;
import nxt.util.Observable;
import org.json.simple.JSONObject;
import java.util.List; | package nxt;
public interface BlockchainProcessor extends Observable<Block,BlockchainProcessor.Event> {
public static enum Event {
BLOCK_PUSHED, BLOCK_POPPED, BLOCK_GENERATED, BLOCK_SCANNED,
RESCAN_BEGIN, RESCAN_END,
BEFORE_BLOCK_ACCEPT,
BEFORE_BLOCK_APPLY, AFTER_BLOCK_APPLY
}
Peer getLastBlockchainFeeder();
int getLastBlockchainFeederHeight();
boolean isScanning();
int getMinRollbackHeight();
void processPeerBlock(JSONObject request) throws NxtException;
void fullReset();
void scan(int height);
void forceScanAtStart();
void validateAtNextScan();
List<? extends Block> popOffTo(int height);
| // Path: src/java/nxt/db/DerivedDbTable.java
// public abstract class DerivedDbTable {
//
// protected final String table;
//
// protected DerivedDbTable(String table) {
// this.table = table;
// Nxt.getBlockchainProcessor().registerDerivedTable(this);
// }
//
// public void rollback(int height) {
// if (!Db.isInTransaction()) {
// throw new IllegalStateException("Not in transaction");
// }
// try (Connection con = Db.getConnection();
// PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
// pstmtDelete.setInt(1, height);
// pstmtDelete.executeUpdate();
// } catch (SQLException e) {
// throw new RuntimeException(e.toString(), e);
// }
// }
//
// public void truncate() {
// if (!Db.isInTransaction()) {
// throw new IllegalStateException("Not in transaction");
// }
// try (Connection con = Db.getConnection();
// Statement stmt = con.createStatement()) {
// stmt.executeUpdate("TRUNCATE TABLE " + table);
// } catch (SQLException e) {
// throw new RuntimeException(e.toString(), e);
// }
// }
//
// public void trim(int height) {
// //nothing to trim
// }
//
// }
// Path: src/java/nxt/BlockchainProcessor.java
import nxt.db.DerivedDbTable;
import nxt.peer.Peer;
import nxt.util.Observable;
import org.json.simple.JSONObject;
import java.util.List;
package nxt;
public interface BlockchainProcessor extends Observable<Block,BlockchainProcessor.Event> {
public static enum Event {
BLOCK_PUSHED, BLOCK_POPPED, BLOCK_GENERATED, BLOCK_SCANNED,
RESCAN_BEGIN, RESCAN_END,
BEFORE_BLOCK_ACCEPT,
BEFORE_BLOCK_APPLY, AFTER_BLOCK_APPLY
}
Peer getLastBlockchainFeeder();
int getLastBlockchainFeederHeight();
boolean isScanning();
int getMinRollbackHeight();
void processPeerBlock(JSONObject request) throws NxtException;
void fullReset();
void scan(int height);
void forceScanAtStart();
void validateAtNextScan();
List<? extends Block> popOffTo(int height);
| void registerDerivedTable(DerivedDbTable table); |
zsawyer/MumbleLink | mod/src/main/java/zsawyer/mods/mumblelink/Config.java | // Path: mod/src/main/java/zsawyer/mods/mumblelink/api/MumbleLink.java
// public interface MumbleLink extends Activateable, Debuggable {
// public final static @Nonnull String MOD_ID = "mumblelink";
//
// /**
// * the API instance which is used by this mod instance
// * registering at this api effectively registers your manipulators with the core MumbleLink mod
// *
// * @return mod's API instance
// */
// public MumbleLinkAPI getApi();
//
// /**
// * display name of the mod
// *
// * @return mod's name
// */
// public String getName();
//
// /**
// * version of the mod
// *
// * @return mod's version
// */
// public String getVersion();
// }
//
// Path: mod/src/main/java/zsawyer/mods/mumblelink/util/ConfigHelper.java
// public class ConfigHelper {
//
// /**
// * short-hand function to supplement the given comment with the values
// * supplied
// *
// * @param comment the comment to be supplemented
// * @param availableValues the values to be appended to the comment
// * @return the compound string result
// */
// public static String configComment(String comment, Object[] availableValues) {
// return comment + System.getProperty("line.separator") + "available values: "
// + Arrays.toString(availableValues);
// }
//
// /**
// * Short-hand function to get a {@link net.minecraftforge.common.ForgeConfigSpec.BooleanValue}, providing a comment, translation and
// * default value. The comment will be supplemented with possible values.
// *
// * @param builder a builder instance to work with
// * @param path an identifier for this key-value pair
// * @param comment a hint which will be written into the config file
// * @param translation the key for the translation string
// * @param defaultValue a default value to use if it wasn't set yet
// * @return the value read from config
// */
// public static ForgeConfigSpec.BooleanValue buildBoolean(ForgeConfigSpec.Builder builder, String path, String comment, String translation, boolean defaultValue) {
// return builder
// .comment(ConfigHelper.configComment(comment,
// new Boolean[]{true, false}))
// .translation(translation)
// .define(path, defaultValue);
// }
// }
| import org.apache.commons.lang3.tuple.Pair;
import zsawyer.mods.mumblelink.api.MumbleLink;
import zsawyer.mods.mumblelink.util.ConfigHelper;
import net.minecraftforge.common.ForgeConfigSpec; | /*
mod_MumbleLink - Positional Audio Communication for Minecraft with Mumble
Copyright 2011-2013 zsawyer (http://sourceforge.net/users/zsawyer)
This file is part of mod_MumbleLink
(http://sourceforge.net/projects/modmumblelink/).
mod_MumbleLink is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mod_MumbleLink is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with mod_MumbleLink. If not, see <http://www.gnu.org/licenses/>.
*/
package zsawyer.mods.mumblelink;
/**
* utility constants class of frequently used config strings
*
* @author zsawyer
*/
public class Config {
public static final ForgeConfigSpec SPEC;
/**
* the target Config to work with
*/
public static final Config CONFIG;
public static final String DEBUG_COMMENT = "whether this addon should do stuff"; | // Path: mod/src/main/java/zsawyer/mods/mumblelink/api/MumbleLink.java
// public interface MumbleLink extends Activateable, Debuggable {
// public final static @Nonnull String MOD_ID = "mumblelink";
//
// /**
// * the API instance which is used by this mod instance
// * registering at this api effectively registers your manipulators with the core MumbleLink mod
// *
// * @return mod's API instance
// */
// public MumbleLinkAPI getApi();
//
// /**
// * display name of the mod
// *
// * @return mod's name
// */
// public String getName();
//
// /**
// * version of the mod
// *
// * @return mod's version
// */
// public String getVersion();
// }
//
// Path: mod/src/main/java/zsawyer/mods/mumblelink/util/ConfigHelper.java
// public class ConfigHelper {
//
// /**
// * short-hand function to supplement the given comment with the values
// * supplied
// *
// * @param comment the comment to be supplemented
// * @param availableValues the values to be appended to the comment
// * @return the compound string result
// */
// public static String configComment(String comment, Object[] availableValues) {
// return comment + System.getProperty("line.separator") + "available values: "
// + Arrays.toString(availableValues);
// }
//
// /**
// * Short-hand function to get a {@link net.minecraftforge.common.ForgeConfigSpec.BooleanValue}, providing a comment, translation and
// * default value. The comment will be supplemented with possible values.
// *
// * @param builder a builder instance to work with
// * @param path an identifier for this key-value pair
// * @param comment a hint which will be written into the config file
// * @param translation the key for the translation string
// * @param defaultValue a default value to use if it wasn't set yet
// * @return the value read from config
// */
// public static ForgeConfigSpec.BooleanValue buildBoolean(ForgeConfigSpec.Builder builder, String path, String comment, String translation, boolean defaultValue) {
// return builder
// .comment(ConfigHelper.configComment(comment,
// new Boolean[]{true, false}))
// .translation(translation)
// .define(path, defaultValue);
// }
// }
// Path: mod/src/main/java/zsawyer/mods/mumblelink/Config.java
import org.apache.commons.lang3.tuple.Pair;
import zsawyer.mods.mumblelink.api.MumbleLink;
import zsawyer.mods.mumblelink.util.ConfigHelper;
import net.minecraftforge.common.ForgeConfigSpec;
/*
mod_MumbleLink - Positional Audio Communication for Minecraft with Mumble
Copyright 2011-2013 zsawyer (http://sourceforge.net/users/zsawyer)
This file is part of mod_MumbleLink
(http://sourceforge.net/projects/modmumblelink/).
mod_MumbleLink is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mod_MumbleLink is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with mod_MumbleLink. If not, see <http://www.gnu.org/licenses/>.
*/
package zsawyer.mods.mumblelink;
/**
* utility constants class of frequently used config strings
*
* @author zsawyer
*/
public class Config {
public static final ForgeConfigSpec SPEC;
/**
* the target Config to work with
*/
public static final Config CONFIG;
public static final String DEBUG_COMMENT = "whether this addon should do stuff"; | public static final String DEBUG_TRANSLATION = MumbleLink.MOD_ID + ".configgui.debug"; |
zsawyer/MumbleLink | mod/src/main/java/zsawyer/mods/mumblelink/Config.java | // Path: mod/src/main/java/zsawyer/mods/mumblelink/api/MumbleLink.java
// public interface MumbleLink extends Activateable, Debuggable {
// public final static @Nonnull String MOD_ID = "mumblelink";
//
// /**
// * the API instance which is used by this mod instance
// * registering at this api effectively registers your manipulators with the core MumbleLink mod
// *
// * @return mod's API instance
// */
// public MumbleLinkAPI getApi();
//
// /**
// * display name of the mod
// *
// * @return mod's name
// */
// public String getName();
//
// /**
// * version of the mod
// *
// * @return mod's version
// */
// public String getVersion();
// }
//
// Path: mod/src/main/java/zsawyer/mods/mumblelink/util/ConfigHelper.java
// public class ConfigHelper {
//
// /**
// * short-hand function to supplement the given comment with the values
// * supplied
// *
// * @param comment the comment to be supplemented
// * @param availableValues the values to be appended to the comment
// * @return the compound string result
// */
// public static String configComment(String comment, Object[] availableValues) {
// return comment + System.getProperty("line.separator") + "available values: "
// + Arrays.toString(availableValues);
// }
//
// /**
// * Short-hand function to get a {@link net.minecraftforge.common.ForgeConfigSpec.BooleanValue}, providing a comment, translation and
// * default value. The comment will be supplemented with possible values.
// *
// * @param builder a builder instance to work with
// * @param path an identifier for this key-value pair
// * @param comment a hint which will be written into the config file
// * @param translation the key for the translation string
// * @param defaultValue a default value to use if it wasn't set yet
// * @return the value read from config
// */
// public static ForgeConfigSpec.BooleanValue buildBoolean(ForgeConfigSpec.Builder builder, String path, String comment, String translation, boolean defaultValue) {
// return builder
// .comment(ConfigHelper.configComment(comment,
// new Boolean[]{true, false}))
// .translation(translation)
// .define(path, defaultValue);
// }
// }
| import org.apache.commons.lang3.tuple.Pair;
import zsawyer.mods.mumblelink.api.MumbleLink;
import zsawyer.mods.mumblelink.util.ConfigHelper;
import net.minecraftforge.common.ForgeConfigSpec; | /*
mod_MumbleLink - Positional Audio Communication for Minecraft with Mumble
Copyright 2011-2013 zsawyer (http://sourceforge.net/users/zsawyer)
This file is part of mod_MumbleLink
(http://sourceforge.net/projects/modmumblelink/).
mod_MumbleLink is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mod_MumbleLink is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with mod_MumbleLink. If not, see <http://www.gnu.org/licenses/>.
*/
package zsawyer.mods.mumblelink;
/**
* utility constants class of frequently used config strings
*
* @author zsawyer
*/
public class Config {
public static final ForgeConfigSpec SPEC;
/**
* the target Config to work with
*/
public static final Config CONFIG;
public static final String DEBUG_COMMENT = "whether this addon should do stuff";
public static final String DEBUG_TRANSLATION = MumbleLink.MOD_ID + ".configgui.debug";
public static final String DEBUG_PATH = "debug";
public static final boolean DEBUG_DEFAULT_VALUE = false;
public static final String ENABLED_COMMENT = "whether this addon should do stuff";
public static final String ENABLED_TRANSLATION = MumbleLink.MOD_ID + ".configgui.enabled";
public static final String ENABLED_PATH = "enabled";
public static final boolean ENABLED_DEFAULT_VALUE = true;
public final ForgeConfigSpec.BooleanValue debug;
public final ForgeConfigSpec.BooleanValue enabled;
static {
final Pair<Config, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Config::new);
SPEC = specPair.getRight();
CONFIG = specPair.getLeft();
}
Config(ForgeConfigSpec.Builder builder) {
builder.comment("Client only settings")
.push("client");
| // Path: mod/src/main/java/zsawyer/mods/mumblelink/api/MumbleLink.java
// public interface MumbleLink extends Activateable, Debuggable {
// public final static @Nonnull String MOD_ID = "mumblelink";
//
// /**
// * the API instance which is used by this mod instance
// * registering at this api effectively registers your manipulators with the core MumbleLink mod
// *
// * @return mod's API instance
// */
// public MumbleLinkAPI getApi();
//
// /**
// * display name of the mod
// *
// * @return mod's name
// */
// public String getName();
//
// /**
// * version of the mod
// *
// * @return mod's version
// */
// public String getVersion();
// }
//
// Path: mod/src/main/java/zsawyer/mods/mumblelink/util/ConfigHelper.java
// public class ConfigHelper {
//
// /**
// * short-hand function to supplement the given comment with the values
// * supplied
// *
// * @param comment the comment to be supplemented
// * @param availableValues the values to be appended to the comment
// * @return the compound string result
// */
// public static String configComment(String comment, Object[] availableValues) {
// return comment + System.getProperty("line.separator") + "available values: "
// + Arrays.toString(availableValues);
// }
//
// /**
// * Short-hand function to get a {@link net.minecraftforge.common.ForgeConfigSpec.BooleanValue}, providing a comment, translation and
// * default value. The comment will be supplemented with possible values.
// *
// * @param builder a builder instance to work with
// * @param path an identifier for this key-value pair
// * @param comment a hint which will be written into the config file
// * @param translation the key for the translation string
// * @param defaultValue a default value to use if it wasn't set yet
// * @return the value read from config
// */
// public static ForgeConfigSpec.BooleanValue buildBoolean(ForgeConfigSpec.Builder builder, String path, String comment, String translation, boolean defaultValue) {
// return builder
// .comment(ConfigHelper.configComment(comment,
// new Boolean[]{true, false}))
// .translation(translation)
// .define(path, defaultValue);
// }
// }
// Path: mod/src/main/java/zsawyer/mods/mumblelink/Config.java
import org.apache.commons.lang3.tuple.Pair;
import zsawyer.mods.mumblelink.api.MumbleLink;
import zsawyer.mods.mumblelink.util.ConfigHelper;
import net.minecraftforge.common.ForgeConfigSpec;
/*
mod_MumbleLink - Positional Audio Communication for Minecraft with Mumble
Copyright 2011-2013 zsawyer (http://sourceforge.net/users/zsawyer)
This file is part of mod_MumbleLink
(http://sourceforge.net/projects/modmumblelink/).
mod_MumbleLink is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mod_MumbleLink is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with mod_MumbleLink. If not, see <http://www.gnu.org/licenses/>.
*/
package zsawyer.mods.mumblelink;
/**
* utility constants class of frequently used config strings
*
* @author zsawyer
*/
public class Config {
public static final ForgeConfigSpec SPEC;
/**
* the target Config to work with
*/
public static final Config CONFIG;
public static final String DEBUG_COMMENT = "whether this addon should do stuff";
public static final String DEBUG_TRANSLATION = MumbleLink.MOD_ID + ".configgui.debug";
public static final String DEBUG_PATH = "debug";
public static final boolean DEBUG_DEFAULT_VALUE = false;
public static final String ENABLED_COMMENT = "whether this addon should do stuff";
public static final String ENABLED_TRANSLATION = MumbleLink.MOD_ID + ".configgui.enabled";
public static final String ENABLED_PATH = "enabled";
public static final boolean ENABLED_DEFAULT_VALUE = true;
public final ForgeConfigSpec.BooleanValue debug;
public final ForgeConfigSpec.BooleanValue enabled;
static {
final Pair<Config, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Config::new);
SPEC = specPair.getRight();
CONFIG = specPair.getLeft();
}
Config(ForgeConfigSpec.Builder builder) {
builder.comment("Client only settings")
.push("client");
| debug = ConfigHelper.buildBoolean(builder, DEBUG_PATH, DEBUG_COMMENT, DEBUG_TRANSLATION, DEBUG_DEFAULT_VALUE); |
zsawyer/MumbleLink | mod/src/main/java/zsawyer/mods/mumblelink/addons/pa/es/Config.java | // Path: mod/src/main/java/zsawyer/mods/mumblelink/util/ConfigHelper.java
// public class ConfigHelper {
//
// /**
// * short-hand function to supplement the given comment with the values
// * supplied
// *
// * @param comment the comment to be supplemented
// * @param availableValues the values to be appended to the comment
// * @return the compound string result
// */
// public static String configComment(String comment, Object[] availableValues) {
// return comment + System.getProperty("line.separator") + "available values: "
// + Arrays.toString(availableValues);
// }
//
// /**
// * Short-hand function to get a {@link net.minecraftforge.common.ForgeConfigSpec.BooleanValue}, providing a comment, translation and
// * default value. The comment will be supplemented with possible values.
// *
// * @param builder a builder instance to work with
// * @param path an identifier for this key-value pair
// * @param comment a hint which will be written into the config file
// * @param translation the key for the translation string
// * @param defaultValue a default value to use if it wasn't set yet
// * @return the value read from config
// */
// public static ForgeConfigSpec.BooleanValue buildBoolean(ForgeConfigSpec.Builder builder, String path, String comment, String translation, boolean defaultValue) {
// return builder
// .comment(ConfigHelper.configComment(comment,
// new Boolean[]{true, false}))
// .translation(translation)
// .define(path, defaultValue);
// }
// }
| import org.apache.commons.lang3.tuple.Pair;
import zsawyer.mods.mumblelink.util.ConfigHelper;
import net.minecraftforge.common.ForgeConfigSpec; | /*
mod_MumbleLink - Positional Audio Communication for Minecraft with Mumble
Copyright 2011-2013 zsawyer (http://sourceforge.net/users/zsawyer)
This file is part of mod_MumbleLink
(http://sourceforge.net/projects/modmumblelink/).
mod_MumbleLink is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mod_MumbleLink is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with mod_MumbleLink. If not, see <http://www.gnu.org/licenses/>.
*/
package zsawyer.mods.mumblelink.addons.pa.es;
/**
* utility constants class of frequently used config strings
*
* @author zsawyer
*/
public class Config {
public static final ForgeConfigSpec SPEC;
/**
* the target Config to work with
*/
public static Config CONFIG;
public static final String DEBUG_COMMENT = "whether this addon should do stuff";
public static final String DEBUG_TRANSLATION = ExtendedPASupport.MOD_ID + ".configgui.debug";
public static final String DEBUG_PATH = "debug";
public static final boolean DEBUG_DEFAULT_VALUE = false;
public static final String ENABLED_COMMENT = "whether this addon should do stuff";
public static final String ENABLED_TRANSLATION = ExtendedPASupport.MOD_ID + ".configgui.enabled";
public static final String ENABLED_PATH = "enabled";
public static final boolean ENABLED_DEFAULT_VALUE = true;
public final ForgeConfigSpec.BooleanValue debug;
public final ForgeConfigSpec.BooleanValue enabled;
static {
final Pair<Config, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Config::new);
SPEC = specPair.getRight();
CONFIG = specPair.getLeft();
}
Config(ForgeConfigSpec.Builder builder) {
builder.comment("Client only settings")
.push("client");
| // Path: mod/src/main/java/zsawyer/mods/mumblelink/util/ConfigHelper.java
// public class ConfigHelper {
//
// /**
// * short-hand function to supplement the given comment with the values
// * supplied
// *
// * @param comment the comment to be supplemented
// * @param availableValues the values to be appended to the comment
// * @return the compound string result
// */
// public static String configComment(String comment, Object[] availableValues) {
// return comment + System.getProperty("line.separator") + "available values: "
// + Arrays.toString(availableValues);
// }
//
// /**
// * Short-hand function to get a {@link net.minecraftforge.common.ForgeConfigSpec.BooleanValue}, providing a comment, translation and
// * default value. The comment will be supplemented with possible values.
// *
// * @param builder a builder instance to work with
// * @param path an identifier for this key-value pair
// * @param comment a hint which will be written into the config file
// * @param translation the key for the translation string
// * @param defaultValue a default value to use if it wasn't set yet
// * @return the value read from config
// */
// public static ForgeConfigSpec.BooleanValue buildBoolean(ForgeConfigSpec.Builder builder, String path, String comment, String translation, boolean defaultValue) {
// return builder
// .comment(ConfigHelper.configComment(comment,
// new Boolean[]{true, false}))
// .translation(translation)
// .define(path, defaultValue);
// }
// }
// Path: mod/src/main/java/zsawyer/mods/mumblelink/addons/pa/es/Config.java
import org.apache.commons.lang3.tuple.Pair;
import zsawyer.mods.mumblelink.util.ConfigHelper;
import net.minecraftforge.common.ForgeConfigSpec;
/*
mod_MumbleLink - Positional Audio Communication for Minecraft with Mumble
Copyright 2011-2013 zsawyer (http://sourceforge.net/users/zsawyer)
This file is part of mod_MumbleLink
(http://sourceforge.net/projects/modmumblelink/).
mod_MumbleLink is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
mod_MumbleLink is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with mod_MumbleLink. If not, see <http://www.gnu.org/licenses/>.
*/
package zsawyer.mods.mumblelink.addons.pa.es;
/**
* utility constants class of frequently used config strings
*
* @author zsawyer
*/
public class Config {
public static final ForgeConfigSpec SPEC;
/**
* the target Config to work with
*/
public static Config CONFIG;
public static final String DEBUG_COMMENT = "whether this addon should do stuff";
public static final String DEBUG_TRANSLATION = ExtendedPASupport.MOD_ID + ".configgui.debug";
public static final String DEBUG_PATH = "debug";
public static final boolean DEBUG_DEFAULT_VALUE = false;
public static final String ENABLED_COMMENT = "whether this addon should do stuff";
public static final String ENABLED_TRANSLATION = ExtendedPASupport.MOD_ID + ".configgui.enabled";
public static final String ENABLED_PATH = "enabled";
public static final boolean ENABLED_DEFAULT_VALUE = true;
public final ForgeConfigSpec.BooleanValue debug;
public final ForgeConfigSpec.BooleanValue enabled;
static {
final Pair<Config, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Config::new);
SPEC = specPair.getRight();
CONFIG = specPair.getLeft();
}
Config(ForgeConfigSpec.Builder builder) {
builder.comment("Client only settings")
.push("client");
| debug = ConfigHelper.buildBoolean(builder, DEBUG_PATH, DEBUG_COMMENT, DEBUG_TRANSLATION, DEBUG_DEFAULT_VALUE); |
Karumi/MarvelApiClientAndroid | MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/CharactersQuery.java | // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/utils/DateUtil.java
// public class DateUtil {
//
// private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
//
// public static String parseDate(Date date) {
// SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
// return format.format(date);
// }
// }
| import com.karumi.marvelapiclient.utils.DateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | String plainComics = convertToList(comics);
String plainEvents = convertToList(events);
String plainSeries = convertToList(series);
String plainStories = convertToList(stories);
String plainOrderBy = convertOrderBy(orderBy, orderByAscendant);
return new CharactersQuery(name, nameStartWith, plainModifedSince, plainComics, plainSeries,
plainEvents, plainStories, plainOrderBy, limit, offset);
}
private void checkLimit(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must be bigger than zero");
}
if (limit > MAX_SIZE) {
throw new IllegalArgumentException("limit must be smaller than 100");
}
}
private void checkNull(List<Integer> list) {
if (list == null) {
throw new IllegalArgumentException("the collection can not be null");
}
}
private String convertDate(Date date) {
if (date == null) {
return null;
} | // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/utils/DateUtil.java
// public class DateUtil {
//
// private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
//
// public static String parseDate(Date date) {
// SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
// return format.format(date);
// }
// }
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/CharactersQuery.java
import com.karumi.marvelapiclient.utils.DateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
String plainComics = convertToList(comics);
String plainEvents = convertToList(events);
String plainSeries = convertToList(series);
String plainStories = convertToList(stories);
String plainOrderBy = convertOrderBy(orderBy, orderByAscendant);
return new CharactersQuery(name, nameStartWith, plainModifedSince, plainComics, plainSeries,
plainEvents, plainStories, plainOrderBy, limit, offset);
}
private void checkLimit(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must be bigger than zero");
}
if (limit > MAX_SIZE) {
throw new IllegalArgumentException("limit must be smaller than 100");
}
}
private void checkNull(List<Integer> list) {
if (list == null) {
throw new IllegalArgumentException("the collection can not be null");
}
}
private String convertDate(Date date) {
if (date == null) {
return null;
} | return DateUtil.parseDate(date); |
Karumi/MarvelApiClientAndroid | MarvelApiClient/src/test/java/com/karumi/marvelapiclient/ApiClientTest.java | // Path: MarvelApiClient/src/test/java/com/karumi/marvelapiclient/extensions/FileExtensions.java
// public final class FileExtensions {
//
// private static final String UTF_8 = "UTF-8";
//
// private FileExtensions() {
// }
//
// public static String getStringFromFile(Class clazz, String filePath) throws IOException {
// ClassLoader classLoader = clazz.getClassLoader();
// File file = new File(classLoader.getResource("resources/" + filePath).getFile());
// return FileUtils.readFileToString(file, UTF_8);
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/MarvelResponse.java
// public class MarvelResponse<T> {
// @SerializedName("code") private int code;
// @SerializedName("status") private String status;
// @SerializedName("copyright") private String copyright;
// @SerializedName("attributionText") private String attributionText;
// @SerializedName("attributionHTML") private String getAttributionHtml;
// @SerializedName("etag") private String etag;
//
// @SerializedName("data") private T response;
//
// public MarvelResponse() {
// }
//
// public MarvelResponse(MarvelResponse marvelResponse) {
// code = marvelResponse.getCode();
// status = marvelResponse.getStatus();
// copyright = marvelResponse.getCopyright();
// attributionText = marvelResponse.getAttributionText();
// getAttributionHtml = marvelResponse.getGetAttributionHtml();
// etag = marvelResponse.getEtag();
// }
//
// public int getCode() {
// return code;
// }
//
// public String getStatus() {
// return status;
// }
//
// public String getCopyright() {
// return copyright;
// }
//
// public String getAttributionText() {
// return attributionText;
// }
//
// public String getGetAttributionHtml() {
// return getAttributionHtml;
// }
//
// public T getResponse() {
// return response;
// }
//
// public String getEtag() {
// return etag;
// }
//
// @Override public String toString() {
// return "MarvelResponse{"
// + "code="
// + code
// + ", status='"
// + status
// + '\''
// + ", copyright='"
// + copyright
// + '\''
// + ", attributionText='"
// + attributionText
// + '\''
// + ", getAttributionHtml='"
// + getAttributionHtml
// + '\''
// + ", etag='"
// + etag
// + '\''
// + ", response="
// + response
// + '}';
// }
//
// public void setResponse(T response) {
// this.response = response;
// }
// }
| import com.karumi.marvelapiclient.extensions.FileExtensions;
import com.karumi.marvelapiclient.model.MarvelResponse;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.io.IOException;
import org.hamcrest.core.StringContains;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertEquals; | /*
* Copyright (C) 2015 Karumi.
* 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.karumi.marvelapiclient;
public class ApiClientTest {
protected static final String ANY_TIME_ZONE = "PST";
private static final int OK_CODE = 200;
private MockWebServer server;
@Before public void setUp() throws Exception {
System.setProperty("user.timezone", ANY_TIME_ZONE);
MockitoAnnotations.initMocks(this);
this.server = new MockWebServer();
this.server.start();
}
@After public void tearDown() throws Exception {
server.shutdown();
}
protected void enqueueMockResponse() throws IOException {
enqueueMockResponse(OK_CODE);
}
protected void enqueueMockResponse(int code) throws IOException {
enqueueMockResponse(code, "{}");
}
protected void enqueueMockResponse(int code, String response) throws IOException {
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(code);
mockResponse.setBody(response);
server.enqueue(mockResponse);
}
protected void enqueueMockResponse(String fileName) throws IOException { | // Path: MarvelApiClient/src/test/java/com/karumi/marvelapiclient/extensions/FileExtensions.java
// public final class FileExtensions {
//
// private static final String UTF_8 = "UTF-8";
//
// private FileExtensions() {
// }
//
// public static String getStringFromFile(Class clazz, String filePath) throws IOException {
// ClassLoader classLoader = clazz.getClassLoader();
// File file = new File(classLoader.getResource("resources/" + filePath).getFile());
// return FileUtils.readFileToString(file, UTF_8);
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/MarvelResponse.java
// public class MarvelResponse<T> {
// @SerializedName("code") private int code;
// @SerializedName("status") private String status;
// @SerializedName("copyright") private String copyright;
// @SerializedName("attributionText") private String attributionText;
// @SerializedName("attributionHTML") private String getAttributionHtml;
// @SerializedName("etag") private String etag;
//
// @SerializedName("data") private T response;
//
// public MarvelResponse() {
// }
//
// public MarvelResponse(MarvelResponse marvelResponse) {
// code = marvelResponse.getCode();
// status = marvelResponse.getStatus();
// copyright = marvelResponse.getCopyright();
// attributionText = marvelResponse.getAttributionText();
// getAttributionHtml = marvelResponse.getGetAttributionHtml();
// etag = marvelResponse.getEtag();
// }
//
// public int getCode() {
// return code;
// }
//
// public String getStatus() {
// return status;
// }
//
// public String getCopyright() {
// return copyright;
// }
//
// public String getAttributionText() {
// return attributionText;
// }
//
// public String getGetAttributionHtml() {
// return getAttributionHtml;
// }
//
// public T getResponse() {
// return response;
// }
//
// public String getEtag() {
// return etag;
// }
//
// @Override public String toString() {
// return "MarvelResponse{"
// + "code="
// + code
// + ", status='"
// + status
// + '\''
// + ", copyright='"
// + copyright
// + '\''
// + ", attributionText='"
// + attributionText
// + '\''
// + ", getAttributionHtml='"
// + getAttributionHtml
// + '\''
// + ", etag='"
// + etag
// + '\''
// + ", response="
// + response
// + '}';
// }
//
// public void setResponse(T response) {
// this.response = response;
// }
// }
// Path: MarvelApiClient/src/test/java/com/karumi/marvelapiclient/ApiClientTest.java
import com.karumi.marvelapiclient.extensions.FileExtensions;
import com.karumi.marvelapiclient.model.MarvelResponse;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.io.IOException;
import org.hamcrest.core.StringContains;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertEquals;
/*
* Copyright (C) 2015 Karumi.
* 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.karumi.marvelapiclient;
public class ApiClientTest {
protected static final String ANY_TIME_ZONE = "PST";
private static final int OK_CODE = 200;
private MockWebServer server;
@Before public void setUp() throws Exception {
System.setProperty("user.timezone", ANY_TIME_ZONE);
MockitoAnnotations.initMocks(this);
this.server = new MockWebServer();
this.server.start();
}
@After public void tearDown() throws Exception {
server.shutdown();
}
protected void enqueueMockResponse() throws IOException {
enqueueMockResponse(OK_CODE);
}
protected void enqueueMockResponse(int code) throws IOException {
enqueueMockResponse(code, "{}");
}
protected void enqueueMockResponse(int code, String response) throws IOException {
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(code);
mockResponse.setBody(response);
server.enqueue(mockResponse);
}
protected void enqueueMockResponse(String fileName) throws IOException { | String body = FileExtensions.getStringFromFile(getClass(), fileName); |
Karumi/MarvelApiClientAndroid | MarvelApiClient/src/test/java/com/karumi/marvelapiclient/ApiClientTest.java | // Path: MarvelApiClient/src/test/java/com/karumi/marvelapiclient/extensions/FileExtensions.java
// public final class FileExtensions {
//
// private static final String UTF_8 = "UTF-8";
//
// private FileExtensions() {
// }
//
// public static String getStringFromFile(Class clazz, String filePath) throws IOException {
// ClassLoader classLoader = clazz.getClassLoader();
// File file = new File(classLoader.getResource("resources/" + filePath).getFile());
// return FileUtils.readFileToString(file, UTF_8);
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/MarvelResponse.java
// public class MarvelResponse<T> {
// @SerializedName("code") private int code;
// @SerializedName("status") private String status;
// @SerializedName("copyright") private String copyright;
// @SerializedName("attributionText") private String attributionText;
// @SerializedName("attributionHTML") private String getAttributionHtml;
// @SerializedName("etag") private String etag;
//
// @SerializedName("data") private T response;
//
// public MarvelResponse() {
// }
//
// public MarvelResponse(MarvelResponse marvelResponse) {
// code = marvelResponse.getCode();
// status = marvelResponse.getStatus();
// copyright = marvelResponse.getCopyright();
// attributionText = marvelResponse.getAttributionText();
// getAttributionHtml = marvelResponse.getGetAttributionHtml();
// etag = marvelResponse.getEtag();
// }
//
// public int getCode() {
// return code;
// }
//
// public String getStatus() {
// return status;
// }
//
// public String getCopyright() {
// return copyright;
// }
//
// public String getAttributionText() {
// return attributionText;
// }
//
// public String getGetAttributionHtml() {
// return getAttributionHtml;
// }
//
// public T getResponse() {
// return response;
// }
//
// public String getEtag() {
// return etag;
// }
//
// @Override public String toString() {
// return "MarvelResponse{"
// + "code="
// + code
// + ", status='"
// + status
// + '\''
// + ", copyright='"
// + copyright
// + '\''
// + ", attributionText='"
// + attributionText
// + '\''
// + ", getAttributionHtml='"
// + getAttributionHtml
// + '\''
// + ", etag='"
// + etag
// + '\''
// + ", response="
// + response
// + '}';
// }
//
// public void setResponse(T response) {
// this.response = response;
// }
// }
| import com.karumi.marvelapiclient.extensions.FileExtensions;
import com.karumi.marvelapiclient.model.MarvelResponse;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.io.IOException;
import org.hamcrest.core.StringContains;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertEquals; | }
protected void enqueueMockResponse(int code, String response) throws IOException {
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(code);
mockResponse.setBody(response);
server.enqueue(mockResponse);
}
protected void enqueueMockResponse(String fileName) throws IOException {
String body = FileExtensions.getStringFromFile(getClass(), fileName);
MockResponse response = new MockResponse();
response.setResponseCode(OK_CODE);
response.setBody(body);
server.enqueue(response);
}
protected void assertRequestSentTo(String url) throws InterruptedException {
RecordedRequest request = server.takeRequest();
assertEquals(url, request.getPath());
}
protected void assertRequestSentToContains(String... paths) throws InterruptedException {
RecordedRequest request = server.takeRequest();
for (String path : paths) {
Assert.assertThat(request.getPath(), StringContains.containsString(path));
}
}
| // Path: MarvelApiClient/src/test/java/com/karumi/marvelapiclient/extensions/FileExtensions.java
// public final class FileExtensions {
//
// private static final String UTF_8 = "UTF-8";
//
// private FileExtensions() {
// }
//
// public static String getStringFromFile(Class clazz, String filePath) throws IOException {
// ClassLoader classLoader = clazz.getClassLoader();
// File file = new File(classLoader.getResource("resources/" + filePath).getFile());
// return FileUtils.readFileToString(file, UTF_8);
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/MarvelResponse.java
// public class MarvelResponse<T> {
// @SerializedName("code") private int code;
// @SerializedName("status") private String status;
// @SerializedName("copyright") private String copyright;
// @SerializedName("attributionText") private String attributionText;
// @SerializedName("attributionHTML") private String getAttributionHtml;
// @SerializedName("etag") private String etag;
//
// @SerializedName("data") private T response;
//
// public MarvelResponse() {
// }
//
// public MarvelResponse(MarvelResponse marvelResponse) {
// code = marvelResponse.getCode();
// status = marvelResponse.getStatus();
// copyright = marvelResponse.getCopyright();
// attributionText = marvelResponse.getAttributionText();
// getAttributionHtml = marvelResponse.getGetAttributionHtml();
// etag = marvelResponse.getEtag();
// }
//
// public int getCode() {
// return code;
// }
//
// public String getStatus() {
// return status;
// }
//
// public String getCopyright() {
// return copyright;
// }
//
// public String getAttributionText() {
// return attributionText;
// }
//
// public String getGetAttributionHtml() {
// return getAttributionHtml;
// }
//
// public T getResponse() {
// return response;
// }
//
// public String getEtag() {
// return etag;
// }
//
// @Override public String toString() {
// return "MarvelResponse{"
// + "code="
// + code
// + ", status='"
// + status
// + '\''
// + ", copyright='"
// + copyright
// + '\''
// + ", attributionText='"
// + attributionText
// + '\''
// + ", getAttributionHtml='"
// + getAttributionHtml
// + '\''
// + ", etag='"
// + etag
// + '\''
// + ", response="
// + response
// + '}';
// }
//
// public void setResponse(T response) {
// this.response = response;
// }
// }
// Path: MarvelApiClient/src/test/java/com/karumi/marvelapiclient/ApiClientTest.java
import com.karumi.marvelapiclient.extensions.FileExtensions;
import com.karumi.marvelapiclient.model.MarvelResponse;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import com.squareup.okhttp.mockwebserver.RecordedRequest;
import java.io.IOException;
import org.hamcrest.core.StringContains;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertEquals;
}
protected void enqueueMockResponse(int code, String response) throws IOException {
MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(code);
mockResponse.setBody(response);
server.enqueue(mockResponse);
}
protected void enqueueMockResponse(String fileName) throws IOException {
String body = FileExtensions.getStringFromFile(getClass(), fileName);
MockResponse response = new MockResponse();
response.setResponseCode(OK_CODE);
response.setBody(body);
server.enqueue(response);
}
protected void assertRequestSentTo(String url) throws InterruptedException {
RecordedRequest request = server.takeRequest();
assertEquals(url, request.getPath());
}
protected void assertRequestSentToContains(String... paths) throws InterruptedException {
RecordedRequest request = server.takeRequest();
for (String path : paths) {
Assert.assertThat(request.getPath(), StringContains.containsString(path));
}
}
| protected <T> void assertBasicMarvelResponse(MarvelResponse<T> marvelResponse) { |
Karumi/MarvelApiClientAndroid | MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/SeriesQuery.java | // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/utils/DateUtil.java
// public class DateUtil {
//
// private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
//
// public static String parseDate(Date date) {
// SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
// return format.format(date);
// }
// }
| import com.karumi.marvelapiclient.utils.DateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | String storiesAsString = convertToList(stories);
String orderByAsString = convertOrderBy(orderBy, orderByAscendant);
String containsAsString = (contains != null) ? contains.toString() : null;
String seriesTypeAsString = (seriesType != null) ? seriesType.toString() : null;
return new SeriesQuery(title, titleStartsWith, startYear, modifiedSinceAsString,
comicsAsString, storiesAsString, eventsAsString, creatorsAsString, charactersAsString,
orderByAsString, seriesTypeAsString, containsAsString, limit, offset);
}
private void checkLimit(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must be bigger than zero");
}
if (limit > MAX_SIZE) {
throw new IllegalArgumentException("limit must be smaller than 100");
}
}
private void checkNotNull(Object object) {
if (object == null) {
throw new IllegalArgumentException("the argument can not be null");
}
}
private String convertDate(Date date) {
if (date == null) {
return null;
} | // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/utils/DateUtil.java
// public class DateUtil {
//
// private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
//
// public static String parseDate(Date date) {
// SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
// return format.format(date);
// }
// }
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/SeriesQuery.java
import com.karumi.marvelapiclient.utils.DateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
String storiesAsString = convertToList(stories);
String orderByAsString = convertOrderBy(orderBy, orderByAscendant);
String containsAsString = (contains != null) ? contains.toString() : null;
String seriesTypeAsString = (seriesType != null) ? seriesType.toString() : null;
return new SeriesQuery(title, titleStartsWith, startYear, modifiedSinceAsString,
comicsAsString, storiesAsString, eventsAsString, creatorsAsString, charactersAsString,
orderByAsString, seriesTypeAsString, containsAsString, limit, offset);
}
private void checkLimit(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must be bigger than zero");
}
if (limit > MAX_SIZE) {
throw new IllegalArgumentException("limit must be smaller than 100");
}
}
private void checkNotNull(Object object) {
if (object == null) {
throw new IllegalArgumentException("the argument can not be null");
}
}
private String convertDate(Date date) {
if (date == null) {
return null;
} | return DateUtil.parseDate(date); |
Karumi/MarvelApiClientAndroid | MarvelApiClient/src/main/java/com/karumi/marvelapiclient/SeriesApiRest.java | // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/ComicsDto.java
// public class ComicsDto extends MarvelCollection<ComicDto> {
//
// public List<ComicDto> getComics() {
// return getResults();
// }
//
// @Override public String toString() {
// return "CharactersDto{"
// + "offset="
// + getOffset()
// + ", limit="
// + getLimit()
// + ", total="
// + getTotal()
// + ", count="
// + getCount()
// + ", characters="
// + getComics().toString()
// + '}';
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/MarvelResponse.java
// public class MarvelResponse<T> {
// @SerializedName("code") private int code;
// @SerializedName("status") private String status;
// @SerializedName("copyright") private String copyright;
// @SerializedName("attributionText") private String attributionText;
// @SerializedName("attributionHTML") private String getAttributionHtml;
// @SerializedName("etag") private String etag;
//
// @SerializedName("data") private T response;
//
// public MarvelResponse() {
// }
//
// public MarvelResponse(MarvelResponse marvelResponse) {
// code = marvelResponse.getCode();
// status = marvelResponse.getStatus();
// copyright = marvelResponse.getCopyright();
// attributionText = marvelResponse.getAttributionText();
// getAttributionHtml = marvelResponse.getGetAttributionHtml();
// etag = marvelResponse.getEtag();
// }
//
// public int getCode() {
// return code;
// }
//
// public String getStatus() {
// return status;
// }
//
// public String getCopyright() {
// return copyright;
// }
//
// public String getAttributionText() {
// return attributionText;
// }
//
// public String getGetAttributionHtml() {
// return getAttributionHtml;
// }
//
// public T getResponse() {
// return response;
// }
//
// public String getEtag() {
// return etag;
// }
//
// @Override public String toString() {
// return "MarvelResponse{"
// + "code="
// + code
// + ", status='"
// + status
// + '\''
// + ", copyright='"
// + copyright
// + '\''
// + ", attributionText='"
// + attributionText
// + '\''
// + ", getAttributionHtml='"
// + getAttributionHtml
// + '\''
// + ", etag='"
// + etag
// + '\''
// + ", response="
// + response
// + '}';
// }
//
// public void setResponse(T response) {
// this.response = response;
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/SeriesCollectionDto.java
// public class SeriesCollectionDto extends MarvelCollection<SeriesDto> {
//
// public List<SeriesDto> getSeries() {
// return getResults();
// }
//
// @Override public String toString() {
// return "CharactersDto{"
// + "offset="
// + getOffset()
// + ", limit="
// + getLimit()
// + ", total="
// + getTotal()
// + ", count="
// + getCount()
// + ", characters="
// + getSeries().toString()
// + '}';
// }
// }
| import com.karumi.marvelapiclient.model.ComicsDto;
import com.karumi.marvelapiclient.model.MarvelResponse;
import com.karumi.marvelapiclient.model.SeriesCollectionDto;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.QueryMap; | /*
* Copyright (C) 2015 Karumi.
* 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.karumi.marvelapiclient;
interface SeriesApiRest {
@GET("series") Call<MarvelResponse<SeriesCollectionDto>> getSeries(
@QueryMap Map<String, Object> seriesFilter);
@GET("series/{id}") Call<MarvelResponse<SeriesCollectionDto>> getSerie(
@Path("id") String serieId);
| // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/ComicsDto.java
// public class ComicsDto extends MarvelCollection<ComicDto> {
//
// public List<ComicDto> getComics() {
// return getResults();
// }
//
// @Override public String toString() {
// return "CharactersDto{"
// + "offset="
// + getOffset()
// + ", limit="
// + getLimit()
// + ", total="
// + getTotal()
// + ", count="
// + getCount()
// + ", characters="
// + getComics().toString()
// + '}';
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/MarvelResponse.java
// public class MarvelResponse<T> {
// @SerializedName("code") private int code;
// @SerializedName("status") private String status;
// @SerializedName("copyright") private String copyright;
// @SerializedName("attributionText") private String attributionText;
// @SerializedName("attributionHTML") private String getAttributionHtml;
// @SerializedName("etag") private String etag;
//
// @SerializedName("data") private T response;
//
// public MarvelResponse() {
// }
//
// public MarvelResponse(MarvelResponse marvelResponse) {
// code = marvelResponse.getCode();
// status = marvelResponse.getStatus();
// copyright = marvelResponse.getCopyright();
// attributionText = marvelResponse.getAttributionText();
// getAttributionHtml = marvelResponse.getGetAttributionHtml();
// etag = marvelResponse.getEtag();
// }
//
// public int getCode() {
// return code;
// }
//
// public String getStatus() {
// return status;
// }
//
// public String getCopyright() {
// return copyright;
// }
//
// public String getAttributionText() {
// return attributionText;
// }
//
// public String getGetAttributionHtml() {
// return getAttributionHtml;
// }
//
// public T getResponse() {
// return response;
// }
//
// public String getEtag() {
// return etag;
// }
//
// @Override public String toString() {
// return "MarvelResponse{"
// + "code="
// + code
// + ", status='"
// + status
// + '\''
// + ", copyright='"
// + copyright
// + '\''
// + ", attributionText='"
// + attributionText
// + '\''
// + ", getAttributionHtml='"
// + getAttributionHtml
// + '\''
// + ", etag='"
// + etag
// + '\''
// + ", response="
// + response
// + '}';
// }
//
// public void setResponse(T response) {
// this.response = response;
// }
// }
//
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/SeriesCollectionDto.java
// public class SeriesCollectionDto extends MarvelCollection<SeriesDto> {
//
// public List<SeriesDto> getSeries() {
// return getResults();
// }
//
// @Override public String toString() {
// return "CharactersDto{"
// + "offset="
// + getOffset()
// + ", limit="
// + getLimit()
// + ", total="
// + getTotal()
// + ", count="
// + getCount()
// + ", characters="
// + getSeries().toString()
// + '}';
// }
// }
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/SeriesApiRest.java
import com.karumi.marvelapiclient.model.ComicsDto;
import com.karumi.marvelapiclient.model.MarvelResponse;
import com.karumi.marvelapiclient.model.SeriesCollectionDto;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
/*
* Copyright (C) 2015 Karumi.
* 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.karumi.marvelapiclient;
interface SeriesApiRest {
@GET("series") Call<MarvelResponse<SeriesCollectionDto>> getSeries(
@QueryMap Map<String, Object> seriesFilter);
@GET("series/{id}") Call<MarvelResponse<SeriesCollectionDto>> getSerie(
@Path("id") String serieId);
| @GET("series/{id}/comics") Call<MarvelResponse<ComicsDto>> getComicsBySerie( |
Karumi/MarvelApiClientAndroid | MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/ComicsQuery.java | // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/utils/DateUtil.java
// public class DateUtil {
//
// private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
//
// public static String parseDate(Date date) {
// SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
// return format.format(date);
// }
// }
| import com.karumi.marvelapiclient.utils.DateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | String dateDescriptorAsString = (dateDescriptor != null) ? dateDescriptor.toString() : null;
return new ComicsQuery(formatAsString, formatTypeAsString, noVariants,
dateDescriptorAsString, dataRangeAsString, title, titleStartsWith, startYear,
issueNumber, diamondCode, digitalId, upc, isbn, ean, issn, hasDigitalIssue,
modifiedSinceAsString, creatorsAsString, charactersAsString, seriesAsString,
eventsAsString, storiesAsString, sharedAppearancesAsString, collaboratorsAsString,
orderByAsString, limit, offset);
}
private void checkLimit(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must be bigger than zero");
}
if (limit > MAX_SIZE) {
throw new IllegalArgumentException("limit must be smaller than 100");
}
}
private void checkNotNull(Object object) {
if (object == null) {
throw new IllegalArgumentException("the argument can not be null");
}
}
private String convertDate(Date date) {
if (date == null) {
return null;
} | // Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/utils/DateUtil.java
// public class DateUtil {
//
// private static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ";
//
// public static String parseDate(Date date) {
// SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
// return format.format(date);
// }
// }
// Path: MarvelApiClient/src/main/java/com/karumi/marvelapiclient/model/ComicsQuery.java
import com.karumi.marvelapiclient.utils.DateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
String dateDescriptorAsString = (dateDescriptor != null) ? dateDescriptor.toString() : null;
return new ComicsQuery(formatAsString, formatTypeAsString, noVariants,
dateDescriptorAsString, dataRangeAsString, title, titleStartsWith, startYear,
issueNumber, diamondCode, digitalId, upc, isbn, ean, issn, hasDigitalIssue,
modifiedSinceAsString, creatorsAsString, charactersAsString, seriesAsString,
eventsAsString, storiesAsString, sharedAppearancesAsString, collaboratorsAsString,
orderByAsString, limit, offset);
}
private void checkLimit(int limit) {
if (limit <= 0) {
throw new IllegalArgumentException("limit must be bigger than zero");
}
if (limit > MAX_SIZE) {
throw new IllegalArgumentException("limit must be smaller than 100");
}
}
private void checkNotNull(Object object) {
if (object == null) {
throw new IllegalArgumentException("the argument can not be null");
}
}
private String convertDate(Date date) {
if (date == null) {
return null;
} | return DateUtil.parseDate(date); |
deepnighttwo/yet-another-storm-ui | yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/model/SlotStatus.java | // Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/util/UptimeUtil.java
// public class UptimeUtil {
//
// private static final Splitter SPLITTER = Splitter.on(Pattern.compile("[d|h|m|s]")).omitEmptyStrings().trimResults();
//
// public static int compareUptime(String uptime1, String uptime2) {
// if (uptime1 == null && uptime2 == null) {
// return 0;
// }
//
// if (uptime1 == null) {
// return -1;
// }
//
// if (uptime2 == null) {
// return 1;
// }
//
// String[] parts1 = getUptimeStrings(uptime1);
// String[] parts2 = getUptimeStrings(uptime2);
//
// if (parts1.length != parts2.length) {
// return parts1.length - parts2.length;
// }
//
// for (int i = 0; i < parts1.length; i++) {
// int ret = Integer.parseInt(parts1[i]) - Integer.parseInt(parts2[i]);
// if (ret != 0) {
// return ret;
// }
// }
//
// return 0;
// }
//
// public static String[] getUptimeStrings(String uptime) {
// Iterable<String> uptimeParts = SPLITTER.split(uptime);
//
// List<String> parts = new ArrayList<String>(4);
// for (String part : uptimeParts) {
// parts.add(part);
// }
// return parts.toArray(new String[parts.size()]);
// }
// }
| import com.deepnighttwo.yasu.util.UptimeUtil;
import java.util.List; | package com.deepnighttwo.yasu.model;
/**
* User: mzang
* Date: 2014-10-09
* Time: 18:18
*/
public class SlotStatus implements Comparable<SlotStatus> {
String host;
String ip;
int port;
String uptime;
List<ExecutorStatus> stats;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SlotStatus)) return false;
SlotStatus that = (SlotStatus) o;
if (port != that.port) return false;
if (host != null ? !host.equals(that.host) : that.host != null) return false;
return true;
}
@Override
public int hashCode() {
int result = host != null ? host.hashCode() : 0;
result = 31 * result + port;
return result;
}
public String getUptime() {
return uptime;
}
public void setUptime(String uptime) {
this.uptime = uptime;
}
public void updateUptime(String uptime) { | // Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/util/UptimeUtil.java
// public class UptimeUtil {
//
// private static final Splitter SPLITTER = Splitter.on(Pattern.compile("[d|h|m|s]")).omitEmptyStrings().trimResults();
//
// public static int compareUptime(String uptime1, String uptime2) {
// if (uptime1 == null && uptime2 == null) {
// return 0;
// }
//
// if (uptime1 == null) {
// return -1;
// }
//
// if (uptime2 == null) {
// return 1;
// }
//
// String[] parts1 = getUptimeStrings(uptime1);
// String[] parts2 = getUptimeStrings(uptime2);
//
// if (parts1.length != parts2.length) {
// return parts1.length - parts2.length;
// }
//
// for (int i = 0; i < parts1.length; i++) {
// int ret = Integer.parseInt(parts1[i]) - Integer.parseInt(parts2[i]);
// if (ret != 0) {
// return ret;
// }
// }
//
// return 0;
// }
//
// public static String[] getUptimeStrings(String uptime) {
// Iterable<String> uptimeParts = SPLITTER.split(uptime);
//
// List<String> parts = new ArrayList<String>(4);
// for (String part : uptimeParts) {
// parts.add(part);
// }
// return parts.toArray(new String[parts.size()]);
// }
// }
// Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/model/SlotStatus.java
import com.deepnighttwo.yasu.util.UptimeUtil;
import java.util.List;
package com.deepnighttwo.yasu.model;
/**
* User: mzang
* Date: 2014-10-09
* Time: 18:18
*/
public class SlotStatus implements Comparable<SlotStatus> {
String host;
String ip;
int port;
String uptime;
List<ExecutorStatus> stats;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SlotStatus)) return false;
SlotStatus that = (SlotStatus) o;
if (port != that.port) return false;
if (host != null ? !host.equals(that.host) : that.host != null) return false;
return true;
}
@Override
public int hashCode() {
int result = host != null ? host.hashCode() : 0;
result = 31 * result + port;
return result;
}
public String getUptime() {
return uptime;
}
public void setUptime(String uptime) {
this.uptime = uptime;
}
public void updateUptime(String uptime) { | if (UptimeUtil.compareUptime(this.uptime, uptime) < 0) { |
deepnighttwo/yet-another-storm-ui | yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/servlet/Hosts.java | // Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/model/Host.java
// public class Host implements Comparable<Host> {
// String host;
// String ip;
// String uptime;
// String supId;
// int slotsTotal;
// int slotsUsed;
// List<SlotStatus> slots = new ArrayList<SlotStatus>();
//
// public List<SlotStatus> getSlots() {
// return slots;
// }
//
// public void setSlots(List<SlotStatus> slots) {
// this.slots = slots;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public String getIp() {
// return ip;
// }
//
// public void setIp(String ip) {
// this.ip = ip;
// }
//
// public String getUptime() {
// return uptime;
// }
//
// public void setUptime(String uptime) {
// this.uptime = uptime;
// }
//
// public String getSupId() {
// return supId;
// }
//
// public void setSupId(String supId) {
// this.supId = supId;
// }
//
// public int getSlotsTotal() {
// return slotsTotal;
// }
//
// public void setSlotsTotal(int slotsTotal) {
// this.slotsTotal = slotsTotal;
// }
//
// public int getSlotsUsed() {
// return slotsUsed;
// }
//
// public void setSlotsUsed(int slotsUsed) {
// this.slotsUsed = slotsUsed;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Host)) return false;
//
// Host host1 = (Host) o;
//
// if (host != null ? !host.equals(host1.host) : host1.host != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return host != null ? host.hashCode() : 0;
// }
//
// @Override
// public int compareTo(Host o) {
// return this.getHost().compareTo(o.getHost());
// }
// }
| import com.deepnighttwo.yasu.model.Host;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map; | package com.deepnighttwo.yasu.servlet;
/**
* User: mzang
* Date: 2014-09-30
* Time: 13:08
*/
@WebServlet(name = "hosts", urlPatterns = {"/hosts"})
public class Hosts extends ServletBase {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
setCommonHeaders(resp);
| // Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/model/Host.java
// public class Host implements Comparable<Host> {
// String host;
// String ip;
// String uptime;
// String supId;
// int slotsTotal;
// int slotsUsed;
// List<SlotStatus> slots = new ArrayList<SlotStatus>();
//
// public List<SlotStatus> getSlots() {
// return slots;
// }
//
// public void setSlots(List<SlotStatus> slots) {
// this.slots = slots;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public String getIp() {
// return ip;
// }
//
// public void setIp(String ip) {
// this.ip = ip;
// }
//
// public String getUptime() {
// return uptime;
// }
//
// public void setUptime(String uptime) {
// this.uptime = uptime;
// }
//
// public String getSupId() {
// return supId;
// }
//
// public void setSupId(String supId) {
// this.supId = supId;
// }
//
// public int getSlotsTotal() {
// return slotsTotal;
// }
//
// public void setSlotsTotal(int slotsTotal) {
// this.slotsTotal = slotsTotal;
// }
//
// public int getSlotsUsed() {
// return slotsUsed;
// }
//
// public void setSlotsUsed(int slotsUsed) {
// this.slotsUsed = slotsUsed;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Host)) return false;
//
// Host host1 = (Host) o;
//
// if (host != null ? !host.equals(host1.host) : host1.host != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return host != null ? host.hashCode() : 0;
// }
//
// @Override
// public int compareTo(Host o) {
// return this.getHost().compareTo(o.getHost());
// }
// }
// Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/servlet/Hosts.java
import com.deepnighttwo.yasu.model.Host;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
package com.deepnighttwo.yasu.servlet;
/**
* User: mzang
* Date: 2014-09-30
* Time: 13:08
*/
@WebServlet(name = "hosts", urlPatterns = {"/hosts"})
public class Hosts extends ServletBase {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
setCommonHeaders(resp);
| Map<String, Host> hosts = getStormDataService(req).getHostWithExecutorDetails(); |
deepnighttwo/yet-another-storm-ui | yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/servlet/AngularJSAjax.java | // Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/model/Person.java
// public class Person {
// String name;
// String phoneNumber;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
// }
| import com.deepnighttwo.yasu.model.Person;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random; | package com.deepnighttwo.yasu.servlet;
/**
* User: mzang
* Date: 2014-08-26
* Time: 19:54
*/
@WebServlet(name = "angularjsajax", urlPatterns = {"/angularjsajax"})
public class AngularJSAjax extends HttpServlet {
Gson gson = new Gson();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
resp.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
int size = 9;
Random random = new Random(); | // Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/model/Person.java
// public class Person {
// String name;
// String phoneNumber;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPhoneNumber() {
// return phoneNumber;
// }
//
// public void setPhoneNumber(String phoneNumber) {
// this.phoneNumber = phoneNumber;
// }
// }
// Path: yet-another-storm-ui-server/src/main/java/com/deepnighttwo/yasu/servlet/AngularJSAjax.java
import com.deepnighttwo.yasu.model.Person;
import com.google.gson.Gson;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;
package com.deepnighttwo.yasu.servlet;
/**
* User: mzang
* Date: 2014-08-26
* Time: 19:54
*/
@WebServlet(name = "angularjsajax", urlPatterns = {"/angularjsajax"})
public class AngularJSAjax extends HttpServlet {
Gson gson = new Gson();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
resp.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
int size = 9;
Random random = new Random(); | Person[] persons = new Person[size]; |
CrazyBBB/tenhou-visualizer | src/main/java/tenhouvisualizer/domain/service/DatabaseService.java | // Path: src/main/java/tenhouvisualizer/domain/model/InfoSchema.java
// public class InfoSchema {
// private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日H時m分");
//
// private final String id;
// private final boolean isSanma;
// private final boolean isTonnan;
// private final LocalDateTime dateTime;
// private final String first;
// private final String second;
// private final String third;
// private final String fourth;
// private final int minute;
// private final int firstScore;
// private final int secondScore;
// private final int thirdScore;
// private final int fourthScore;
//
// public static class Builder {
// private final String id;
// private final boolean isSanma;
// private final boolean isTonnan;
// private final LocalDateTime dateTime;
// private final String first;
// private final String second;
// private final String third;
// private final String fourth;
//
// private int minute = 0;
// private int firstScore = 0;
// private int secondScore = 0;
// private int thirdScore = 0;
// private int fourthScore = 0;
//
// public Builder(String id, boolean isSanma, boolean isTonnan, LocalDateTime dateTime,
// String first, String second, String third, String fourth) {
// this.id = id;
// this.isSanma = isSanma;
// this.isTonnan = isTonnan;
// this.dateTime = dateTime;
// this.first = first;
// this.second = second;
// this.third = third;
// this.fourth = fourth;
// }
//
// public Builder minute(int val) {
// minute = val;
// return this;
// }
//
// public Builder firstScore(int val) {
// firstScore = val;
// return this;
// }
//
// public Builder secondScore(int val) {
// secondScore = val;
// return this;
// }
//
// public Builder thirdScore(int val) {
// thirdScore = val;
// return this;
// }
//
// public Builder fourthScore(int val) {
// fourthScore = val;
// return this;
// }
//
// public InfoSchema build() {
// return new InfoSchema(this);
// }
// }
//
// private InfoSchema(Builder builder) {
// id = builder.id;
// isSanma = builder.isSanma;
// isTonnan = builder.isTonnan;
// minute = builder.minute;
// dateTime = builder.dateTime;
// first = builder.first;
// second = builder.second;
// third = builder.third;
// fourth = builder.fourth;
// firstScore = builder.firstScore;
// secondScore = builder.secondScore;
// thirdScore = builder.thirdScore;
// fourthScore = builder.fourthScore;
// }
//
// @Override
// public String toString() {
// return (isSanma ? "三" : "四") + "鳳" + (isTonnan ? "南" : "東")
// + " 1位:" + first + " 2位:" + second + " 3位:" + third
// + (isSanma ? "" : " 4位:" + fourth) + " " + dateTime.format(dateFormatter);
// }
//
// public String getId() {
// return id;
// }
//
// public boolean isSanma() {
// return isSanma;
// }
//
// public boolean isTonnan() {
// return isTonnan;
// }
//
// public int getMinute() {
// return minute;
// }
//
// public LocalDateTime getDateTime() {
// return dateTime;
// }
//
// public String getFirst() {
// return first;
// }
//
// public String getSecond() {
// return second;
// }
//
// public String getThird() {
// return third;
// }
//
// public String getFourth() {
// return fourth;
// }
//
// public int getFirstScore() {
// return firstScore;
// }
//
// public int getSecondScore() {
// return secondScore;
// }
//
// public int getThirdScore() {
// return thirdScore;
// }
//
// public int getFourthScore() {
// return fourthScore;
// }
// }
| import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tenhouvisualizer.domain.model.InfoSchema;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
| long end = System.currentTimeMillis();
log.info("time to initialize db: {}", end - start);
}
private void initialize() throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS MJLOG(id TEXT PRIMARY KEY, content TEXT);";
Statement statement = this.connection.createStatement();
statement.execute(sql);
sql = "CREATE TABLE IF NOT EXISTS INFO(id TEXT PRIMARY KEY, is_sanma BOOLEAN, is_tonnan BOOLEAN," +
" date_time DATETIME, minute INT, first TEXT, second TEXT, third TEXT, fourth TEXT," +
" first_score INT, second_score INT, third_score INT, fourth_score INT);";
statement = this.connection.createStatement();
statement.execute(sql);
sql = "CREATE INDEX IF NOT EXISTS INDEXDATE ON INFO (date_time)";
statement = this.connection.createStatement();
statement.execute(sql);
sql = "CREATE TABLE IF NOT EXISTS MJLOGINDEX(id TEXT PRIMARY KEY);";
statement = this.connection.createStatement();
statement.execute(sql);
}
void saveMjlog(String id, String content) throws SQLException {
this.insertMjlogStatement.setString(1, id);
this.insertMjlogStatement.setString(2, content);
this.insertMjlogStatement.executeUpdate();
}
| // Path: src/main/java/tenhouvisualizer/domain/model/InfoSchema.java
// public class InfoSchema {
// private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy年M月d日H時m分");
//
// private final String id;
// private final boolean isSanma;
// private final boolean isTonnan;
// private final LocalDateTime dateTime;
// private final String first;
// private final String second;
// private final String third;
// private final String fourth;
// private final int minute;
// private final int firstScore;
// private final int secondScore;
// private final int thirdScore;
// private final int fourthScore;
//
// public static class Builder {
// private final String id;
// private final boolean isSanma;
// private final boolean isTonnan;
// private final LocalDateTime dateTime;
// private final String first;
// private final String second;
// private final String third;
// private final String fourth;
//
// private int minute = 0;
// private int firstScore = 0;
// private int secondScore = 0;
// private int thirdScore = 0;
// private int fourthScore = 0;
//
// public Builder(String id, boolean isSanma, boolean isTonnan, LocalDateTime dateTime,
// String first, String second, String third, String fourth) {
// this.id = id;
// this.isSanma = isSanma;
// this.isTonnan = isTonnan;
// this.dateTime = dateTime;
// this.first = first;
// this.second = second;
// this.third = third;
// this.fourth = fourth;
// }
//
// public Builder minute(int val) {
// minute = val;
// return this;
// }
//
// public Builder firstScore(int val) {
// firstScore = val;
// return this;
// }
//
// public Builder secondScore(int val) {
// secondScore = val;
// return this;
// }
//
// public Builder thirdScore(int val) {
// thirdScore = val;
// return this;
// }
//
// public Builder fourthScore(int val) {
// fourthScore = val;
// return this;
// }
//
// public InfoSchema build() {
// return new InfoSchema(this);
// }
// }
//
// private InfoSchema(Builder builder) {
// id = builder.id;
// isSanma = builder.isSanma;
// isTonnan = builder.isTonnan;
// minute = builder.minute;
// dateTime = builder.dateTime;
// first = builder.first;
// second = builder.second;
// third = builder.third;
// fourth = builder.fourth;
// firstScore = builder.firstScore;
// secondScore = builder.secondScore;
// thirdScore = builder.thirdScore;
// fourthScore = builder.fourthScore;
// }
//
// @Override
// public String toString() {
// return (isSanma ? "三" : "四") + "鳳" + (isTonnan ? "南" : "東")
// + " 1位:" + first + " 2位:" + second + " 3位:" + third
// + (isSanma ? "" : " 4位:" + fourth) + " " + dateTime.format(dateFormatter);
// }
//
// public String getId() {
// return id;
// }
//
// public boolean isSanma() {
// return isSanma;
// }
//
// public boolean isTonnan() {
// return isTonnan;
// }
//
// public int getMinute() {
// return minute;
// }
//
// public LocalDateTime getDateTime() {
// return dateTime;
// }
//
// public String getFirst() {
// return first;
// }
//
// public String getSecond() {
// return second;
// }
//
// public String getThird() {
// return third;
// }
//
// public String getFourth() {
// return fourth;
// }
//
// public int getFirstScore() {
// return firstScore;
// }
//
// public int getSecondScore() {
// return secondScore;
// }
//
// public int getThirdScore() {
// return thirdScore;
// }
//
// public int getFourthScore() {
// return fourthScore;
// }
// }
// Path: src/main/java/tenhouvisualizer/domain/service/DatabaseService.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tenhouvisualizer.domain.model.InfoSchema;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
long end = System.currentTimeMillis();
log.info("time to initialize db: {}", end - start);
}
private void initialize() throws SQLException {
String sql = "CREATE TABLE IF NOT EXISTS MJLOG(id TEXT PRIMARY KEY, content TEXT);";
Statement statement = this.connection.createStatement();
statement.execute(sql);
sql = "CREATE TABLE IF NOT EXISTS INFO(id TEXT PRIMARY KEY, is_sanma BOOLEAN, is_tonnan BOOLEAN," +
" date_time DATETIME, minute INT, first TEXT, second TEXT, third TEXT, fourth TEXT," +
" first_score INT, second_score INT, third_score INT, fourth_score INT);";
statement = this.connection.createStatement();
statement.execute(sql);
sql = "CREATE INDEX IF NOT EXISTS INDEXDATE ON INFO (date_time)";
statement = this.connection.createStatement();
statement.execute(sql);
sql = "CREATE TABLE IF NOT EXISTS MJLOGINDEX(id TEXT PRIMARY KEY);";
statement = this.connection.createStatement();
statement.execute(sql);
}
void saveMjlog(String id, String content) throws SQLException {
this.insertMjlogStatement.setString(1, id);
this.insertMjlogStatement.setString(2, content);
this.insertMjlogStatement.executeUpdate();
}
| public void saveInfos(List<InfoSchema> infos) {
|
CrazyBBB/tenhou-visualizer | src/test/java/tenhouvisualizer/domain/task/DownloadYearTaskTest.java | // Path: src/main/java/tenhouvisualizer/domain/task/DownloadYearTask.java
// @NotNull
// static String getFileNameWithExtension(String path) {
// return path.substring(path.lastIndexOf('/') + 1);
// }
| import org.junit.Test;
import static org.junit.Assert.*;
import static tenhouvisualizer.domain.task.DownloadYearTask.getFileNameWithExtension; | package tenhouvisualizer.domain.task;
public class DownloadYearTaskTest {
@Test
public void getFileNameTest01() throws Exception {
String path = "aaa/bbb.html"; | // Path: src/main/java/tenhouvisualizer/domain/task/DownloadYearTask.java
// @NotNull
// static String getFileNameWithExtension(String path) {
// return path.substring(path.lastIndexOf('/') + 1);
// }
// Path: src/test/java/tenhouvisualizer/domain/task/DownloadYearTaskTest.java
import org.junit.Test;
import static org.junit.Assert.*;
import static tenhouvisualizer.domain.task.DownloadYearTask.getFileNameWithExtension;
package tenhouvisualizer.domain.task;
public class DownloadYearTaskTest {
@Test
public void getFileNameTest01() throws Exception {
String path = "aaa/bbb.html"; | assertEquals("bbb.html", getFileNameWithExtension(path)); |
CrazyBBB/tenhou-visualizer | src/main/java/tenhouvisualizer/app/donatationranker/DonationRankerController.java | // Path: src/main/java/tenhouvisualizer/Main.java
// public class Main extends Application {
//
// private final static Logger log = LoggerFactory.getLogger(Main.class);
//
// public static DatabaseService databaseService;
// public static Properties properties;
//
// public static void main(String[] args) {
// launch(args);
// }
//
// @Override
// public void start(Stage stage) throws IOException {
// log.info("start!");
//
// properties = new Properties();
// File configationFile = new File("./tenhouvisualizer.properties");
// if (configationFile.isFile()) {
// try (InputStream is = new FileInputStream(configationFile)) {
// properties.load(is);
// }
// }
// if (!properties.containsKey("css")) {
// properties.setProperty("css", "/darcula.css");
// }
//
// try {
// Main.databaseService = new DatabaseService(new File("./tenhouvisualizer.sqlite"));
// } catch (ClassNotFoundException | SQLException e) {
// e.printStackTrace();
// }
//
// Parent root = FXMLLoader.load(getClass().getResource("/app.fxml"));
// root.getStylesheets().add(this.getClass().getResource(Main.properties.getProperty("css")).toExternalForm());
// Scene scene = new Scene(root);
// stage.setScene(scene);
// stage.setTitle("Tenhou Visualizer");
// stage.show();
// }
//
// @Override
// public void stop() throws Exception {
// super.stop();
// Main.databaseService.close();
// log.info("stop!");
// }
// }
| import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tenhouvisualizer.Main;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern; | matchMinField.setText(String.valueOf(DEFAULT_MATCH_MIN));
}
if (isNotSmallNumberString(showMaxField.getText())) {
showMaxField.setText(String.valueOf(DEFAULT_SHOW_MAX));
}
boolean isSanma = sanmaRadioButton.isSelected();
boolean isTonnan = tonnanRadioButton.isSelected();
String playerName = filterField.getText();
int matchMin = Integer.parseInt(matchMinField.getText());
int showMax = Integer.parseInt(showMaxField.getText());
rankingTableView.setItems(rankWinnerAndLoser(isSanma, isTonnan, playerName, matchMin, showMax));
}
public void clear(ActionEvent actionEvent) {
sanmaRadioButton.setSelected(true);
tonnanRadioButton.setSelected(true);
filterField.clear();
matchMinField.setText(String.valueOf(DEFAULT_MATCH_MIN));
showMaxField.setText(String.valueOf(DEFAULT_SHOW_MAX));
}
public void clearFilterField(ActionEvent actionEvent) {
filterField.clear();
filterField.requestFocus();
}
private ObservableList<Donation> rankWinnerAndLoser(boolean isSanma, boolean isTonnan, String playerName,
int matchMin, int showMax) { | // Path: src/main/java/tenhouvisualizer/Main.java
// public class Main extends Application {
//
// private final static Logger log = LoggerFactory.getLogger(Main.class);
//
// public static DatabaseService databaseService;
// public static Properties properties;
//
// public static void main(String[] args) {
// launch(args);
// }
//
// @Override
// public void start(Stage stage) throws IOException {
// log.info("start!");
//
// properties = new Properties();
// File configationFile = new File("./tenhouvisualizer.properties");
// if (configationFile.isFile()) {
// try (InputStream is = new FileInputStream(configationFile)) {
// properties.load(is);
// }
// }
// if (!properties.containsKey("css")) {
// properties.setProperty("css", "/darcula.css");
// }
//
// try {
// Main.databaseService = new DatabaseService(new File("./tenhouvisualizer.sqlite"));
// } catch (ClassNotFoundException | SQLException e) {
// e.printStackTrace();
// }
//
// Parent root = FXMLLoader.load(getClass().getResource("/app.fxml"));
// root.getStylesheets().add(this.getClass().getResource(Main.properties.getProperty("css")).toExternalForm());
// Scene scene = new Scene(root);
// stage.setScene(scene);
// stage.setTitle("Tenhou Visualizer");
// stage.show();
// }
//
// @Override
// public void stop() throws Exception {
// super.stop();
// Main.databaseService.close();
// log.info("stop!");
// }
// }
// Path: src/main/java/tenhouvisualizer/app/donatationranker/DonationRankerController.java
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tenhouvisualizer.Main;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
matchMinField.setText(String.valueOf(DEFAULT_MATCH_MIN));
}
if (isNotSmallNumberString(showMaxField.getText())) {
showMaxField.setText(String.valueOf(DEFAULT_SHOW_MAX));
}
boolean isSanma = sanmaRadioButton.isSelected();
boolean isTonnan = tonnanRadioButton.isSelected();
String playerName = filterField.getText();
int matchMin = Integer.parseInt(matchMinField.getText());
int showMax = Integer.parseInt(showMaxField.getText());
rankingTableView.setItems(rankWinnerAndLoser(isSanma, isTonnan, playerName, matchMin, showMax));
}
public void clear(ActionEvent actionEvent) {
sanmaRadioButton.setSelected(true);
tonnanRadioButton.setSelected(true);
filterField.clear();
matchMinField.setText(String.valueOf(DEFAULT_MATCH_MIN));
showMaxField.setText(String.valueOf(DEFAULT_SHOW_MAX));
}
public void clearFilterField(ActionEvent actionEvent) {
filterField.clear();
filterField.requestFocus();
}
private ObservableList<Donation> rankWinnerAndLoser(boolean isSanma, boolean isTonnan, String playerName,
int matchMin, int showMax) { | List<String[]> list = Main.databaseService.findWinnerAndLoser(isSanma, isTonnan, playerName); |
CrazyBBB/tenhou-visualizer | src/test/java/MahjongUtilsTest.java | // Path: src/main/java/tenhouvisualizer/domain/MahjongUtils.java
// public class MahjongUtils {
//
// public static int computeSyanten(int[] tehai, int naki) {
// int tmp = 13;
// if (naki == 0) {
// tmp = Math.min(tmp, computeKokusiSyanten(tehai));
// tmp = Math.min(tmp, computeTiitoituSyanten(tehai));
// }
// tmp = Math.min(tmp, computeNormalSyanten(tehai, naki));
//
// return tmp;
// }
//
// public static int computeTiitoituSyanten(int[] tehai) {
// int toitu = 0;
// int syurui = 0;
// int syantenTiitoi;
//
// for (int i = 0; i < 34; i++) {
// if (tehai[i] >= 1) syurui++;
// if (tehai[i] >= 2) toitu++;
// }
//
// syantenTiitoi = 6 - toitu;
//
// if (syurui < 7) syantenTiitoi += 7 - syurui;
// return syantenTiitoi;
// }
//
// public static int computeKokusiSyanten(int[] tehai) {
// int kokusiToitu = 0;
// int syantenKokusi = 13;
//
// for (int i = 0; i < 34; i++) {
// if (i % 9 == 0 || i % 9 == 8 || i >= 27) {
// if (tehai[i] >= 1) syantenKokusi--;
// if (tehai[i] >= 2) kokusiToitu = 1;
// }
// }
//
// syantenKokusi -= kokusiToitu;
// return syantenKokusi;
// }
//
// private static int mentu;
// private static int toitu;
// private static int kouho;
// private static int syantenNormal;
//
// public static int computeNormalSyanten(int[] tehai, int naki) {
// mentu = naki;
// toitu = 0;
// kouho = 0;
// syantenNormal = 13;
//
// for (int i = 0; i < 34; i++) {
// if (tehai[i] >= 2) {
// toitu++;
// tehai[i] -= 2;
// mentuCut(0, tehai);
// tehai[i] += 2;
// toitu--;
// }
// }
//
// mentuCut(0, tehai);
// return syantenNormal;
// }
//
// public static void mentuCut(int i, int[] tehai) {
// while (i < 34 && tehai[i] == 0) i++;
// if (i == 34) {
// taatuCut(0, tehai);
// return;
// }
//
// if (tehai[i] >= 3) {
// mentu++;
// tehai[i] -= 3;
// mentuCut(i, tehai);
// tehai[i] += 3;
// mentu--;
// }
//
// if (i < 27 && i % 9 <= 6 && tehai[i + 1] >= 1 && tehai[i + 2] >= 1) {
// mentu++;
// tehai[i]--;
// tehai[i + 1]--;
// tehai[i + 2]--;
// mentuCut(i, tehai);
// tehai[i]++;
// tehai[i + 1]++;
// tehai[i + 2]++;
// mentu--;
// }
//
// mentuCut(i + 1, tehai);
// }
//
// public static void taatuCut(int i, int[] tehai) {
// while (i < 34 && tehai[i] == 0) i++;
// if (i == 34) {
// int tmp = 8 - mentu * 2 - kouho - toitu;
// syantenNormal = Math.min(syantenNormal, tmp);
// return;
// }
//
// if (mentu + kouho < 4) {
// if (tehai[i] >= 2) {
// kouho++;
// tehai[i] -= 2;
// taatuCut(i, tehai);
// tehai[i] += 2;
// kouho--;
// }
//
// if (i < 27 && i % 9 <= 7 && tehai[i + 1] >= 1) {
// kouho++;
// tehai[i]--;
// tehai[i + 1]--;
// taatuCut(i, tehai);
// tehai[i]++;
// tehai[i + 1]++;
// kouho--;
// }
//
// if (i < 27 && i % 9 <= 6 && tehai[i + 2] >= 1) {
// kouho++;
// tehai[i]--;
// tehai[i + 2]--;
// taatuCut(i, tehai);
// tehai[i]++;
// tehai[i + 2]++;
// kouho--;
// }
// }
//
// taatuCut(i + 1, tehai);
// }
//
// }
| import org.junit.Test;
import tenhouvisualizer.domain.MahjongUtils;
import static org.junit.Assert.*; |
public class MahjongUtilsTest {
@Test
public void testComputeTiitoituSyanten_Tenpai() {
int[] tehai = {2, 2, 2, 2, 2, 2, 1, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0};
int expected = 0; | // Path: src/main/java/tenhouvisualizer/domain/MahjongUtils.java
// public class MahjongUtils {
//
// public static int computeSyanten(int[] tehai, int naki) {
// int tmp = 13;
// if (naki == 0) {
// tmp = Math.min(tmp, computeKokusiSyanten(tehai));
// tmp = Math.min(tmp, computeTiitoituSyanten(tehai));
// }
// tmp = Math.min(tmp, computeNormalSyanten(tehai, naki));
//
// return tmp;
// }
//
// public static int computeTiitoituSyanten(int[] tehai) {
// int toitu = 0;
// int syurui = 0;
// int syantenTiitoi;
//
// for (int i = 0; i < 34; i++) {
// if (tehai[i] >= 1) syurui++;
// if (tehai[i] >= 2) toitu++;
// }
//
// syantenTiitoi = 6 - toitu;
//
// if (syurui < 7) syantenTiitoi += 7 - syurui;
// return syantenTiitoi;
// }
//
// public static int computeKokusiSyanten(int[] tehai) {
// int kokusiToitu = 0;
// int syantenKokusi = 13;
//
// for (int i = 0; i < 34; i++) {
// if (i % 9 == 0 || i % 9 == 8 || i >= 27) {
// if (tehai[i] >= 1) syantenKokusi--;
// if (tehai[i] >= 2) kokusiToitu = 1;
// }
// }
//
// syantenKokusi -= kokusiToitu;
// return syantenKokusi;
// }
//
// private static int mentu;
// private static int toitu;
// private static int kouho;
// private static int syantenNormal;
//
// public static int computeNormalSyanten(int[] tehai, int naki) {
// mentu = naki;
// toitu = 0;
// kouho = 0;
// syantenNormal = 13;
//
// for (int i = 0; i < 34; i++) {
// if (tehai[i] >= 2) {
// toitu++;
// tehai[i] -= 2;
// mentuCut(0, tehai);
// tehai[i] += 2;
// toitu--;
// }
// }
//
// mentuCut(0, tehai);
// return syantenNormal;
// }
//
// public static void mentuCut(int i, int[] tehai) {
// while (i < 34 && tehai[i] == 0) i++;
// if (i == 34) {
// taatuCut(0, tehai);
// return;
// }
//
// if (tehai[i] >= 3) {
// mentu++;
// tehai[i] -= 3;
// mentuCut(i, tehai);
// tehai[i] += 3;
// mentu--;
// }
//
// if (i < 27 && i % 9 <= 6 && tehai[i + 1] >= 1 && tehai[i + 2] >= 1) {
// mentu++;
// tehai[i]--;
// tehai[i + 1]--;
// tehai[i + 2]--;
// mentuCut(i, tehai);
// tehai[i]++;
// tehai[i + 1]++;
// tehai[i + 2]++;
// mentu--;
// }
//
// mentuCut(i + 1, tehai);
// }
//
// public static void taatuCut(int i, int[] tehai) {
// while (i < 34 && tehai[i] == 0) i++;
// if (i == 34) {
// int tmp = 8 - mentu * 2 - kouho - toitu;
// syantenNormal = Math.min(syantenNormal, tmp);
// return;
// }
//
// if (mentu + kouho < 4) {
// if (tehai[i] >= 2) {
// kouho++;
// tehai[i] -= 2;
// taatuCut(i, tehai);
// tehai[i] += 2;
// kouho--;
// }
//
// if (i < 27 && i % 9 <= 7 && tehai[i + 1] >= 1) {
// kouho++;
// tehai[i]--;
// tehai[i + 1]--;
// taatuCut(i, tehai);
// tehai[i]++;
// tehai[i + 1]++;
// kouho--;
// }
//
// if (i < 27 && i % 9 <= 6 && tehai[i + 2] >= 1) {
// kouho++;
// tehai[i]--;
// tehai[i + 2]--;
// taatuCut(i, tehai);
// tehai[i]++;
// tehai[i + 2]++;
// kouho--;
// }
// }
//
// taatuCut(i + 1, tehai);
// }
//
// }
// Path: src/test/java/MahjongUtilsTest.java
import org.junit.Test;
import tenhouvisualizer.domain.MahjongUtils;
import static org.junit.Assert.*;
public class MahjongUtilsTest {
@Test
public void testComputeTiitoituSyanten_Tenpai() {
int[] tehai = {2, 2, 2, 2, 2, 2, 1, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0};
int expected = 0; | assertEquals(expected, MahjongUtils.computeTiitoituSyanten(tehai)); |
liyuanhust/LoadMoreHelper | libary/src/main/java/com/lain/loadmorehelper/LoadController.java | // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
| import android.os.Handler;
import android.os.Looper;
import android.support.annotation.MainThread;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors; | return;
}
isPullingData = true;
mCurrentPageIndex = 0;
startLoadData(FIRST_PAGE_INDEX);
}
/**
* Call when 1st page data loaded
*/
@MainThread
private void onPullDataEnd() {
isPullingData = false;
if (isDestoryed) {
return;
}
if (paramBuilder.pullView != null) {
paramBuilder.pullView.doPullEnd();
}
}
/**
* Call when recyclerview scroll to the end
*/
@MainThread
public void doLoadMore() {
if (isPullingData || isLoadingMore || isDestoryed) {
return;
}
isLoadingMore = true; | // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
// Path: libary/src/main/java/com/lain/loadmorehelper/LoadController.java
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.MainThread;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
return;
}
isPullingData = true;
mCurrentPageIndex = 0;
startLoadData(FIRST_PAGE_INDEX);
}
/**
* Call when 1st page data loaded
*/
@MainThread
private void onPullDataEnd() {
isPullingData = false;
if (isDestoryed) {
return;
}
if (paramBuilder.pullView != null) {
paramBuilder.pullView.doPullEnd();
}
}
/**
* Call when recyclerview scroll to the end
*/
@MainThread
public void doLoadMore() {
if (isPullingData || isLoadingMore || isDestoryed) {
return;
}
isLoadingMore = true; | paramBuilder.listWrapper.setState(IListWrapper.STATE_LOAD_MORE); |
liyuanhust/LoadMoreHelper | libary/src/main/java/com/lain/loadmorehelper/LoadController.java | // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
| import android.os.Handler;
import android.os.Looper;
import android.support.annotation.MainThread;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors; | if (pageData.getPageIndex() == FIRST_PAGE_INDEX && isPullingData) {
onPullDataEnd();
}
lastPageData = pageData;
}
/**
* Start load data auto
*/
@MainThread
public void startLoadAuto(boolean anima) {
if (isDestoryed) {
return;
}
if (paramBuilder.pullView != null && anima) {
paramBuilder.pullView.startAutoPull();
} else {
doPullData();
}
}
public void release() {
isDestoryed = true;
}
public IDataSwapper<DT> getSimpleDataSwaper() {
return paramBuilder.simpleDataSwaper;
}
| // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
// Path: libary/src/main/java/com/lain/loadmorehelper/LoadController.java
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.MainThread;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
if (pageData.getPageIndex() == FIRST_PAGE_INDEX && isPullingData) {
onPullDataEnd();
}
lastPageData = pageData;
}
/**
* Start load data auto
*/
@MainThread
public void startLoadAuto(boolean anima) {
if (isDestoryed) {
return;
}
if (paramBuilder.pullView != null && anima) {
paramBuilder.pullView.startAutoPull();
} else {
doPullData();
}
}
public void release() {
isDestoryed = true;
}
public IDataSwapper<DT> getSimpleDataSwaper() {
return paramBuilder.simpleDataSwaper;
}
| public IFooterViewCreator getLoadMoreFooterCreator() { |
liyuanhust/LoadMoreHelper | libary/src/main/java/com/lain/loadmorehelper/list/recyclerview/FooterViewAdapter.java | // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
| import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_INITIAL;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_MORE;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_FAILED; | package com.lain.loadmorehelper.list.recyclerview;
/**
* Created by liyuan on 16/12/19.
*/
public class FooterViewAdapter<VH extends RecyclerView.ViewHolder> extends BaseWrapperAdapter {
private static final int VIEW_TYPE_LOADMORE = Integer.MAX_VALUE - 1;
private static final int VIEW_TYPE_COMPLETE = Integer.MAX_VALUE - 2;
private static final int VIEW_TYPE_LOADFAILED = Integer.MAX_VALUE - 3;
| // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
// Path: libary/src/main/java/com/lain/loadmorehelper/list/recyclerview/FooterViewAdapter.java
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_INITIAL;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_MORE;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_FAILED;
package com.lain.loadmorehelper.list.recyclerview;
/**
* Created by liyuan on 16/12/19.
*/
public class FooterViewAdapter<VH extends RecyclerView.ViewHolder> extends BaseWrapperAdapter {
private static final int VIEW_TYPE_LOADMORE = Integer.MAX_VALUE - 1;
private static final int VIEW_TYPE_COMPLETE = Integer.MAX_VALUE - 2;
private static final int VIEW_TYPE_LOADFAILED = Integer.MAX_VALUE - 3;
| private @IListWrapper.ListState int mLoadMoreStatus = STATE_INITIAL; |
liyuanhust/LoadMoreHelper | libary/src/main/java/com/lain/loadmorehelper/list/recyclerview/FooterViewAdapter.java | // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
| import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_INITIAL;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_MORE;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_FAILED; | package com.lain.loadmorehelper.list.recyclerview;
/**
* Created by liyuan on 16/12/19.
*/
public class FooterViewAdapter<VH extends RecyclerView.ViewHolder> extends BaseWrapperAdapter {
private static final int VIEW_TYPE_LOADMORE = Integer.MAX_VALUE - 1;
private static final int VIEW_TYPE_COMPLETE = Integer.MAX_VALUE - 2;
private static final int VIEW_TYPE_LOADFAILED = Integer.MAX_VALUE - 3;
private @IListWrapper.ListState int mLoadMoreStatus = STATE_INITIAL;
| // Path: libary/src/main/java/com/lain/loadmorehelper/list/IFooterViewCreator.java
// public interface IFooterViewCreator {
// View getView(ViewGroup parent);
// }
//
// Path: libary/src/main/java/com/lain/loadmorehelper/list/IListWrapper.java
// public interface IListWrapper {
// public static final int STATE_INITIAL = 0;
// public static final int STATE_LOAD_MORE = 1;
// public static final int STATE_LOAD_FAILED = 2;
// public static final int STATE_LOAD_COMPLETE = 3;
//
// void init(LoadController<?> loadController);
//
// void setState(@ListState int curState);
//
// @IntDef({STATE_INITIAL, STATE_LOAD_MORE, STATE_LOAD_FAILED, STATE_LOAD_COMPLETE})
// @Retention(RetentionPolicy.SOURCE)
// @interface ListState {
//
// }
//
// }
// Path: libary/src/main/java/com/lain/loadmorehelper/list/recyclerview/FooterViewAdapter.java
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.lain.loadmorehelper.list.IFooterViewCreator;
import com.lain.loadmorehelper.list.IListWrapper;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_INITIAL;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_MORE;
import static com.lain.loadmorehelper.list.IListWrapper.STATE_LOAD_FAILED;
package com.lain.loadmorehelper.list.recyclerview;
/**
* Created by liyuan on 16/12/19.
*/
public class FooterViewAdapter<VH extends RecyclerView.ViewHolder> extends BaseWrapperAdapter {
private static final int VIEW_TYPE_LOADMORE = Integer.MAX_VALUE - 1;
private static final int VIEW_TYPE_COMPLETE = Integer.MAX_VALUE - 2;
private static final int VIEW_TYPE_LOADFAILED = Integer.MAX_VALUE - 3;
private @IListWrapper.ListState int mLoadMoreStatus = STATE_INITIAL;
| private SparseArray<IFooterViewCreator> footerViewCreators = new SparseArray<>(); |
liyuanhust/LoadMoreHelper | testapp/src/main/java/com/lain/loadmoretest/MainActivity.java | // Path: testapp/src/main/java/com/lain/loadmoretest/base/SimpleActivity.java
// public final class SimpleActivity extends SingleFragmentActivity {
// private static final String EXTRA_INPUT_FRAGMENT_LCASS = "input_frag_class";
//
// @Override
// protected Fragment createFragment() {
// Intent intent = getIntent();
// try {
// Class<? extends Fragment> fragCls = (Class<? extends Fragment>)intent.getSerializableExtra(EXTRA_INPUT_FRAGMENT_LCASS);
// return fragCls.newInstance();
// }catch (Exception e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static Intent getStartIntent(Context ctx, Class<? extends Fragment> cls) {
// Intent intent = new Intent(ctx, SimpleActivity.class);
// intent.putExtra(EXTRA_INPUT_FRAGMENT_LCASS, cls);
// return intent;
// }
//
//
// public static Intent getStartIntent(Context ctx, Class<? extends Fragment> cls, Bundle bundle) {
// Intent intent = new Intent(ctx, SimpleActivity.class);
// intent.putExtra(EXTRA_INPUT_FRAGMENT_LCASS, cls);
// intent.putExtras(bundle);
// return intent;
// }
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.lain.loadmoretest.base.SimpleActivity; | package com.lain.loadmoretest;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(v -> { | // Path: testapp/src/main/java/com/lain/loadmoretest/base/SimpleActivity.java
// public final class SimpleActivity extends SingleFragmentActivity {
// private static final String EXTRA_INPUT_FRAGMENT_LCASS = "input_frag_class";
//
// @Override
// protected Fragment createFragment() {
// Intent intent = getIntent();
// try {
// Class<? extends Fragment> fragCls = (Class<? extends Fragment>)intent.getSerializableExtra(EXTRA_INPUT_FRAGMENT_LCASS);
// return fragCls.newInstance();
// }catch (Exception e) {
// e.printStackTrace();
// }
// return null;
// }
//
// public static Intent getStartIntent(Context ctx, Class<? extends Fragment> cls) {
// Intent intent = new Intent(ctx, SimpleActivity.class);
// intent.putExtra(EXTRA_INPUT_FRAGMENT_LCASS, cls);
// return intent;
// }
//
//
// public static Intent getStartIntent(Context ctx, Class<? extends Fragment> cls, Bundle bundle) {
// Intent intent = new Intent(ctx, SimpleActivity.class);
// intent.putExtra(EXTRA_INPUT_FRAGMENT_LCASS, cls);
// intent.putExtras(bundle);
// return intent;
// }
// }
// Path: testapp/src/main/java/com/lain/loadmoretest/MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.lain.loadmoretest.base.SimpleActivity;
package com.lain.loadmoretest;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn1).setOnClickListener(v -> { | Intent intent = SimpleActivity.getStartIntent(MainActivity.this, Fragment1.class); |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/converter/RoleConverter.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/Role.java
// @Entity
// public class Role extends VersionablePersistentEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String roleName = null;
// private String roleDescription = null;
//
// @ManyToMany(fetch = FetchType.EAGER, mappedBy = "roles")
// private Collection<User> users = null;
//
// /**
// * Crea un nuevo <Role> asignando valores default a todos sus campos.
// */
// @SuppressWarnings("unused")
// private Role() {
// }
//
// /**
// * Crea un nuevo <code>Role</code> asignando únicamente el nombre y la descripción del mismo.
// *
// * @param roleName Nombre de rol.
// * @param roleDescription Descripción del rol.
// */
// public Role(String roleName, String roleDescription) {
// this.roleName = roleName;
// this.roleDescription = roleDescription;
// this.users = new ArrayList<User>();
// }
//
// /**
// * @return Nombre del rol.
// */
// public String getRoleName() {
// return roleName;
// }
//
// /**
// * @param roleName Nombre del rol.
// * @return this.
// */
// public Role setRoleName(String roleName) {
// this.roleName = roleName;
// return this;
// }
//
// /**
// * @return Descripción del rol.
// */
// public String getRoleDescription() {
// return roleDescription;
// }
//
// /**
// * @param roleDescription Descripción del rol.
// * @return this.
// */
// public Role setRoleDescription(String roleDescription) {
// this.roleDescription = roleDescription;
// return this;
// }
//
// /**
// * @return <code>Collection<User></code> que tienen este rol asignado.
// */
// public Collection<User> getUsers() {
// return users;
// }
//
// // /**
// // * @param users <code>Collection<User></code> que tienen este rol asignado.
// // * @return this.
// // */
// // @SuppressWarnings("unchecked")
// // public Role setUsers(Collection<? extends User> users) {
// // this.users = (Collection<User>) users;
// // return this;
// // }
//
//
// public Role addUser(User user){
// this.users.add(user);
// return this;
// }
//
// @Override
// public String toString() {
// return this.roleDescription;
// }
//
// @Override
// public boolean equals(Object obj) {
//
// if (obj instanceof Role) {
// Role otherRole = (Role) obj;
// return otherRole.getRoleName().equals(this.roleName);
// }
//
// return super.equals(obj);
// }
//
// @Override
// public int hashCode() {
// return this.roleName.hashCode();
// }
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/UserService.java
// public interface UserService {
//
// /**
// * Almacena un usuario.
// *
// * @param user Usuario que se desea almacenar.
// */
// public void persistUser(User user);
//
// /**
// * Almacena un rol.
// *
// * @param role Rol que se desea almacenar.
// */
// public void persistRole(Role role);
//
// /**
// * Elimina un usuario.
// *
// * @param user Usuario que se desea eliminar.
// */
// public void removeUser(User user);
//
// /**
// * Busca un usuario dado su nombre de usuario.
// *
// * @param username Nombre de usuario del usuario que se desea buscar.
// * @return Usuario con el nombre de usuario especificado o null en caso de no encontrarlo.
// */
// public User getUserByUsername(String username);
//
// /**
// * Obtiene una colección con todos los roles que pueden tener los usuarios.
// *
// * @return Colección de roles que pueden terner asignados los usuarios.
// */
// public Collection<Role> getAvailableRoles();
//
// /**
// * Obtiene una colección con todos los usuarios registrados.
// *
// * @return Colección con todos los usuarios registrados.
// */
// public Collection<User> getUsers();
//
// /**
// * Obtiene todos los roles que tienen como descripción la indicada.
// *
// * @param roleDescription Descripción de los roles que se quieren obtener.
// * @return Colección con roles cuya descripción es la especificada.
// */
// public Role getRoleByRoleDescription(String roleDescription);
// }
| import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import ar.edu.itba.tpf.chatterbot.model.Role;
import ar.edu.itba.tpf.chatterbot.service.UserService; | package ar.edu.itba.tpf.chatterbot.converter;
public class RoleConverter implements Converter {
private UserService userService = null;
public void setUserService(UserService userService) {
this.userService = userService;
}
public Object getAsObject(FacesContext context, UIComponent component, String value) { | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/Role.java
// @Entity
// public class Role extends VersionablePersistentEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String roleName = null;
// private String roleDescription = null;
//
// @ManyToMany(fetch = FetchType.EAGER, mappedBy = "roles")
// private Collection<User> users = null;
//
// /**
// * Crea un nuevo <Role> asignando valores default a todos sus campos.
// */
// @SuppressWarnings("unused")
// private Role() {
// }
//
// /**
// * Crea un nuevo <code>Role</code> asignando únicamente el nombre y la descripción del mismo.
// *
// * @param roleName Nombre de rol.
// * @param roleDescription Descripción del rol.
// */
// public Role(String roleName, String roleDescription) {
// this.roleName = roleName;
// this.roleDescription = roleDescription;
// this.users = new ArrayList<User>();
// }
//
// /**
// * @return Nombre del rol.
// */
// public String getRoleName() {
// return roleName;
// }
//
// /**
// * @param roleName Nombre del rol.
// * @return this.
// */
// public Role setRoleName(String roleName) {
// this.roleName = roleName;
// return this;
// }
//
// /**
// * @return Descripción del rol.
// */
// public String getRoleDescription() {
// return roleDescription;
// }
//
// /**
// * @param roleDescription Descripción del rol.
// * @return this.
// */
// public Role setRoleDescription(String roleDescription) {
// this.roleDescription = roleDescription;
// return this;
// }
//
// /**
// * @return <code>Collection<User></code> que tienen este rol asignado.
// */
// public Collection<User> getUsers() {
// return users;
// }
//
// // /**
// // * @param users <code>Collection<User></code> que tienen este rol asignado.
// // * @return this.
// // */
// // @SuppressWarnings("unchecked")
// // public Role setUsers(Collection<? extends User> users) {
// // this.users = (Collection<User>) users;
// // return this;
// // }
//
//
// public Role addUser(User user){
// this.users.add(user);
// return this;
// }
//
// @Override
// public String toString() {
// return this.roleDescription;
// }
//
// @Override
// public boolean equals(Object obj) {
//
// if (obj instanceof Role) {
// Role otherRole = (Role) obj;
// return otherRole.getRoleName().equals(this.roleName);
// }
//
// return super.equals(obj);
// }
//
// @Override
// public int hashCode() {
// return this.roleName.hashCode();
// }
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/UserService.java
// public interface UserService {
//
// /**
// * Almacena un usuario.
// *
// * @param user Usuario que se desea almacenar.
// */
// public void persistUser(User user);
//
// /**
// * Almacena un rol.
// *
// * @param role Rol que se desea almacenar.
// */
// public void persistRole(Role role);
//
// /**
// * Elimina un usuario.
// *
// * @param user Usuario que se desea eliminar.
// */
// public void removeUser(User user);
//
// /**
// * Busca un usuario dado su nombre de usuario.
// *
// * @param username Nombre de usuario del usuario que se desea buscar.
// * @return Usuario con el nombre de usuario especificado o null en caso de no encontrarlo.
// */
// public User getUserByUsername(String username);
//
// /**
// * Obtiene una colección con todos los roles que pueden tener los usuarios.
// *
// * @return Colección de roles que pueden terner asignados los usuarios.
// */
// public Collection<Role> getAvailableRoles();
//
// /**
// * Obtiene una colección con todos los usuarios registrados.
// *
// * @return Colección con todos los usuarios registrados.
// */
// public Collection<User> getUsers();
//
// /**
// * Obtiene todos los roles que tienen como descripción la indicada.
// *
// * @param roleDescription Descripción de los roles que se quieren obtener.
// * @return Colección con roles cuya descripción es la especificada.
// */
// public Role getRoleByRoleDescription(String roleDescription);
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/converter/RoleConverter.java
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import ar.edu.itba.tpf.chatterbot.model.Role;
import ar.edu.itba.tpf.chatterbot.service.UserService;
package ar.edu.itba.tpf.chatterbot.converter;
public class RoleConverter implements Converter {
private UserService userService = null;
public void setUserService(UserService userService) {
this.userService = userService;
}
public Object getAsObject(FacesContext context, UIComponent component, String value) { | Role role = userService.getRoleByRoleDescription(value); |
martinbigio/chatterbot | code/dispatcher/src/main/java/ar/edu/itba/tpf/chatterbot/dispatcher/JabberClient.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/exception/ChatterbotClientException.java
// public class ChatterbotClientException extends ChatterbotException {
// private static final long serialVersionUID = 1L;
//
// public ChatterbotClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import org.apache.log4j.Logger;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import ar.edu.itba.tpf.chatterbot.exception.ChatterbotClientException; | package ar.edu.itba.tpf.chatterbot.dispatcher;
/**
* Bean que ofrece servicios para enviar y recibir mensajes a través del procotolo XMPP.
*
* Primero se deben setear las propiedades server, username y password. Luego, en el método <code>init</code> se realiza
* la conexión al servidor. Durante todo el tiempo que el bean esté en memoria, el cliente permanecerá conectado. Al
* destruirlo se desconecta del servidor. Para enviar mensajes de manera sincrónica se utiliza el método
* <code>sendMessage</code>. Para recibir mensajes se debe registrar un observer, que va a ser invocado cuando llegue un
* mensaje nuevo.
*/
public class JabberClient {
private static final Logger logger = Logger.getLogger(JabberClient.class);
private String server;
private String username;
private String password;
private JabberClientObserver observer;
private XMPPConnection connection;
/**
* Inicializa el bean realizando el login al servidor Jabber, y dejando al cliente online.
*
* @throws ChatterbotClientException Si falla la conexión, retornará en esta excepción información del error.
*/ | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/exception/ChatterbotClientException.java
// public class ChatterbotClientException extends ChatterbotException {
// private static final long serialVersionUID = 1L;
//
// public ChatterbotClientException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: code/dispatcher/src/main/java/ar/edu/itba/tpf/chatterbot/dispatcher/JabberClient.java
import org.apache.log4j.Logger;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import ar.edu.itba.tpf.chatterbot.exception.ChatterbotClientException;
package ar.edu.itba.tpf.chatterbot.dispatcher;
/**
* Bean que ofrece servicios para enviar y recibir mensajes a través del procotolo XMPP.
*
* Primero se deben setear las propiedades server, username y password. Luego, en el método <code>init</code> se realiza
* la conexión al servidor. Durante todo el tiempo que el bean esté en memoria, el cliente permanecerá conectado. Al
* destruirlo se desconecta del servidor. Para enviar mensajes de manera sincrónica se utiliza el método
* <code>sendMessage</code>. Para recibir mensajes se debe registrar un observer, que va a ser invocado cuando llegue un
* mensaje nuevo.
*/
public class JabberClient {
private static final Logger logger = Logger.getLogger(JabberClient.class);
private String server;
private String username;
private String password;
private JabberClientObserver observer;
private XMPPConnection connection;
/**
* Inicializa el bean realizando el login al servidor Jabber, y dejando al cliente online.
*
* @throws ChatterbotClientException Si falla la conexión, retornará en esta excepción información del error.
*/ | public void init() throws ChatterbotClientException { |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/SuccessfulQueriesChart.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
| import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria; | package ar.edu.itba.tpf.chatterbot.web.charts;
public class SuccessfulQueriesChart extends ReportChart {
private LoggingService loggingService;
private DefaultPieDataset pieDataSet = null;
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
public SuccessfulQueriesChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "successful_queries";
this.chartType = "pie";
this.xLabelName = " ";
this.yLabelName = " ";
this.chartDescription = "Reporte de consultas exitosas";
this.width = 450;
this.height = 300;
}
| // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/SuccessfulQueriesChart.java
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
package ar.edu.itba.tpf.chatterbot.web.charts;
public class SuccessfulQueriesChart extends ReportChart {
private LoggingService loggingService;
private DefaultPieDataset pieDataSet = null;
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
public SuccessfulQueriesChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "successful_queries";
this.chartType = "pie";
this.xLabelName = " ";
this.yLabelName = " ";
this.chartDescription = "Reporte de consultas exitosas";
this.width = 450;
this.height = 300;
}
| public void reloadDataSet(IntervalCriteria intervalCriteria) { |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/MeanSessionTimeChart.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
| import java.util.Map;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.AbstractDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria; | package ar.edu.itba.tpf.chatterbot.web.charts;
public class MeanSessionTimeChart extends ReportChart {
private LoggingService loggingService;
private DefaultCategoryDataset dataset = null;
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
public MeanSessionTimeChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "mean_session_time";
this.chartType = "bar";
this.xLabelName = " ";
this.yLabelName = "cantidad de chats";
this.chartDescription = "Reporte de tiempo promedio";
this.width = 450;
this.height = 300;
}
@Override
public AbstractDataset getDataSet() {
return dataset;
}
@Override | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/MeanSessionTimeChart.java
import java.util.Map;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.AbstractDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
package ar.edu.itba.tpf.chatterbot.web.charts;
public class MeanSessionTimeChart extends ReportChart {
private LoggingService loggingService;
private DefaultCategoryDataset dataset = null;
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
public MeanSessionTimeChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "mean_session_time";
this.chartType = "bar";
this.xLabelName = " ";
this.yLabelName = "cantidad de chats";
this.chartDescription = "Reporte de tiempo promedio";
this.width = 450;
this.height = 300;
}
@Override
public AbstractDataset getDataSet() {
return dataset;
}
@Override | public void reloadDataSet(IntervalCriteria intervalCriteria) { |
martinbigio/chatterbot | code/impl/src/test/java/ar/edu/itba/tpf/chatterbot/dao/GenericDAOTest.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/PersistentEntity.java
// @MappedSuperclass
// public abstract class PersistentEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id = null;
//
// /**
// * @return Id de la entidad. Si no está persistida es null.
// */
// public Long getId() {
// return id;
// }
//
// /**
// * @param id Id de la entidad.
// */
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public int hashCode() {
// return 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// return true;
// }
//
// }
| import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.Collection;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.test.context.transaction.TransactionConfiguration;
import ar.edu.itba.tpf.chatterbot.model.PersistentEntity; | package ar.edu.itba.tpf.chatterbot.dao;
@ContextConfiguration(locations = { "classpath:impl-data.xml", "classpath:impl-beans.xml" })
@TransactionConfiguration(transactionManager = "transactionManager") | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/PersistentEntity.java
// @MappedSuperclass
// public abstract class PersistentEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id = null;
//
// /**
// * @return Id de la entidad. Si no está persistida es null.
// */
// public Long getId() {
// return id;
// }
//
// /**
// * @param id Id de la entidad.
// */
// public void setId(Long id) {
// this.id = id;
// }
//
// @Override
// public int hashCode() {
// return 0;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// return true;
// }
//
// }
// Path: code/impl/src/test/java/ar/edu/itba/tpf/chatterbot/dao/GenericDAOTest.java
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.Collection;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.test.context.transaction.TransactionConfiguration;
import ar.edu.itba.tpf.chatterbot.model.PersistentEntity;
package ar.edu.itba.tpf.chatterbot.dao;
@ContextConfiguration(locations = { "classpath:impl-data.xml", "classpath:impl-beans.xml" })
@TransactionConfiguration(transactionManager = "transactionManager") | public abstract class GenericDAOTest<T extends PersistentEntity> extends AbstractTransactionalJUnit4SpringContextTests { |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/ReportChart.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
| import org.jfree.data.general.AbstractDataset;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria; | package ar.edu.itba.tpf.chatterbot.web.charts;
public abstract class ReportChart {
protected String chartType;
protected String chartName;
protected String xLabelName;
protected String yLabelName;
protected String chartDescription;
protected Integer height;
protected Integer width;
public String getChartType() {
return chartType;
}
public String getChartName() {
return chartName;
}
public String getXLabelName() {
return xLabelName;
}
public String getYLabelName() {
return yLabelName;
}
public Integer getHeight() {
return height;
}
public Integer getWidth() {
return width;
}
public String getChartDescription() {
return chartDescription;
}
| // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/ReportChart.java
import org.jfree.data.general.AbstractDataset;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
package ar.edu.itba.tpf.chatterbot.web.charts;
public abstract class ReportChart {
protected String chartType;
protected String chartName;
protected String xLabelName;
protected String yLabelName;
protected String chartDescription;
protected Integer height;
protected Integer width;
public String getChartType() {
return chartType;
}
public String getChartName() {
return chartName;
}
public String getXLabelName() {
return xLabelName;
}
public String getYLabelName() {
return yLabelName;
}
public Integer getHeight() {
return height;
}
public Integer getWidth() {
return width;
}
public String getChartDescription() {
return chartDescription;
}
| public void reloadDataSet(IntervalCriteria intervalCriteria) { |
martinbigio/chatterbot | code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/WebServiceAction.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/business/InfoProvider.java
// @WebService
// public interface InfoProvider {
//
// @WebMethod
// public void provide(@WebParam String s, @WebParam(mode=Mode.INOUT) Holder<ArrayList<String>> keys, @WebParam(mode=Mode.INOUT) Holder<ArrayList<String>> values);
// }
| import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Transient;
import javax.xml.ws.Holder;
import org.apache.log4j.Logger;
import org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean;
import ar.edu.itba.tpf.chatterbot.business.InfoProvider; | package ar.edu.itba.tpf.chatterbot.model;
/**
* Implementación de <code>BaseAction</code> para Webservices. un Webservice que desee ser utilizado como acción por
* el chatterbot debe implementar la interfaz <code>InfoProvider</code>. Cuando se obtiene una instancia de esta case
* se genera el port (proxy) para comunicarse con el Webservice.
*/
@Entity
public class WebServiceAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WebServiceAction.class);
/* NamespaceUri que se va a colocar en el SoapEnvelope */
private static final String NAMESPACE_URI = "http://business.chatterbot.tpf.itba.edu.ar/";
/* URL del Webservice descriptor */
private String wsdlUrl;
/* Nombre del servicio que se queire acceder */
private String serviceName;
/* Método que se quiere consumir (requerido por <code>InfoProvider</code>) */
private String methodNane;
@Transient | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/business/InfoProvider.java
// @WebService
// public interface InfoProvider {
//
// @WebMethod
// public void provide(@WebParam String s, @WebParam(mode=Mode.INOUT) Holder<ArrayList<String>> keys, @WebParam(mode=Mode.INOUT) Holder<ArrayList<String>> values);
// }
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/WebServiceAction.java
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Transient;
import javax.xml.ws.Holder;
import org.apache.log4j.Logger;
import org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean;
import ar.edu.itba.tpf.chatterbot.business.InfoProvider;
package ar.edu.itba.tpf.chatterbot.model;
/**
* Implementación de <code>BaseAction</code> para Webservices. un Webservice que desee ser utilizado como acción por
* el chatterbot debe implementar la interfaz <code>InfoProvider</code>. Cuando se obtiene una instancia de esta case
* se genera el port (proxy) para comunicarse con el Webservice.
*/
@Entity
public class WebServiceAction extends BaseAction {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WebServiceAction.class);
/* NamespaceUri que se va a colocar en el SoapEnvelope */
private static final String NAMESPACE_URI = "http://business.chatterbot.tpf.itba.edu.ar/";
/* URL del Webservice descriptor */
private String wsdlUrl;
/* Nombre del servicio que se queire acceder */
private String serviceName;
/* Método que se quiere consumir (requerido por <code>InfoProvider</code>) */
private String methodNane;
@Transient | private InfoProvider provider; |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/MostTraversedPathsChart.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
| import java.util.Map;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria; | package ar.edu.itba.tpf.chatterbot.web.charts;
public class MostTraversedPathsChart extends ReportChart {
private DefaultPieDataset pieDataSet = null; | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/MostTraversedPathsChart.java
import java.util.Map;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
package ar.edu.itba.tpf.chatterbot.web.charts;
public class MostTraversedPathsChart extends ReportChart {
private DefaultPieDataset pieDataSet = null; | private LoggingService loggingService; |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/MostTraversedPathsChart.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
| import java.util.Map;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria; | package ar.edu.itba.tpf.chatterbot.web.charts;
public class MostTraversedPathsChart extends ReportChart {
private DefaultPieDataset pieDataSet = null;
private LoggingService loggingService;
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
public MostTraversedPathsChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "most_traversed_paths";
this.chartType = "pie";
this.xLabelName = " ";
this.yLabelName = " ";
this.chartDescription = "Reporte de caminos más recorridos";
this.width = 450;
this.height = 300;
}
@Override
public AbstractDataset getDataSet() {
return pieDataSet;
}
@Override | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/MostTraversedPathsChart.java
import java.util.Map;
import org.jfree.data.general.AbstractDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
package ar.edu.itba.tpf.chatterbot.web.charts;
public class MostTraversedPathsChart extends ReportChart {
private DefaultPieDataset pieDataSet = null;
private LoggingService loggingService;
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
public MostTraversedPathsChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "most_traversed_paths";
this.chartType = "pie";
this.xLabelName = " ";
this.yLabelName = " ";
this.chartDescription = "Reporte de caminos más recorridos";
this.width = 450;
this.height = 300;
}
@Override
public AbstractDataset getDataSet() {
return pieDataSet;
}
@Override | public void reloadDataSet(IntervalCriteria intervalCriteria) { |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/ErrorLogWrapper.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/ErrorLog.java
// @Entity
// public class ErrorLog extends VersionablePersistentEntity {
// private static final long serialVersionUID = 0L;
//
// private static final int MAX_LENGTH_MESSAGE = 500;
// private static final int MAX_LENGTH_STACK_TRACE = 1000;
//
// @Column(length=MAX_LENGTH_MESSAGE)
// private String message;
//
// @Column(length=MAX_LENGTH_STACK_TRACE)
// private String stackTrace;
// private Date timestamp;
//
// ErrorLog() {
// }
//
// /**
// * Crea un nuevo error log dado un mensaje, un stack trace y un timestamp.
// *
// * @param message Mensaje del error.
// * @param stackTrace Stack trace completo.
// * @param timestamp Fecha y hora del error.
// */
// public ErrorLog(String message, String stackTrace, Date timestamp) {
// super();
//
// if (message.length() > MAX_LENGTH_MESSAGE) {
// this.message = message.substring(0, MAX_LENGTH_MESSAGE - 1);
// } else {
// this.message = message;
// }
//
// if (stackTrace.length() > MAX_LENGTH_STACK_TRACE) {
// this.stackTrace = stackTrace.substring(0, MAX_LENGTH_STACK_TRACE- 1);
// } else {
// this.stackTrace = stackTrace;
// }
//
// this.timestamp = timestamp;
// }
//
// /**
// * Crea un nuevo error log dado un mensaje y un stack trace utilizando la fecha de creación del objeto.
// *
// * @param message Mensaje del error.
// * @param stackTrace Stack trace completo.
// */
// public ErrorLog(String message, String stackTrace) {
// super();
//
// if (message.length() > MAX_LENGTH_MESSAGE) {
// this.message = message.substring(0, MAX_LENGTH_MESSAGE - 1);
// } else {
// this.message = message;
// }
//
// if (stackTrace.length() > MAX_LENGTH_STACK_TRACE) {
// this.stackTrace = stackTrace.substring(0, MAX_LENGTH_STACK_TRACE- 1);
// } else {
// this.stackTrace = stackTrace;
// }
//
// this.timestamp = new Date();
// }
//
// /**
// * @return Mensaje del error.
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * @return Stack trace del error.
// */
// public String getStackTrace() {
// return stackTrace;
// }
//
// /**
// * @return Fecha y hora del error.
// */
// public Date getTimestamp() {
// return timestamp;
// }
//
// /**
// * @param message Mensaje de error.
// */
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + ((message == null) ? 0 : message.hashCode());
// result = prime * result + ((stackTrace == null) ? 0 : stackTrace.hashCode());
// result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// ErrorLog other = (ErrorLog) obj;
// if (message == null) {
// if (other.message != null)
// return false;
// } else if (!message.equals(other.message))
// return false;
// if (stackTrace == null) {
// if (other.stackTrace != null)
// return false;
// } else if (!stackTrace.equals(other.stackTrace))
// return false;
// if (timestamp == null) {
// if (other.timestamp != null)
// return false;
// } else if (!timestamp.equals(other.timestamp))
// return false;
// return true;
// }
//
//
// }
| import ar.edu.itba.tpf.chatterbot.model.ErrorLog;
| package ar.edu.itba.tpf.chatterbot.web;
public class ErrorLogWrapper {
private final static int MESSAGE_SIZE = 45;
private final static int STACKTRACE_SIZE = 30;
| // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/ErrorLog.java
// @Entity
// public class ErrorLog extends VersionablePersistentEntity {
// private static final long serialVersionUID = 0L;
//
// private static final int MAX_LENGTH_MESSAGE = 500;
// private static final int MAX_LENGTH_STACK_TRACE = 1000;
//
// @Column(length=MAX_LENGTH_MESSAGE)
// private String message;
//
// @Column(length=MAX_LENGTH_STACK_TRACE)
// private String stackTrace;
// private Date timestamp;
//
// ErrorLog() {
// }
//
// /**
// * Crea un nuevo error log dado un mensaje, un stack trace y un timestamp.
// *
// * @param message Mensaje del error.
// * @param stackTrace Stack trace completo.
// * @param timestamp Fecha y hora del error.
// */
// public ErrorLog(String message, String stackTrace, Date timestamp) {
// super();
//
// if (message.length() > MAX_LENGTH_MESSAGE) {
// this.message = message.substring(0, MAX_LENGTH_MESSAGE - 1);
// } else {
// this.message = message;
// }
//
// if (stackTrace.length() > MAX_LENGTH_STACK_TRACE) {
// this.stackTrace = stackTrace.substring(0, MAX_LENGTH_STACK_TRACE- 1);
// } else {
// this.stackTrace = stackTrace;
// }
//
// this.timestamp = timestamp;
// }
//
// /**
// * Crea un nuevo error log dado un mensaje y un stack trace utilizando la fecha de creación del objeto.
// *
// * @param message Mensaje del error.
// * @param stackTrace Stack trace completo.
// */
// public ErrorLog(String message, String stackTrace) {
// super();
//
// if (message.length() > MAX_LENGTH_MESSAGE) {
// this.message = message.substring(0, MAX_LENGTH_MESSAGE - 1);
// } else {
// this.message = message;
// }
//
// if (stackTrace.length() > MAX_LENGTH_STACK_TRACE) {
// this.stackTrace = stackTrace.substring(0, MAX_LENGTH_STACK_TRACE- 1);
// } else {
// this.stackTrace = stackTrace;
// }
//
// this.timestamp = new Date();
// }
//
// /**
// * @return Mensaje del error.
// */
// public String getMessage() {
// return message;
// }
//
// /**
// * @return Stack trace del error.
// */
// public String getStackTrace() {
// return stackTrace;
// }
//
// /**
// * @return Fecha y hora del error.
// */
// public Date getTimestamp() {
// return timestamp;
// }
//
// /**
// * @param message Mensaje de error.
// */
// public void setMessage(String message) {
// this.message = message;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + ((message == null) ? 0 : message.hashCode());
// result = prime * result + ((stackTrace == null) ? 0 : stackTrace.hashCode());
// result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (getClass() != obj.getClass())
// return false;
// ErrorLog other = (ErrorLog) obj;
// if (message == null) {
// if (other.message != null)
// return false;
// } else if (!message.equals(other.message))
// return false;
// if (stackTrace == null) {
// if (other.stackTrace != null)
// return false;
// } else if (!stackTrace.equals(other.stackTrace))
// return false;
// if (timestamp == null) {
// if (other.timestamp != null)
// return false;
// } else if (!timestamp.equals(other.timestamp))
// return false;
// return true;
// }
//
//
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/ErrorLogWrapper.java
import ar.edu.itba.tpf.chatterbot.model.ErrorLog;
package ar.edu.itba.tpf.chatterbot.web;
public class ErrorLogWrapper {
private final static int MESSAGE_SIZE = 45;
private final static int STACKTRACE_SIZE = 30;
| ErrorLog errorLog;
|
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/ChatsCountChart.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
| import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.AbstractDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria; | package ar.edu.itba.tpf.chatterbot.web.charts;
public class ChatsCountChart extends ReportChart {
private LoggingService loggingService;
private DefaultCategoryDataset dataset = null;
public ChatsCountChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "chats_count";
this.chartType = "bar";
this.xLabelName = "días";
this.yLabelName = "cantidad de chats";
this.chartDescription = "Reporte de cantidad de chats por día";
this.width = 450;
this.height = 300;
}
@Override
public AbstractDataset getDataSet() {
return this.dataset;
}
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
@Override | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/service/LoggingService.java
// public interface LoggingService {
//
// /**
// * Almacena una conversacion.
// *
// * @param chat Conversación que se desea almacenar.
// */
// public void persistChat(Chat chat);
//
// /**
// * Obtiene un histograma con la cantidad de chats por dia.
// *
// * @param intervalCriteria Intervalo en el que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats realizados en cada fecha.
// */
// public Map<Date, Long> getChatsPerDay(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene el porcentaje de chats que fueron atendidos en forma satisfactoria.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Un arreglo de long indicando, el número de chats successful y el número total de chats.
// */
// public Long[] getSuccessfulChatsRatio(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene un histograma con la cantidad de chats de diferentes duraciones.
// *
// * @param intervalCriteria Intervalo de fechas en la que se realiza la búsqueda.
// * @return Mapa con la cantidad de chats que duraron diferente cantidad de minutos.
// */
// public Map<String, Long> getAverageChatTime(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene todos los chats que satisfacen un criterio de búsqueda.
// *
// * @param loggingCriteria Criterio de búsqueda que contiene palabras clave.
// * @return Colección con todos los chats cuyo log tiene uno o más de las palabras clave que se indican en el
// * criterio de búsqueda.
// */
// public Collection<Chat> getChats(LoggingCriteria loggingCriteria);
//
// /**
// * Almacena un error ocurrido en la aplicación.
// *
// * @param errorLog Información del error ocurrido.
// */
// public void persistErrorLog(ErrorLog errorLog);
//
// /**
// * Elimina un ErrorLog.
// *
// * @param server ErrorLog que se desea eliminar.
// */
// public void removeErrorLog(ErrorLog errorLog);
//
// /**
// * Obtiene todos los errores ocurridos en un determinado intervalo de tiempo.
// *
// * @param intervalCriteria Intervalo de tiempo en el cual buscar errores.
// * @return Colección de errores ocurridos en dicho intervalo.
// */
// public Collection<ErrorLog> getErrorLogs(IntervalCriteria intervalCriteria);
//
// /**
// * Obtiene los nodos hoja del árbol de consultas y la cantidad de veces que fueron visitados en el intervalo dado.
// *
// * @param intervalCriteria Intervalo en el cual hacer la consulta.
// * @return Listado de nodos con la cantidad de veces que fueron visitados.
// */
// public Map<String, Long> getMostVisitedNodes(IntervalCriteria intervalCriteria);
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/ChatsCountChart.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.AbstractDataset;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.service.LoggingService;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
package ar.edu.itba.tpf.chatterbot.web.charts;
public class ChatsCountChart extends ReportChart {
private LoggingService loggingService;
private DefaultCategoryDataset dataset = null;
public ChatsCountChart() {
/* No tocar este nombre que se utiliza para identificar al gráfico. */
this.chartName = "chats_count";
this.chartType = "bar";
this.xLabelName = "días";
this.yLabelName = "cantidad de chats";
this.chartDescription = "Reporte de cantidad de chats por día";
this.width = 450;
this.height = 300;
}
@Override
public AbstractDataset getDataSet() {
return this.dataset;
}
@Required
public void setLoggingService(LoggingService loggingService) {
this.loggingService = loggingService;
}
@Override | public void reloadDataSet(IntervalCriteria intervalCriteria) { |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/IntervalCriteriaManager.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
| import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
| package ar.edu.itba.tpf.chatterbot.web;
public class IntervalCriteriaManager {
private static final int FROM_HOUR_INITIAL = 0;
private static final int TO_HOUR_INITIAL = 23;
| // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/support/IntervalCriteria.java
// public class IntervalCriteria {
// private Date from;
// private Date to;
//
// /**
// * Crea un nuevo criterio de búsqueda completando la fecha de comienzo y fin.
// *
// * @param from Fecha inicial.
// * @param to Fecha final.
// */
// public IntervalCriteria(Date from, Date to) {
// super();
// this.from = from;
// this.to = to;
// }
//
// /**
// * @return Fecha inicial.
// */
// public Date getFrom() {
// return from;
// }
//
// /**
// * @param from Fecha inicial.
// * @return this.
// */
// public IntervalCriteria setFrom(Date from) {
// this.from = from;
// return this;
// }
//
// /**
// * @return Fecha final.
// */
// public Date getTo() {
// return to;
// }
//
// /**
// * @param to Fecha final.
// * @return this.
// */
// public IntervalCriteria setTo(Date to) {
// this.to = to;
// return this;
// }
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/IntervalCriteriaManager.java
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import ar.edu.itba.tpf.chatterbot.support.IntervalCriteria;
package ar.edu.itba.tpf.chatterbot.web;
public class IntervalCriteriaManager {
private static final int FROM_HOUR_INITIAL = 0;
private static final int TO_HOUR_INITIAL = 23;
| private IntervalCriteria intervalCriteria;
|
martinbigio/chatterbot | code/impl/src/test/java/ar/edu/itba/tpf/chatterbot/dao/TreeNodeDAOTest.java | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/LeafNode.java
// @Entity
// public class LeafNode extends TreeNode {
// private static final long serialVersionUID = 0L;
//
// LeafNode() {
// }
//
// /**
// * Construye un <code>LeafNode</code> completando únicamente la información del <code>Node</code> del que hereda.
// *
// * @param action Acción a realizar cuando el chatterbot está en el nodo.
// * @param keywords Palabras clave que hacen que el chatterbot llegue a este nodo.
// * @param description Descripción del nodo.
// * @param answer Respuesta que el chatterbot emite cuando estando el el nodo.
// * @param errorTransition Transición de error.
// */
// public LeafNode(Action action, String keywords, String description, String answer, TreeNode errorTransition) {
// super(action, keywords, description, answer, errorTransition);
// }
//
// @Override
// public boolean hasTransitions() {
// return false;
// }
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/TreeNode.java
// @Entity
// public abstract class TreeNode extends AbstractNode {
//
// private static final long serialVersionUID = 1L;
//
// @ManyToOne()
// protected InternalNode parent;
//
// @ManyToOne()
// private TreeNode errorTransition;
//
// /* Quienes me tienen en sus transiciones de error */
// @OneToMany(mappedBy = "errorTransition", cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
// private Collection<TreeNode> references = new ArrayList<TreeNode>();
//
// TreeNode() {
// }
//
// /**
// * Construye un <code>TreeNode</code> completando únicamente la información del <code>Node</code> del que hereda.
// *
// * @param action Acción a realizar cuando el chatterbot está en el nodo.
// * @param keywords Palabras clave que hacen que el chatterbot llegue a este nodo.
// * @param description Descripción del nodo.
// * @param answer Respuesta que el chatterbot emite cuando estando el el nodo.
// * @param errorTransition Transición de error a la que se pasa si ocurre un error durante la ejecución de una
// * acción.
// */
// public TreeNode(Action action, String keywords, String description, String answer, TreeNode errorTransition) {
// super(action, keywords, description, answer);
// setErrorTransition(errorTransition);
// }
//
// /**
// * @see ar.edu.itba.tpf.chatterbot.model.GlobalNode#hasTransitions()
// */
// public abstract boolean hasTransitions();
//
// /**
// * @return Nodo padre del nodo.
// */
// public InternalNode getParent() {
// return parent;
// }
//
// /**
// * @return Transición de error.
// */
// public TreeNode getErrorTransition() {
// return errorTransition;
// }
//
// /**
// * @param errorTransition Transición de error.
// */
// public void setErrorTransition(TreeNode errorTransition) {
// if ((this.errorTransition == null && errorTransition == null)
// || (this.errorTransition != null && errorTransition != null && this.errorTransition
// .equals(errorTransition))) {
// return;
// }
// if (this.errorTransition != null) {
// // System.out.println("setErrorTransition: sacandome de mi padre anterior");
// this.errorTransition.getReferences().remove(this);
// }
//
// this.errorTransition = errorTransition;
// if (this.errorTransition != null) {
// // System.out.println("setErrorTransition: poniendome en mi nuevo padre");
// this.errorTransition.getReferences().add(this);
// }
// }
//
// public Collection<TreeNode> getReferences() {
// return references;
// }
//
// }
| import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import ar.edu.itba.tpf.chatterbot.model.InternalNode;
import ar.edu.itba.tpf.chatterbot.model.LeafNode;
import ar.edu.itba.tpf.chatterbot.model.TreeNode;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat; | package ar.edu.itba.tpf.chatterbot.dao;
public class TreeNodeDAOTest extends GenericDAOTest<TreeNode> {
@Autowired
private TreeNodeDAO treeNodeDAO;
@Override
protected GenericDAO<TreeNode, Long> getDao() {
return treeNodeDAO;
}
@Override
protected TreeNode getSample() {
return new InternalNode(null, "test", "test", "test", null);
}
@Override
protected void updateSample(TreeNode sample) {
sample.setDescription("test2");
}
@Test
public void testFindRootNode() {
InternalNode rootNode = new InternalNode(null, "keywords", "root", "answer", null); | // Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/LeafNode.java
// @Entity
// public class LeafNode extends TreeNode {
// private static final long serialVersionUID = 0L;
//
// LeafNode() {
// }
//
// /**
// * Construye un <code>LeafNode</code> completando únicamente la información del <code>Node</code> del que hereda.
// *
// * @param action Acción a realizar cuando el chatterbot está en el nodo.
// * @param keywords Palabras clave que hacen que el chatterbot llegue a este nodo.
// * @param description Descripción del nodo.
// * @param answer Respuesta que el chatterbot emite cuando estando el el nodo.
// * @param errorTransition Transición de error.
// */
// public LeafNode(Action action, String keywords, String description, String answer, TreeNode errorTransition) {
// super(action, keywords, description, answer, errorTransition);
// }
//
// @Override
// public boolean hasTransitions() {
// return false;
// }
// }
//
// Path: code/api/src/main/java/ar/edu/itba/tpf/chatterbot/model/TreeNode.java
// @Entity
// public abstract class TreeNode extends AbstractNode {
//
// private static final long serialVersionUID = 1L;
//
// @ManyToOne()
// protected InternalNode parent;
//
// @ManyToOne()
// private TreeNode errorTransition;
//
// /* Quienes me tienen en sus transiciones de error */
// @OneToMany(mappedBy = "errorTransition", cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
// private Collection<TreeNode> references = new ArrayList<TreeNode>();
//
// TreeNode() {
// }
//
// /**
// * Construye un <code>TreeNode</code> completando únicamente la información del <code>Node</code> del que hereda.
// *
// * @param action Acción a realizar cuando el chatterbot está en el nodo.
// * @param keywords Palabras clave que hacen que el chatterbot llegue a este nodo.
// * @param description Descripción del nodo.
// * @param answer Respuesta que el chatterbot emite cuando estando el el nodo.
// * @param errorTransition Transición de error a la que se pasa si ocurre un error durante la ejecución de una
// * acción.
// */
// public TreeNode(Action action, String keywords, String description, String answer, TreeNode errorTransition) {
// super(action, keywords, description, answer);
// setErrorTransition(errorTransition);
// }
//
// /**
// * @see ar.edu.itba.tpf.chatterbot.model.GlobalNode#hasTransitions()
// */
// public abstract boolean hasTransitions();
//
// /**
// * @return Nodo padre del nodo.
// */
// public InternalNode getParent() {
// return parent;
// }
//
// /**
// * @return Transición de error.
// */
// public TreeNode getErrorTransition() {
// return errorTransition;
// }
//
// /**
// * @param errorTransition Transición de error.
// */
// public void setErrorTransition(TreeNode errorTransition) {
// if ((this.errorTransition == null && errorTransition == null)
// || (this.errorTransition != null && errorTransition != null && this.errorTransition
// .equals(errorTransition))) {
// return;
// }
// if (this.errorTransition != null) {
// // System.out.println("setErrorTransition: sacandome de mi padre anterior");
// this.errorTransition.getReferences().remove(this);
// }
//
// this.errorTransition = errorTransition;
// if (this.errorTransition != null) {
// // System.out.println("setErrorTransition: poniendome en mi nuevo padre");
// this.errorTransition.getReferences().add(this);
// }
// }
//
// public Collection<TreeNode> getReferences() {
// return references;
// }
//
// }
// Path: code/impl/src/test/java/ar/edu/itba/tpf/chatterbot/dao/TreeNodeDAOTest.java
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import ar.edu.itba.tpf.chatterbot.model.InternalNode;
import ar.edu.itba.tpf.chatterbot.model.LeafNode;
import ar.edu.itba.tpf.chatterbot.model.TreeNode;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
package ar.edu.itba.tpf.chatterbot.dao;
public class TreeNodeDAOTest extends GenericDAOTest<TreeNode> {
@Autowired
private TreeNodeDAO treeNodeDAO;
@Override
protected GenericDAO<TreeNode, Long> getDao() {
return treeNodeDAO;
}
@Override
protected TreeNode getSample() {
return new InternalNode(null, "test", "test", "test", null);
}
@Override
protected void updateSample(TreeNode sample) {
sample.setDescription("test2");
}
@Test
public void testFindRootNode() {
InternalNode rootNode = new InternalNode(null, "keywords", "root", "answer", null); | LeafNode leftSon = new LeafNode(null, "leftkeywords", "left", "answer", null); |
martinbigio/chatterbot | code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/ReportManagerBean.java | // Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/ReportChart.java
// public abstract class ReportChart {
//
// protected String chartType;
// protected String chartName;
// protected String xLabelName;
// protected String yLabelName;
// protected String chartDescription;
// protected Integer height;
// protected Integer width;
//
// public String getChartType() {
// return chartType;
// }
//
// public String getChartName() {
// return chartName;
// }
//
// public String getXLabelName() {
// return xLabelName;
// }
//
// public String getYLabelName() {
// return yLabelName;
// }
//
// public Integer getHeight() {
// return height;
// }
//
// public Integer getWidth() {
// return width;
// }
//
// public String getChartDescription() {
// return chartDescription;
// }
//
// public void reloadDataSet(IntervalCriteria intervalCriteria) {
// throw new RuntimeException("Falta implementar");
// }
//
// public abstract AbstractDataset getDataSet();
//
//
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.web.charts.ReportChart; | package ar.edu.itba.tpf.chatterbot.web;
public class ReportManagerBean {
private static ResourceBundle rb;
{
rb = ResourceBundle.getBundle("ar.edu.itba.tpf.chatterbot.ErrorMessages");
}
private boolean showChart = true; | // Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/charts/ReportChart.java
// public abstract class ReportChart {
//
// protected String chartType;
// protected String chartName;
// protected String xLabelName;
// protected String yLabelName;
// protected String chartDescription;
// protected Integer height;
// protected Integer width;
//
// public String getChartType() {
// return chartType;
// }
//
// public String getChartName() {
// return chartName;
// }
//
// public String getXLabelName() {
// return xLabelName;
// }
//
// public String getYLabelName() {
// return yLabelName;
// }
//
// public Integer getHeight() {
// return height;
// }
//
// public Integer getWidth() {
// return width;
// }
//
// public String getChartDescription() {
// return chartDescription;
// }
//
// public void reloadDataSet(IntervalCriteria intervalCriteria) {
// throw new RuntimeException("Falta implementar");
// }
//
// public abstract AbstractDataset getDataSet();
//
//
// }
// Path: code/web/src/main/java/ar/edu/itba/tpf/chatterbot/web/ReportManagerBean.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.annotation.Required;
import ar.edu.itba.tpf.chatterbot.web.charts.ReportChart;
package ar.edu.itba.tpf.chatterbot.web;
public class ReportManagerBean {
private static ResourceBundle rb;
{
rb = ResourceBundle.getBundle("ar.edu.itba.tpf.chatterbot.ErrorMessages");
}
private boolean showChart = true; | private Map<String, ReportChart> reports; |
worldsproject/Fluxware-Game-Engine | src/sprites/AnimatedSprite.java | // Path: src/util/ImageData.java
// public class ImageData
// {
// private Texture texture = null;
// private boolean[][] mask = null;
//
// public ImageData(Texture texture, boolean[][] mask)
// {
// super();
// this.texture = texture;
// this.mask = mask;
// }
//
// public Texture getTexture()
// {
// return texture;
// }
//
// public void setTexture(Texture texture)
// {
// this.texture = texture;
// }
//
// public boolean[][] getMask()
// {
// return mask;
// }
//
// public void setMask(boolean[][] mask)
// {
// this.mask = mask;
// }
//
// }
| import util.ImageData; | package sprites;
/**
* The Animated Sprite takes in an array of images and rotates through them in order
* to create an animation.
* @author Tim Butram
*
*/
@SuppressWarnings("serial")
public class AnimatedSprite extends Sprite implements Runnable
{
public final int serial = 3;
| // Path: src/util/ImageData.java
// public class ImageData
// {
// private Texture texture = null;
// private boolean[][] mask = null;
//
// public ImageData(Texture texture, boolean[][] mask)
// {
// super();
// this.texture = texture;
// this.mask = mask;
// }
//
// public Texture getTexture()
// {
// return texture;
// }
//
// public void setTexture(Texture texture)
// {
// this.texture = texture;
// }
//
// public boolean[][] getMask()
// {
// return mask;
// }
//
// public void setMask(boolean[][] mask)
// {
// this.mask = mask;
// }
//
// }
// Path: src/sprites/AnimatedSprite.java
import util.ImageData;
package sprites;
/**
* The Animated Sprite takes in an array of images and rotates through them in order
* to create an animation.
* @author Tim Butram
*
*/
@SuppressWarnings("serial")
public class AnimatedSprite extends Sprite implements Runnable
{
public final int serial = 3;
| protected ImageData[] textures = null; |
worldsproject/Fluxware-Game-Engine | src/sound/WaveLoader.java | // Path: src/exception/IncorrectFormatException.java
// public class IncorrectFormatException extends Exception
// {
// public static final int NOT_A_RIFF = 0;
// public static final int INCORRECT_FILESIZE = 1;
// public static final int NOT_A_WAVE = 2;
// public static final int DOES_NOT_HAVE_FMT = 3;
// public static final int SUBCHUNK_SIZE_INCORRECT = 4;
// public static final int COMPRESSION_DETECTED = 5;
// public static final int DATA_NOT_FOUND = 6;
// public static final int UNSUPPORTED_SAMPLE_SIZE = 7;
// public static final int UNSUPPORTED_CHANNEL_NUMBER = 8;
//
// public IncorrectFormatException(int type)
// {
// switch(type)
// {
// case 0: System.err.println("The .wav files header is not RIFF."); break;
// case 1: System.err.println("The .wav files size is reported incorrectly."); break;
// case 2: System.err.println("The format of the .wav file is not WAVE"); break;
// case 3: System.err.println("The .wav header does not have fmt "); break;
// case 4: System.err.println("Subchunk size indicates it is not PCM"); break;
// case 5: System.err.println("Compressed .wav files are not supported."); break;
// case 6: System.err.println("The value 'data' has not been found in the .wav header"); break;
// case 7: System.err.println("Currently only supports 8 and 16 bit sample sizes."); break;
// case 8: System.err.println("Currently only support 1 or 2 channels."); break;
// }
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import org.lwjgl.openal.AL10;
import exception.IncorrectFormatException; | private FileInputStream dir;
public WaveLoader(String path)
{
path = WaveLoader.class.getResource(path).getPath();
File potential_wav = new File(path);
try
{
dir = new FileInputStream(path);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return;
}
try
{
//Read in the first 4 bytes. These bytes should spell RIFF.
byte[] buffer = new byte[4];
dir.read(buffer);
//Unsign the bytes and put it into a IntBuffer for comparison to the IntBuffer RIFF
IntBuffer is_riff = IntBuffer.wrap(this.unsign_byte(buffer));
if(RIFF.compareTo(is_riff) != 0)
{ | // Path: src/exception/IncorrectFormatException.java
// public class IncorrectFormatException extends Exception
// {
// public static final int NOT_A_RIFF = 0;
// public static final int INCORRECT_FILESIZE = 1;
// public static final int NOT_A_WAVE = 2;
// public static final int DOES_NOT_HAVE_FMT = 3;
// public static final int SUBCHUNK_SIZE_INCORRECT = 4;
// public static final int COMPRESSION_DETECTED = 5;
// public static final int DATA_NOT_FOUND = 6;
// public static final int UNSUPPORTED_SAMPLE_SIZE = 7;
// public static final int UNSUPPORTED_CHANNEL_NUMBER = 8;
//
// public IncorrectFormatException(int type)
// {
// switch(type)
// {
// case 0: System.err.println("The .wav files header is not RIFF."); break;
// case 1: System.err.println("The .wav files size is reported incorrectly."); break;
// case 2: System.err.println("The format of the .wav file is not WAVE"); break;
// case 3: System.err.println("The .wav header does not have fmt "); break;
// case 4: System.err.println("Subchunk size indicates it is not PCM"); break;
// case 5: System.err.println("Compressed .wav files are not supported."); break;
// case 6: System.err.println("The value 'data' has not been found in the .wav header"); break;
// case 7: System.err.println("Currently only supports 8 and 16 bit sample sizes."); break;
// case 8: System.err.println("Currently only support 1 or 2 channels."); break;
// }
// }
// }
// Path: src/sound/WaveLoader.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import org.lwjgl.openal.AL10;
import exception.IncorrectFormatException;
private FileInputStream dir;
public WaveLoader(String path)
{
path = WaveLoader.class.getResource(path).getPath();
File potential_wav = new File(path);
try
{
dir = new FileInputStream(path);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
return;
}
try
{
//Read in the first 4 bytes. These bytes should spell RIFF.
byte[] buffer = new byte[4];
dir.read(buffer);
//Unsign the bytes and put it into a IntBuffer for comparison to the IntBuffer RIFF
IntBuffer is_riff = IntBuffer.wrap(this.unsign_byte(buffer));
if(RIFF.compareTo(is_riff) != 0)
{ | new IncorrectFormatException(IncorrectFormatException.NOT_A_RIFF); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.