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
|
---|---|---|---|---|---|---|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/AMap.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
|
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface represents immutable maps with mutator methods (<code>updated(), removed()</code>) that return a
* new map instance with different members. Since all instances are immutable, they are thread-safe by definition.
* They are also useful in recursive algorithms.<p>
*
* This interface does not implement <code>java.util.Map</code> since that interface is inherently mutable. There is
* however a conversion method to <code>java.util.Map</code>, and AMap implementations have factory methods that
* take <code>java.util.Map</code> instances.<p>
*
* The AMap contract is <em>not</em> hard-wired to <code>equals()</code> and <code>hashCode()</code> methods.
* Implementations are configurable through a pluggable equalityForEquals strategy, which defaults to equals() and hashCode()
* however. That allows e.g. using all AMap implementations based on object identity ('==') along the lines of what
* <code>java.util.IdentityHashMap</code> does.<p>
*
* Implementations (AHashMap in particular) use highly optimized algorithms to minimize 'copying' on modification.
*
* @author arno
*/
public interface AMap<K,V> extends Iterable<AMapEntry<K,V>>, Serializable {
static <K,V> AMap<K,V> empty() {
return AHashMap.empty ();
}
static <K,V> AMap<K,V> fromJava (Map<K,V> map) {
return AHashMap.fromJavaUtilMap (map);
}
/**
* @return an {@link AEquality} that returns {@code true} if and only if two elements are
* 'equal' in the sense that one would replace the other as a key.
*/
AEquality keyEquality ();
/**
* @return an empty {@link AMap} instance of the same type and configuration as this instance.
*/
AMap<K,V> clear();
/**
* @return the number of key-value pairs in this map.
*/
int size();
/**
* @return true if and only if this map's {@link #size()} is 0.
*/
boolean isEmpty();
/**
* @return true if and only if this map's {@link #size()} greater than 0.
*/
boolean nonEmpty();
/**
* Returns true iff the map contains the specified key. The containment check is based on the implementation's
* equalityForEquals strategy, which may or may not use <code>equals()</code>.
*/
boolean containsKey(K key);
/**
* Returns true iff the map contains the specified value.
*/
boolean containsValue(V value);
/**
* Returns the value stored for a given key. If the map contains the key, the corresponding value is wrapped in
* AOption.some(...), otherwise AOption.none() is returned.
*/
AOption<V> get(K key);
/**
* This is the equivalent of calling get(...).get(); implementations throw a NoSuchElementException if there is
* no entry for the key.
*/
V getRequired(K key);
/**
* This method 'adds' a new value for a given key, returning a modified copy of the map while leaving the original
* unmodified.
*/
AMap<K,V> updated(K key, V value);
/**
* This method 'removes' an entry from the map, returning a modified copy of the map while leaving the original
* unmodified.
*/
AMap<K,V> removed(K key);
/**
* Returns an iterator with all key/value pairs stored in the map. This method allows AMap instances to be used
* with the <code>for(...: map)</code> syntax introduced with Java 5.
*/
@Override Iterator<AMapEntry<K,V>> iterator();
/**
* Returns an <code>java.util.Set</code> with the map's keys. The returned object throws
* <code>UnsupportedOperationException</code> for all modifying operations.<p>
*
* The returned set is <em>not</em> guaranteed to provide uniqueness with regard to <code>equals()</code>. If the
* map's equalityForEquals strategy treats two objects as different even if their <code>equals</code> methods return true,
* then the returned set may contain both.
*/
ASet<K> keys();
/**
* Returns a <code>java.util.Collection</code> with the map's values. Duplicate values are returned as often as they
* occur. The returned collection throws <code>UnsupportedOperationException</code> for all modifying operations.
*/
ACollection<V> values();
/**
* Returns a read-only <code>java.util.Map</code> view of the AMap. Constructing the view takes constant time (i.e.
* there is no copying), lookup and iteration are passed to the underlying AMap. All modifying operations on the
* returned Map throw <code>UnsupportedOperationException</code>.
*/
java.util.Map<K,V> asJavaUtilMap();
/**
* This method wraps an AMap, causing a given defaultValue to be returned for all keys not explicitly present in
* the map. Looking up the value for a key not explicitly stored in the map does <em>not</em> modify the map.
*/
AMap<K,V> withDefaultValue(V defaultValue);
/**
* This method wraps an AMap. If one of the <code>get...</code> methods is called for a key not stored in the map,
* a function is called to determine the value to be returned. <p>
*
* NB: This does <em>not</em> cause the calculated value to be stored in the map; repeated calls for the same
* key trigger the value's calculation anew each time.
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/AMap.java
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface represents immutable maps with mutator methods (<code>updated(), removed()</code>) that return a
* new map instance with different members. Since all instances are immutable, they are thread-safe by definition.
* They are also useful in recursive algorithms.<p>
*
* This interface does not implement <code>java.util.Map</code> since that interface is inherently mutable. There is
* however a conversion method to <code>java.util.Map</code>, and AMap implementations have factory methods that
* take <code>java.util.Map</code> instances.<p>
*
* The AMap contract is <em>not</em> hard-wired to <code>equals()</code> and <code>hashCode()</code> methods.
* Implementations are configurable through a pluggable equalityForEquals strategy, which defaults to equals() and hashCode()
* however. That allows e.g. using all AMap implementations based on object identity ('==') along the lines of what
* <code>java.util.IdentityHashMap</code> does.<p>
*
* Implementations (AHashMap in particular) use highly optimized algorithms to minimize 'copying' on modification.
*
* @author arno
*/
public interface AMap<K,V> extends Iterable<AMapEntry<K,V>>, Serializable {
static <K,V> AMap<K,V> empty() {
return AHashMap.empty ();
}
static <K,V> AMap<K,V> fromJava (Map<K,V> map) {
return AHashMap.fromJavaUtilMap (map);
}
/**
* @return an {@link AEquality} that returns {@code true} if and only if two elements are
* 'equal' in the sense that one would replace the other as a key.
*/
AEquality keyEquality ();
/**
* @return an empty {@link AMap} instance of the same type and configuration as this instance.
*/
AMap<K,V> clear();
/**
* @return the number of key-value pairs in this map.
*/
int size();
/**
* @return true if and only if this map's {@link #size()} is 0.
*/
boolean isEmpty();
/**
* @return true if and only if this map's {@link #size()} greater than 0.
*/
boolean nonEmpty();
/**
* Returns true iff the map contains the specified key. The containment check is based on the implementation's
* equalityForEquals strategy, which may or may not use <code>equals()</code>.
*/
boolean containsKey(K key);
/**
* Returns true iff the map contains the specified value.
*/
boolean containsValue(V value);
/**
* Returns the value stored for a given key. If the map contains the key, the corresponding value is wrapped in
* AOption.some(...), otherwise AOption.none() is returned.
*/
AOption<V> get(K key);
/**
* This is the equivalent of calling get(...).get(); implementations throw a NoSuchElementException if there is
* no entry for the key.
*/
V getRequired(K key);
/**
* This method 'adds' a new value for a given key, returning a modified copy of the map while leaving the original
* unmodified.
*/
AMap<K,V> updated(K key, V value);
/**
* This method 'removes' an entry from the map, returning a modified copy of the map while leaving the original
* unmodified.
*/
AMap<K,V> removed(K key);
/**
* Returns an iterator with all key/value pairs stored in the map. This method allows AMap instances to be used
* with the <code>for(...: map)</code> syntax introduced with Java 5.
*/
@Override Iterator<AMapEntry<K,V>> iterator();
/**
* Returns an <code>java.util.Set</code> with the map's keys. The returned object throws
* <code>UnsupportedOperationException</code> for all modifying operations.<p>
*
* The returned set is <em>not</em> guaranteed to provide uniqueness with regard to <code>equals()</code>. If the
* map's equalityForEquals strategy treats two objects as different even if their <code>equals</code> methods return true,
* then the returned set may contain both.
*/
ASet<K> keys();
/**
* Returns a <code>java.util.Collection</code> with the map's values. Duplicate values are returned as often as they
* occur. The returned collection throws <code>UnsupportedOperationException</code> for all modifying operations.
*/
ACollection<V> values();
/**
* Returns a read-only <code>java.util.Map</code> view of the AMap. Constructing the view takes constant time (i.e.
* there is no copying), lookup and iteration are passed to the underlying AMap. All modifying operations on the
* returned Map throw <code>UnsupportedOperationException</code>.
*/
java.util.Map<K,V> asJavaUtilMap();
/**
* This method wraps an AMap, causing a given defaultValue to be returned for all keys not explicitly present in
* the map. Looking up the value for a key not explicitly stored in the map does <em>not</em> modify the map.
*/
AMap<K,V> withDefaultValue(V defaultValue);
/**
* This method wraps an AMap. If one of the <code>get...</code> methods is called for a key not stored in the map,
* a function is called to determine the value to be returned. <p>
*
* NB: This does <em>not</em> cause the calculated value to be stored in the map; repeated calls for the same
* key trigger the value's calculation anew each time.
*/
|
AMap<K,V> withDefault(AFunction1<? super K, ? extends V, ? extends RuntimeException> function);
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SharedQueueNonblockPushBlockPopImpl.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
|
}
private int asArrayIndex (long l) {
return (int) (l & mask);
}
//------------- Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_TASKS;
private static final long SCALE_TASKS;
private static final long OFFS_LOCK;
private static final long OFFS_BASE;
private static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_TASKS = UNSAFE.arrayBaseOffset (Runnable[].class);
SCALE_TASKS = UNSAFE.arrayIndexScale (Runnable[].class);
OFFS_LOCK = UNSAFE.objectFieldOffset (SharedQueueNonblockPushBlockPopImpl.class.getDeclaredField ("lock"));
OFFS_BASE = UNSAFE.objectFieldOffset (SharedQueueNonblockPushBlockPopImpl.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (SharedQueueNonblockPushBlockPopImpl.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SharedQueueNonblockPushBlockPopImpl.java
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
}
private int asArrayIndex (long l) {
return (int) (l & mask);
}
//------------- Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_TASKS;
private static final long SCALE_TASKS;
private static final long OFFS_LOCK;
private static final long OFFS_BASE;
private static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_TASKS = UNSAFE.arrayBaseOffset (Runnable[].class);
SCALE_TASKS = UNSAFE.arrayIndexScale (Runnable[].class);
OFFS_LOCK = UNSAFE.objectFieldOffset (SharedQueueNonblockPushBlockPopImpl.class.getDeclaredField ("lock"));
OFFS_BASE = UNSAFE.objectFieldOffset (SharedQueueNonblockPushBlockPopImpl.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (SharedQueueNonblockPushBlockPopImpl.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
AUnchecker.throwUnchecked (e);
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SharedQueueBlockPushBlockPopImpl.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
|
final Runnable result = tasks [arrIdx];
if (result != null) tasks[arrIdx] = null; //TODO remove the check
return result;
}
@Override public synchronized void clear () {
final long _top = top;
for (long _base=base; _base < _top; _base++) {
tasks[asArrayIndex (_base)] = null;
}
UNSAFE.putLongVolatile (this, OFFS_BASE, _top);
}
//------------- Unsafe stuff
static final Unsafe UNSAFE;
static final long OFFS_BASE;
static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_BASE = UNSAFE.objectFieldOffset (SharedQueueBlockPushBlockPopImpl.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (SharedQueueBlockPushBlockPopImpl.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SharedQueueBlockPushBlockPopImpl.java
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
final Runnable result = tasks [arrIdx];
if (result != null) tasks[arrIdx] = null; //TODO remove the check
return result;
}
@Override public synchronized void clear () {
final long _top = top;
for (long _base=base; _base < _top; _base++) {
tasks[asArrayIndex (_base)] = null;
}
UNSAFE.putLongVolatile (this, OFFS_BASE, _top);
}
//------------- Unsafe stuff
static final Unsafe UNSAFE;
static final long OFFS_BASE;
static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_BASE = UNSAFE.objectFieldOffset (SharedQueueBlockPushBlockPopImpl.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (SharedQueueBlockPushBlockPopImpl.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
AUnchecker.throwUnchecked (e);
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction0.java
// public interface AFunction0<R, E extends Throwable> extends Serializable {
// R apply() throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement0.java
// public interface AStatement0<E extends Throwable> extends Serializable {
// void apply() throws E;
// }
|
import com.ajjpj.afoundation.function.AFunction0;
import com.ajjpj.afoundation.function.AStatement0;
|
package com.ajjpj.afoundation.util;
/**
* This class throws an arbitrary exception without requiring it to be declared in a throws clause
*
* @author arno
*/
public class AUnchecker {
public static void throwUnchecked(Throwable th) {
AUnchecker.<RuntimeException> doIt(th);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void doIt(Throwable th) throws T {
throw (T) th;
}
@SuppressWarnings("unused")
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction0.java
// public interface AFunction0<R, E extends Throwable> extends Serializable {
// R apply() throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement0.java
// public interface AStatement0<E extends Throwable> extends Serializable {
// void apply() throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
import com.ajjpj.afoundation.function.AFunction0;
import com.ajjpj.afoundation.function.AStatement0;
package com.ajjpj.afoundation.util;
/**
* This class throws an arbitrary exception without requiring it to be declared in a throws clause
*
* @author arno
*/
public class AUnchecker {
public static void throwUnchecked(Throwable th) {
AUnchecker.<RuntimeException> doIt(th);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void doIt(Throwable th) throws T {
throw (T) th;
}
@SuppressWarnings("unused")
|
public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction0.java
// public interface AFunction0<R, E extends Throwable> extends Serializable {
// R apply() throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement0.java
// public interface AStatement0<E extends Throwable> extends Serializable {
// void apply() throws E;
// }
|
import com.ajjpj.afoundation.function.AFunction0;
import com.ajjpj.afoundation.function.AStatement0;
|
package com.ajjpj.afoundation.util;
/**
* This class throws an arbitrary exception without requiring it to be declared in a throws clause
*
* @author arno
*/
public class AUnchecker {
public static void throwUnchecked(Throwable th) {
AUnchecker.<RuntimeException> doIt(th);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void doIt(Throwable th) throws T {
throw (T) th;
}
@SuppressWarnings("unused")
public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
try {
callback.apply();
}
catch (Throwable exc) {
throwUnchecked (exc);
}
}
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction0.java
// public interface AFunction0<R, E extends Throwable> extends Serializable {
// R apply() throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement0.java
// public interface AStatement0<E extends Throwable> extends Serializable {
// void apply() throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
import com.ajjpj.afoundation.function.AFunction0;
import com.ajjpj.afoundation.function.AStatement0;
package com.ajjpj.afoundation.util;
/**
* This class throws an arbitrary exception without requiring it to be declared in a throws clause
*
* @author arno
*/
public class AUnchecker {
public static void throwUnchecked(Throwable th) {
AUnchecker.<RuntimeException> doIt(th);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void doIt(Throwable th) throws T {
throw (T) th;
}
@SuppressWarnings("unused")
public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
try {
callback.apply();
}
catch (Throwable exc) {
throwUnchecked (exc);
}
}
|
public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
|
public abstract <X extends Throwable> void foreach (AStatement1<T, X> f) throws X;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
public abstract <X extends Throwable> void foreach (AStatement1<T, X> f) throws X;
/**
* @return This method returns a new ATry with inverted 'success' semantics: If the original ATry is a success,
* the newly created ATry is a failure with a {@link SuccessfulCompletionException} as its cause, and if the
* original ATry is a failure, the newly created ATry is a success with the causing Throwable as its value.
*/
public abstract ATry<Throwable> inverse ();
/**
* This method creates a new ATry applying a given function to the value if this ATry is successful, or returns
* this ATry's failure unchanged.
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
public abstract <X extends Throwable> void foreach (AStatement1<T, X> f) throws X;
/**
* @return This method returns a new ATry with inverted 'success' semantics: If the original ATry is a success,
* the newly created ATry is a failure with a {@link SuccessfulCompletionException} as its cause, and if the
* original ATry is a failure, the newly created ATry is a success with the causing Throwable as its value.
*/
public abstract ATry<Throwable> inverse ();
/**
* This method creates a new ATry applying a given function to the value if this ATry is successful, or returns
* this ATry's failure unchanged.
*/
|
public abstract <S, E extends Throwable> ATry<S> map (AFunction1<T, S, E> f) throws E;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
public abstract <X extends Throwable> void foreach (AStatement1<T, X> f) throws X;
/**
* @return This method returns a new ATry with inverted 'success' semantics: If the original ATry is a success,
* the newly created ATry is a failure with a {@link SuccessfulCompletionException} as its cause, and if the
* original ATry is a failure, the newly created ATry is a success with the causing Throwable as its value.
*/
public abstract ATry<Throwable> inverse ();
/**
* This method creates a new ATry applying a given function to the value if this ATry is successful, or returns
* this ATry's failure unchanged.
*/
public abstract <S, E extends Throwable> ATry<S> map (AFunction1<T, S, E> f) throws E;
/**
* @return true if and only if this ATry is a success.
*/
public abstract boolean isSuccess ();
/**
* @return true if and only if this ATry is a failure.
*/
public boolean isFailure () {
return !isSuccess ();
}
/**
* @return this ATry's value if it is a success, and the underlying Throwable if it is a failure
*/
public abstract T getValue ();
/**
* If this is a failure and the given function {@link APartialFunction#isDefinedAt is defined at} the Throwable,
* a new successful ATry is created with the function's result. Otherwise this ATry is returned unmodified.
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
public abstract <X extends Throwable> void foreach (AStatement1<T, X> f) throws X;
/**
* @return This method returns a new ATry with inverted 'success' semantics: If the original ATry is a success,
* the newly created ATry is a failure with a {@link SuccessfulCompletionException} as its cause, and if the
* original ATry is a failure, the newly created ATry is a success with the causing Throwable as its value.
*/
public abstract ATry<Throwable> inverse ();
/**
* This method creates a new ATry applying a given function to the value if this ATry is successful, or returns
* this ATry's failure unchanged.
*/
public abstract <S, E extends Throwable> ATry<S> map (AFunction1<T, S, E> f) throws E;
/**
* @return true if and only if this ATry is a success.
*/
public abstract boolean isSuccess ();
/**
* @return true if and only if this ATry is a failure.
*/
public boolean isFailure () {
return !isSuccess ();
}
/**
* @return this ATry's value if it is a success, and the underlying Throwable if it is a failure
*/
public abstract T getValue ();
/**
* If this is a failure and the given function {@link APartialFunction#isDefinedAt is defined at} the Throwable,
* a new successful ATry is created with the function's result. Otherwise this ATry is returned unmodified.
*/
|
public abstract <E extends Throwable> ATry<T> recover (APartialFunction<Throwable, T, E> f) throws E;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
public abstract <X extends Throwable> void foreach (AStatement1<T, X> f) throws X;
/**
* @return This method returns a new ATry with inverted 'success' semantics: If the original ATry is a success,
* the newly created ATry is a failure with a {@link SuccessfulCompletionException} as its cause, and if the
* original ATry is a failure, the newly created ATry is a success with the causing Throwable as its value.
*/
public abstract ATry<Throwable> inverse ();
/**
* This method creates a new ATry applying a given function to the value if this ATry is successful, or returns
* this ATry's failure unchanged.
*/
public abstract <S, E extends Throwable> ATry<S> map (AFunction1<T, S, E> f) throws E;
/**
* @return true if and only if this ATry is a success.
*/
public abstract boolean isSuccess ();
/**
* @return true if and only if this ATry is a failure.
*/
public boolean isFailure () {
return !isSuccess ();
}
/**
* @return this ATry's value if it is a success, and the underlying Throwable if it is a failure
*/
public abstract T getValue ();
/**
* If this is a failure and the given function {@link APartialFunction#isDefinedAt is defined at} the Throwable,
* a new successful ATry is created with the function's result. Otherwise this ATry is returned unmodified.
*/
public abstract <E extends Throwable> ATry<T> recover (APartialFunction<Throwable, T, E> f) throws E;
/**
* If this is a failure and the given function {@link APartialFunction#isDefinedAt is defined at} the Throwable,
* the function's result is returned. Otherwise this ATry is returned unmodified.
*/
public abstract <E extends Throwable> ATry<T> recoverWith (APartialFunction<Throwable, ATry<T>, E> f) throws E;
//TODO more operations
static class ASuccess<T> extends ATry<T> {
final T value;
private ASuccess (T value) {
this.value = value;
}
@Override public <X extends Throwable> void foreach (AStatement1<T, X> f) throws X {
f.apply (value);
}
@Override public ATry<Throwable> inverse () {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
package com.ajjpj.afoundation.collection.immutable;
/**
* An ATry represents either a value ('success') or a Throwable that occurred trying to provide the value ('failure').
*/
public abstract class ATry<T> {
/**
* This method creates a successful ATry.
*/
public static <T> ATry<T> success (T o) {
return new ASuccess<> (o);
}
/**
* This method creates a failed ATry.
*/
public static <T> ATry<T> failure (Throwable th) {
return new AFailure<> (th);
}
/**
* This method executed a statement for the value (in case of success), or does nothing (in case of failure).
*/
public abstract <X extends Throwable> void foreach (AStatement1<T, X> f) throws X;
/**
* @return This method returns a new ATry with inverted 'success' semantics: If the original ATry is a success,
* the newly created ATry is a failure with a {@link SuccessfulCompletionException} as its cause, and if the
* original ATry is a failure, the newly created ATry is a success with the causing Throwable as its value.
*/
public abstract ATry<Throwable> inverse ();
/**
* This method creates a new ATry applying a given function to the value if this ATry is successful, or returns
* this ATry's failure unchanged.
*/
public abstract <S, E extends Throwable> ATry<S> map (AFunction1<T, S, E> f) throws E;
/**
* @return true if and only if this ATry is a success.
*/
public abstract boolean isSuccess ();
/**
* @return true if and only if this ATry is a failure.
*/
public boolean isFailure () {
return !isSuccess ();
}
/**
* @return this ATry's value if it is a success, and the underlying Throwable if it is a failure
*/
public abstract T getValue ();
/**
* If this is a failure and the given function {@link APartialFunction#isDefinedAt is defined at} the Throwable,
* a new successful ATry is created with the function's result. Otherwise this ATry is returned unmodified.
*/
public abstract <E extends Throwable> ATry<T> recover (APartialFunction<Throwable, T, E> f) throws E;
/**
* If this is a failure and the given function {@link APartialFunction#isDefinedAt is defined at} the Throwable,
* the function's result is returned. Otherwise this ATry is returned unmodified.
*/
public abstract <E extends Throwable> ATry<T> recoverWith (APartialFunction<Throwable, ATry<T>, E> f) throws E;
//TODO more operations
static class ASuccess<T> extends ATry<T> {
final T value;
private ASuccess (T value) {
this.value = value;
}
@Override public <X extends Throwable> void foreach (AStatement1<T, X> f) throws X {
f.apply (value);
}
@Override public ATry<Throwable> inverse () {
|
return ATry.failure (new SuccessfulCompletionException (value));
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
|
@Override public <E extends Throwable> ATry<T> recoverWith (APartialFunction<Throwable, ATry<T>, E> f) throws E {
return this;
}
}
static class AFailure<T> extends ATry<T> {
final Throwable th;
private AFailure (Throwable th) {
this.th = th;
}
@Override public <X extends Throwable> void foreach (AStatement1<T, X> f) throws X {
}
@Override public ATry<Throwable> inverse () {
return ATry.success (th);
}
@Override public <S, E extends Throwable> ATry<S> map (AFunction1<T, S, E> f) throws E {
//noinspection unchecked
return (ATry<S>) this;
}
@Override public boolean isSuccess () {
return false;
}
@Override public T getValue () {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SuccessfulCompletionException.java
// public class SuccessfulCompletionException extends RuntimeException {
// private final Object originalResult;
//
// public SuccessfulCompletionException (Object originalResult) {
// this.originalResult = originalResult;
// }
//
// /**
// * @return the 'success' value result
// */
// public Object getOriginalResult () {
// return originalResult;
// }
//
// @Override public synchronized Throwable fillInStackTrace () {
// return this;
// }
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ATry.java
import com.ajjpj.afoundation.concurrent.SuccessfulCompletionException;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.util.AUnchecker;
@Override public <E extends Throwable> ATry<T> recoverWith (APartialFunction<Throwable, ATry<T>, E> f) throws E {
return this;
}
}
static class AFailure<T> extends ATry<T> {
final Throwable th;
private AFailure (Throwable th) {
this.th = th;
}
@Override public <X extends Throwable> void foreach (AStatement1<T, X> f) throws X {
}
@Override public ATry<Throwable> inverse () {
return ATry.success (th);
}
@Override public <S, E extends Throwable> ATry<S> map (AFunction1<T, S, E> f) throws E {
//noinspection unchecked
return (ATry<S>) this;
}
@Override public boolean isSuccess () {
return false;
}
@Override public T getValue () {
|
AUnchecker.throwUnchecked (th);
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/io/AJsonSerHelper.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
|
import com.ajjpj.afoundation.function.AStatement1;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Locale;
|
public void writeStringArray (Iterable<String> values) throws IOException {
startArray ();
for (String el: values) writeStringLiteral (el);
endArray ();
}
public void writeStringField (String key, String value) throws IOException {
writeKey (key);
writeStringLiteral (value);
}
public void writeBooleanField (String key, Boolean value) throws IOException {
writeKey (key);
if (value == null) writeNullLiteral ();
else writeBooleanLiteral (value);
}
public void writeIntField (String key, Integer value) throws IOException {
writeKey (key);
if (value == null) writeNullLiteral ();
else writeIntLiteral (value);
}
public void writeLongField (String key, Long value) throws IOException {
writeKey (key);
if (value == null) writeNullLiteral ();
else writeLongLiteral (value);
}
/**
* This is a convenience method for building simple JSON strings. It passes an AJsonSerHelper to a callback and
* builds a string based on what the callback does with it.
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/io/AJsonSerHelper.java
import com.ajjpj.afoundation.function.AStatement1;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Locale;
public void writeStringArray (Iterable<String> values) throws IOException {
startArray ();
for (String el: values) writeStringLiteral (el);
endArray ();
}
public void writeStringField (String key, String value) throws IOException {
writeKey (key);
writeStringLiteral (value);
}
public void writeBooleanField (String key, Boolean value) throws IOException {
writeKey (key);
if (value == null) writeNullLiteral ();
else writeBooleanLiteral (value);
}
public void writeIntField (String key, Integer value) throws IOException {
writeKey (key);
if (value == null) writeNullLiteral ();
else writeIntLiteral (value);
}
public void writeLongField (String key, Long value) throws IOException {
writeKey (key);
if (value == null) writeNullLiteral ();
else writeLongLiteral (value);
}
/**
* This is a convenience method for building simple JSON strings. It passes an AJsonSerHelper to a callback and
* builds a string based on what the callback does with it.
*/
|
public static <E extends Throwable> String buildString (AStatement1<AJsonSerHelper, E> code) throws E {
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ACollection.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
|
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
import java.util.Collection;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains methods provided by all a-base collections. Implementing <code>Iterable</code> allows
* collections to be used with Java's <code>for(....: collection)</code> syntax introduced with version 1.5.<p>
*
* The first generic parameter T represents the collection's element type, while the second parameter represents
* the concrete collection class.
*
* @author arno
*/
public interface ACollection<T> extends ATraversable<T>, Iterable<T> {
/**
* @return an empty {@link ACollection} of the same size as this one.
*/
ACollection<T> clear();
/**
* @return the number of elements in this {@link ACollection}.
*/
int size();
/**
* @return true if and only if this collection's size is 0
*/
boolean isEmpty();
/**
* @return true if and only if this collection's size is greater than 0
*/
boolean nonEmpty();
/**
* This method checks if the collection has an element that is 'equal' to the parameter {@code el}. For collections
* that have a configurable {@link com.ajjpj.afoundation.collection.AEquality}, that equality is used to check
* containment. This applies to {@link ASet} instances in particular.
*/
boolean contains (T el);
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ACollection.java
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
import java.util.Collection;
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains methods provided by all a-base collections. Implementing <code>Iterable</code> allows
* collections to be used with Java's <code>for(....: collection)</code> syntax introduced with version 1.5.<p>
*
* The first generic parameter T represents the collection's element type, while the second parameter represents
* the concrete collection class.
*
* @author arno
*/
public interface ACollection<T> extends ATraversable<T>, Iterable<T> {
/**
* @return an empty {@link ACollection} of the same size as this one.
*/
ACollection<T> clear();
/**
* @return the number of elements in this {@link ACollection}.
*/
int size();
/**
* @return true if and only if this collection's size is 0
*/
boolean isEmpty();
/**
* @return true if and only if this collection's size is greater than 0
*/
boolean nonEmpty();
/**
* This method checks if the collection has an element that is 'equal' to the parameter {@code el}. For collections
* that have a configurable {@link com.ajjpj.afoundation.collection.AEquality}, that equality is used to check
* containment. This applies to {@link ASet} instances in particular.
*/
boolean contains (T el);
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
|
@Override <E extends Throwable> ACollection<T> filter(APredicate<? super T, E> pred) throws E;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ACollection.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
|
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
import java.util.Collection;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains methods provided by all a-base collections. Implementing <code>Iterable</code> allows
* collections to be used with Java's <code>for(....: collection)</code> syntax introduced with version 1.5.<p>
*
* The first generic parameter T represents the collection's element type, while the second parameter represents
* the concrete collection class.
*
* @author arno
*/
public interface ACollection<T> extends ATraversable<T>, Iterable<T> {
/**
* @return an empty {@link ACollection} of the same size as this one.
*/
ACollection<T> clear();
/**
* @return the number of elements in this {@link ACollection}.
*/
int size();
/**
* @return true if and only if this collection's size is 0
*/
boolean isEmpty();
/**
* @return true if and only if this collection's size is greater than 0
*/
boolean nonEmpty();
/**
* This method checks if the collection has an element that is 'equal' to the parameter {@code el}. For collections
* that have a configurable {@link com.ajjpj.afoundation.collection.AEquality}, that equality is used to check
* containment. This applies to {@link ASet} instances in particular.
*/
boolean contains (T el);
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
@Override <E extends Throwable> ACollection<T> filter(APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
@Override <E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ACollection.java
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
import java.util.Collection;
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains methods provided by all a-base collections. Implementing <code>Iterable</code> allows
* collections to be used with Java's <code>for(....: collection)</code> syntax introduced with version 1.5.<p>
*
* The first generic parameter T represents the collection's element type, while the second parameter represents
* the concrete collection class.
*
* @author arno
*/
public interface ACollection<T> extends ATraversable<T>, Iterable<T> {
/**
* @return an empty {@link ACollection} of the same size as this one.
*/
ACollection<T> clear();
/**
* @return the number of elements in this {@link ACollection}.
*/
int size();
/**
* @return true if and only if this collection's size is 0
*/
boolean isEmpty();
/**
* @return true if and only if this collection's size is greater than 0
*/
boolean nonEmpty();
/**
* This method checks if the collection has an element that is 'equal' to the parameter {@code el}. For collections
* that have a configurable {@link com.ajjpj.afoundation.collection.AEquality}, that equality is used to check
* containment. This applies to {@link ASet} instances in particular.
*/
boolean contains (T el);
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
@Override <E extends Throwable> ACollection<T> filter(APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
@Override <E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
|
@Override <X, E extends Throwable> ACollection<X> map(AFunction1<? super T, ? extends X, E> f) throws E;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ACollection.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
|
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
import java.util.Collection;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains methods provided by all a-base collections. Implementing <code>Iterable</code> allows
* collections to be used with Java's <code>for(....: collection)</code> syntax introduced with version 1.5.<p>
*
* The first generic parameter T represents the collection's element type, while the second parameter represents
* the concrete collection class.
*
* @author arno
*/
public interface ACollection<T> extends ATraversable<T>, Iterable<T> {
/**
* @return an empty {@link ACollection} of the same size as this one.
*/
ACollection<T> clear();
/**
* @return the number of elements in this {@link ACollection}.
*/
int size();
/**
* @return true if and only if this collection's size is 0
*/
boolean isEmpty();
/**
* @return true if and only if this collection's size is greater than 0
*/
boolean nonEmpty();
/**
* This method checks if the collection has an element that is 'equal' to the parameter {@code el}. For collections
* that have a configurable {@link com.ajjpj.afoundation.collection.AEquality}, that equality is used to check
* containment. This applies to {@link ASet} instances in particular.
*/
boolean contains (T el);
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
@Override <E extends Throwable> ACollection<T> filter(APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
@Override <E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
@Override <X, E extends Throwable> ACollection<X> map(AFunction1<? super T, ? extends X, E> f) throws E;
@Override <X, E extends Throwable> ACollection<X> flatMap(AFunction1<? super T, ? extends Iterable<X>, E> f) throws E;
/**
* Turns a collection of collections into a 'flat' collection, removing one layer of collections.
*/
<X> ACollection<X> flatten();
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ACollection.java
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
import java.util.Collection;
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains methods provided by all a-base collections. Implementing <code>Iterable</code> allows
* collections to be used with Java's <code>for(....: collection)</code> syntax introduced with version 1.5.<p>
*
* The first generic parameter T represents the collection's element type, while the second parameter represents
* the concrete collection class.
*
* @author arno
*/
public interface ACollection<T> extends ATraversable<T>, Iterable<T> {
/**
* @return an empty {@link ACollection} of the same size as this one.
*/
ACollection<T> clear();
/**
* @return the number of elements in this {@link ACollection}.
*/
int size();
/**
* @return true if and only if this collection's size is 0
*/
boolean isEmpty();
/**
* @return true if and only if this collection's size is greater than 0
*/
boolean nonEmpty();
/**
* This method checks if the collection has an element that is 'equal' to the parameter {@code el}. For collections
* that have a configurable {@link com.ajjpj.afoundation.collection.AEquality}, that equality is used to check
* containment. This applies to {@link ASet} instances in particular.
*/
boolean contains (T el);
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
@Override <E extends Throwable> ACollection<T> filter(APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
@Override <E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
@Override <X, E extends Throwable> ACollection<X> map(AFunction1<? super T, ? extends X, E> f) throws E;
@Override <X, E extends Throwable> ACollection<X> flatMap(AFunction1<? super T, ? extends Iterable<X>, E> f) throws E;
/**
* Turns a collection of collections into a 'flat' collection, removing one layer of collections.
*/
<X> ACollection<X> flatten();
|
@Override <X, E extends Throwable> ACollection<X> collect (APartialFunction<? super T, ? extends X, E> pf) throws E;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/LocalQueue.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
|
private long taskOffset (long l) {
return OFFS_TASKS + SCALE_TASKS * (l & mask);
}
int asArrayindex (long l) {
return (int) (l & mask);
}
//------------- Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_TASKS;
private static final long SCALE_TASKS;
private static final long OFFS_BASE;
static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_TASKS = UNSAFE.arrayBaseOffset (Runnable[].class);
SCALE_TASKS = UNSAFE.arrayIndexScale (Runnable[].class);
OFFS_BASE = UNSAFE.objectFieldOffset (LocalQueue.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (LocalQueue.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/LocalQueue.java
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
private long taskOffset (long l) {
return OFFS_TASKS + SCALE_TASKS * (l & mask);
}
int asArrayindex (long l) {
return (int) (l & mask);
}
//------------- Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_TASKS;
private static final long SCALE_TASKS;
private static final long OFFS_BASE;
static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_TASKS = UNSAFE.arrayBaseOffset (Runnable[].class);
SCALE_TASKS = UNSAFE.arrayIndexScale (Runnable[].class);
OFFS_BASE = UNSAFE.objectFieldOffset (LocalQueue.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (LocalQueue.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
AUnchecker.throwUnchecked (e);
|
arnohaase/a-foundation
|
a-foundation-benchmark/src/main/java/com/ajjpj/afoundation/concurrent/jdk/j9new/ForkJoinPool.java
|
// Path: a-foundation-benchmark/src/main/java/com/ajjpj/afoundation/concurrent/jdk/ThreadLocalRandomHelper.java
// public class ThreadLocalRandomHelper {
//
// public static int nextSecondarySeed() {
// int r;
// Thread t = Thread.currentThread();
// if ((r = UNSAFE.getInt(t, SECONDARY)) != 0) {
// r ^= r << 13; // xorshift
// r ^= r >>> 17;
// r ^= r << 5;
// }
// else {
// localInit();
// if ((r = (int)UNSAFE.getLong(t, SEED)) == 0)
// r = 1; // avoid zero
// }
// UNSAFE.putInt(t, SECONDARY, r);
// return r;
// }
// public static void localInit () {
// try {
// LOCAL_INIT.invoke (null);
// }
// catch (Exception e) {
// AUnchecker.throwUnchecked (e);
// }
// }
//
// public static int getProbe () {
// return UNSAFE.getInt (Thread.currentThread (), PROBE);
// }
//
// public static int advanceProbe (int probe) {
// probe ^= probe << 13; // xorshift
// probe ^= probe >>> 17;
// probe ^= probe << 5;
// UNSAFE.putInt(Thread.currentThread(), PROBE, probe);
// return probe;
// }
//
// private static final Unsafe UNSAFE;
// private static final long SEED;
// private static final long PROBE;
// private static final long SECONDARY;
// private static final Method LOCAL_INIT;
//
// static {
// try {
// LOCAL_INIT = ThreadLocalRandom.class.getDeclaredMethod ("localInit");
// LOCAL_INIT.setAccessible (true);
//
// final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
// f.setAccessible (true);
// UNSAFE = (Unsafe) f.get (null);
//
// Class<?> tk = Thread.class;
// SEED = UNSAFE.objectFieldOffset
// (tk.getDeclaredField("threadLocalRandomSeed"));
// PROBE = UNSAFE.objectFieldOffset
// (tk.getDeclaredField("threadLocalRandomProbe"));
// SECONDARY = UNSAFE.objectFieldOffset
// (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
// } catch (Exception e) {
// throw new Error(e);
// }
// }
//
// }
|
import com.ajjpj.afoundation.concurrent.jdk.ThreadLocalRandomHelper;
import sun.misc.Unsafe;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.security.AccessControlContext;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
|
/**
* Acquires the runState lock; returns current (locked) runState.
*/
private int lockRunState() {
int rs;
return ((((rs = runState) & RSLOCK) != 0 ||
!U.compareAndSwapInt(this, RUNSTATE, rs, rs |= RSLOCK)) ?
awaitRunStateLock() : rs);
}
/**
* Spins and/or blocks until runstate lock is available. See
* above for explanation.
*/
private int awaitRunStateLock() {
Object lock;
boolean wasInterrupted = false;
for (int spins = SPINS, r = 0, rs, ns;;) {
if (((rs = runState) & RSLOCK) == 0) {
if (U.compareAndSwapInt(this, RUNSTATE, rs, ns = rs | RSLOCK)) {
if (wasInterrupted) {
try {
Thread.currentThread().interrupt();
} catch (SecurityException ignore) {
}
}
return ns;
}
}
else if (r == 0)
|
// Path: a-foundation-benchmark/src/main/java/com/ajjpj/afoundation/concurrent/jdk/ThreadLocalRandomHelper.java
// public class ThreadLocalRandomHelper {
//
// public static int nextSecondarySeed() {
// int r;
// Thread t = Thread.currentThread();
// if ((r = UNSAFE.getInt(t, SECONDARY)) != 0) {
// r ^= r << 13; // xorshift
// r ^= r >>> 17;
// r ^= r << 5;
// }
// else {
// localInit();
// if ((r = (int)UNSAFE.getLong(t, SEED)) == 0)
// r = 1; // avoid zero
// }
// UNSAFE.putInt(t, SECONDARY, r);
// return r;
// }
// public static void localInit () {
// try {
// LOCAL_INIT.invoke (null);
// }
// catch (Exception e) {
// AUnchecker.throwUnchecked (e);
// }
// }
//
// public static int getProbe () {
// return UNSAFE.getInt (Thread.currentThread (), PROBE);
// }
//
// public static int advanceProbe (int probe) {
// probe ^= probe << 13; // xorshift
// probe ^= probe >>> 17;
// probe ^= probe << 5;
// UNSAFE.putInt(Thread.currentThread(), PROBE, probe);
// return probe;
// }
//
// private static final Unsafe UNSAFE;
// private static final long SEED;
// private static final long PROBE;
// private static final long SECONDARY;
// private static final Method LOCAL_INIT;
//
// static {
// try {
// LOCAL_INIT = ThreadLocalRandom.class.getDeclaredMethod ("localInit");
// LOCAL_INIT.setAccessible (true);
//
// final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
// f.setAccessible (true);
// UNSAFE = (Unsafe) f.get (null);
//
// Class<?> tk = Thread.class;
// SEED = UNSAFE.objectFieldOffset
// (tk.getDeclaredField("threadLocalRandomSeed"));
// PROBE = UNSAFE.objectFieldOffset
// (tk.getDeclaredField("threadLocalRandomProbe"));
// SECONDARY = UNSAFE.objectFieldOffset
// (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
// } catch (Exception e) {
// throw new Error(e);
// }
// }
//
// }
// Path: a-foundation-benchmark/src/main/java/com/ajjpj/afoundation/concurrent/jdk/j9new/ForkJoinPool.java
import com.ajjpj.afoundation.concurrent.jdk.ThreadLocalRandomHelper;
import sun.misc.Unsafe;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.security.AccessControlContext;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* Acquires the runState lock; returns current (locked) runState.
*/
private int lockRunState() {
int rs;
return ((((rs = runState) & RSLOCK) != 0 ||
!U.compareAndSwapInt(this, RUNSTATE, rs, rs |= RSLOCK)) ?
awaitRunStateLock() : rs);
}
/**
* Spins and/or blocks until runstate lock is available. See
* above for explanation.
*/
private int awaitRunStateLock() {
Object lock;
boolean wasInterrupted = false;
for (int spins = SPINS, r = 0, rs, ns;;) {
if (((rs = runState) & RSLOCK) == 0) {
if (U.compareAndSwapInt(this, RUNSTATE, rs, ns = rs | RSLOCK)) {
if (wasInterrupted) {
try {
Thread.currentThread().interrupt();
} catch (SecurityException ignore) {
}
}
return ns;
}
}
else if (r == 0)
|
r = ThreadLocalRandomHelper.nextSecondarySeed ();
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/AMonadicOps.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
|
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains those functional operations that are supported for all kinds of collections. This is the greatest common
* denominator of all a-base collection classes.
*
* @author arno
*/
public interface AMonadicOps<T> {
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filter (APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
/**
* Turns a collection of collections into a 'flat' collection, removing one layer of collections.
*/
<X> AMonadicOps<X> flatten();
/**
* Applies a transformation function to each element, creating a new collection instance from the results. For a
* collection of strings, this could e.g. be used to create a collection of integer values with each string's length.
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/AMonadicOps.java
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains those functional operations that are supported for all kinds of collections. This is the greatest common
* denominator of all a-base collection classes.
*
* @author arno
*/
public interface AMonadicOps<T> {
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filter (APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
/**
* Turns a collection of collections into a 'flat' collection, removing one layer of collections.
*/
<X> AMonadicOps<X> flatten();
/**
* Applies a transformation function to each element, creating a new collection instance from the results. For a
* collection of strings, this could e.g. be used to create a collection of integer values with each string's length.
*/
|
<X,E extends Throwable> AMonadicOps<X> map(AFunction1<? super T, ? extends X, E> f) throws E;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/AMonadicOps.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
|
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains those functional operations that are supported for all kinds of collections. This is the greatest common
* denominator of all a-base collection classes.
*
* @author arno
*/
public interface AMonadicOps<T> {
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filter (APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
/**
* Turns a collection of collections into a 'flat' collection, removing one layer of collections.
*/
<X> AMonadicOps<X> flatten();
/**
* Applies a transformation function to each element, creating a new collection instance from the results. For a
* collection of strings, this could e.g. be used to create a collection of integer values with each string's length.
*/
<X,E extends Throwable> AMonadicOps<X> map(AFunction1<? super T, ? extends X, E> f) throws E;
/**
* Maps each element to a collection of values, flattening the results into a single collection. Let there be a
* collection of strings. Calling <code>flatMap</code> with a function that splits a string into tokens, the result
* would be a collection of all tokens of all original strings.
*/
<X, E extends Throwable> AMonadicOps<X> flatMap(AFunction1<? super T, ? extends Iterable<X>, E> f) throws E;
/**
* Applies a transformation function to all elements of a collection, where the partial function is defined for. Creates a new collection
* of the transformed elements only. So the number of result elements may be less than the number of elements in the source collection.
*/
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APartialFunction.java
// public interface APartialFunction<P, R, E extends Throwable> extends AFunction1<P, R, E> {
// boolean isDefinedAt (P param);
// }
//
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/APredicate.java
// public interface APredicate<T,E extends Throwable> extends Serializable {
// boolean apply(T o) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/AMonadicOps.java
import com.ajjpj.afoundation.function.AFunction1;
import com.ajjpj.afoundation.function.APartialFunction;
import com.ajjpj.afoundation.function.APredicate;
package com.ajjpj.afoundation.collection.immutable;
/**
* This interface contains those functional operations that are supported for all kinds of collections. This is the greatest common
* denominator of all a-base collection classes.
*
* @author arno
*/
public interface AMonadicOps<T> {
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filter (APredicate<? super T, E> pred) throws E;
/**
* Filters this collection's elements, this method returns a new collection comprised of only those elements that do not match
* a given predicate.
*/
<E extends Throwable> AMonadicOps<T> filterNot (APredicate<? super T, E> pred) throws E;
/**
* Turns a collection of collections into a 'flat' collection, removing one layer of collections.
*/
<X> AMonadicOps<X> flatten();
/**
* Applies a transformation function to each element, creating a new collection instance from the results. For a
* collection of strings, this could e.g. be used to create a collection of integer values with each string's length.
*/
<X,E extends Throwable> AMonadicOps<X> map(AFunction1<? super T, ? extends X, E> f) throws E;
/**
* Maps each element to a collection of values, flattening the results into a single collection. Let there be a
* collection of strings. Calling <code>flatMap</code> with a function that splits a string into tokens, the result
* would be a collection of all tokens of all original strings.
*/
<X, E extends Throwable> AMonadicOps<X> flatMap(AFunction1<? super T, ? extends Iterable<X>, E> f) throws E;
/**
* Applies a transformation function to all elements of a collection, where the partial function is defined for. Creates a new collection
* of the transformed elements only. So the number of result elements may be less than the number of elements in the source collection.
*/
|
<X, E extends Throwable> AMonadicOps<X> collect (APartialFunction<? super T, ? extends X, E> pf) throws E;
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/WorkerThread.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.function.AStatement1NoThrow;
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
|
continue;
}
if ((task = otherQueue.popFifo ()) != null) {
if (AThreadPoolImpl.SHOULD_GATHER_STATISTICS) stat_numSteals += 1;
//TODO refine prefetching based on other queue's size
//TODO other LocalQueue implementations
for (int i=0; i<numPrefetchLocal; i++) {
final Runnable prefetched = otherQueue.popFifo ();
if (prefetched == null) break;
localQueue.push (prefetched);
if (AThreadPoolImpl.SHOULD_GATHER_STATISTICS) stat_numSteals += 1; //TODO count separately?
}
return task;
}
}
return null;
}
//-------------------- Unsafe stuff
private static final Unsafe UNSAFE;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
}
catch (Exception exc) {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/WorkerThread.java
import com.ajjpj.afoundation.function.AStatement1NoThrow;
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
continue;
}
if ((task = otherQueue.popFifo ()) != null) {
if (AThreadPoolImpl.SHOULD_GATHER_STATISTICS) stat_numSteals += 1;
//TODO refine prefetching based on other queue's size
//TODO other LocalQueue implementations
for (int i=0; i<numPrefetchLocal; i++) {
final Runnable prefetched = otherQueue.popFifo ();
if (prefetched == null) break;
localQueue.push (prefetched);
if (AThreadPoolImpl.SHOULD_GATHER_STATISTICS) stat_numSteals += 1; //TODO count separately?
}
return task;
}
}
return null;
}
//-------------------- Unsafe stuff
private static final Unsafe UNSAFE;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
}
catch (Exception exc) {
|
AUnchecker.throwUnchecked (exc);
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ALongHashMap.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
|
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import java.io.Serializable;
import java.util.*;
|
package com.ajjpj.afoundation.collection.immutable;
/**
* This is an {@link com.ajjpj.afoundation.collection.immutable.AHashMap} that is specialized for keys of type long, i.e. primitive numbers rather than objects. It duplicates its API
* to support both efficient primitive 'long' values and generified 'Long's,
*
* @author arno
*/
public class ALongHashMap<V> extends AbstractAMap<Long,V> {
private static final int LEVEL_INCREMENT = 10;
transient private Integer cachedHashcode = null; // intentionally not volatile: This class is immutable, so recalculating per thread works
private static final ALongHashMap EMPTY = new ALongHashMap ();
/**
* Returns an empty ALongHashMap instance. Calling this factory method instead of
* the constructor allows internal reuse of empty map instances since they are immutable.
*/
@SuppressWarnings("unchecked")
public static <V> ALongHashMap<V> empty() {
return EMPTY;
}
public static <V> ALongHashMap<V> fromJavaUtilMap(Map<? extends Number,V> map) {
ALongHashMap<V> result = empty ();
for(Map.Entry<? extends Number,V> entry: map.entrySet()) {
result = result.updated(entry.getKey().longValue (), entry.getValue());
}
return result;
}
/**
* Returns an ALongHashMap initialized from separate 'keys' and 'values' collections. Both collections
* are iterated exactly once and are expected to have the same size.
*/
public static <V> ALongHashMap<V> fromKeysAndValues(Iterable<? extends Number> keys, Iterable<V> values) {
final Iterator<? extends Number> ki = keys.iterator();
final Iterator<V> vi = values.iterator();
ALongHashMap<V> result = ALongHashMap.empty ();
while(ki.hasNext()) {
final Number key = ki.next();
final V value = vi.next();
result = result.updated(key.longValue (), value);
}
return result;
}
/**
* Returns an ALongHashMap instance initialized from a collection of
* keys and a function. For each element of the <code>keys</code> collection, the function is called once to
* determine the corresponding value, and the pair is then stored in the map.
*/
@SuppressWarnings("unused")
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AFunction1.java
// public interface AFunction1<P, R, E extends Throwable> extends Serializable {
// R apply(P param) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/collection/immutable/ALongHashMap.java
import com.ajjpj.afoundation.collection.AEquality;
import com.ajjpj.afoundation.function.AFunction1;
import java.io.Serializable;
import java.util.*;
package com.ajjpj.afoundation.collection.immutable;
/**
* This is an {@link com.ajjpj.afoundation.collection.immutable.AHashMap} that is specialized for keys of type long, i.e. primitive numbers rather than objects. It duplicates its API
* to support both efficient primitive 'long' values and generified 'Long's,
*
* @author arno
*/
public class ALongHashMap<V> extends AbstractAMap<Long,V> {
private static final int LEVEL_INCREMENT = 10;
transient private Integer cachedHashcode = null; // intentionally not volatile: This class is immutable, so recalculating per thread works
private static final ALongHashMap EMPTY = new ALongHashMap ();
/**
* Returns an empty ALongHashMap instance. Calling this factory method instead of
* the constructor allows internal reuse of empty map instances since they are immutable.
*/
@SuppressWarnings("unchecked")
public static <V> ALongHashMap<V> empty() {
return EMPTY;
}
public static <V> ALongHashMap<V> fromJavaUtilMap(Map<? extends Number,V> map) {
ALongHashMap<V> result = empty ();
for(Map.Entry<? extends Number,V> entry: map.entrySet()) {
result = result.updated(entry.getKey().longValue (), entry.getValue());
}
return result;
}
/**
* Returns an ALongHashMap initialized from separate 'keys' and 'values' collections. Both collections
* are iterated exactly once and are expected to have the same size.
*/
public static <V> ALongHashMap<V> fromKeysAndValues(Iterable<? extends Number> keys, Iterable<V> values) {
final Iterator<? extends Number> ki = keys.iterator();
final Iterator<V> vi = values.iterator();
ALongHashMap<V> result = ALongHashMap.empty ();
while(ki.hasNext()) {
final Number key = ki.next();
final V value = vi.next();
result = result.updated(key.longValue (), value);
}
return result;
}
/**
* Returns an ALongHashMap instance initialized from a collection of
* keys and a function. For each element of the <code>keys</code> collection, the function is called once to
* determine the corresponding value, and the pair is then stored in the map.
*/
@SuppressWarnings("unused")
|
public static <K extends Number, V, E extends Throwable> ALongHashMap<V> fromKeysAndFunction(Iterable<K> keys, AFunction1<? super K, ? extends V, E> f) throws E {
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/AThreadPoolImpl.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.function.AFunction0NoThrow;
import com.ajjpj.afoundation.function.AFunction1NoThrow;
import com.ajjpj.afoundation.function.AStatement1NoThrow;
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
|
while (! UNSAFE.compareAndSwapLong (this, OFFS_IDLE_THREADS, prev, after));
return true;
}
void unmarkScanning() {
long prev, after;
do {
prev = UNSAFE.getLongVolatile (this, OFFS_IDLE_THREADS);
after = prev & ~MASK_IDLE_THREAD_SCANNING;
if (prev == after) {
return;
}
}
while (! UNSAFE.compareAndSwapLong (this, OFFS_IDLE_THREADS, prev, after));
}
//------------------ Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_IDLE_THREADS;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_IDLE_THREADS = UNSAFE.objectFieldOffset (AThreadPoolImpl.class.getDeclaredField ("idleThreads"));
}
catch (Exception e) {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/AThreadPoolImpl.java
import com.ajjpj.afoundation.function.AFunction0NoThrow;
import com.ajjpj.afoundation.function.AFunction1NoThrow;
import com.ajjpj.afoundation.function.AStatement1NoThrow;
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
while (! UNSAFE.compareAndSwapLong (this, OFFS_IDLE_THREADS, prev, after));
return true;
}
void unmarkScanning() {
long prev, after;
do {
prev = UNSAFE.getLongVolatile (this, OFFS_IDLE_THREADS);
after = prev & ~MASK_IDLE_THREAD_SCANNING;
if (prev == after) {
return;
}
}
while (! UNSAFE.compareAndSwapLong (this, OFFS_IDLE_THREADS, prev, after));
}
//------------------ Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_IDLE_THREADS;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_IDLE_THREADS = UNSAFE.objectFieldOffset (AThreadPoolImpl.class.getDeclaredField ("idleThreads"));
}
catch (Exception e) {
|
AUnchecker.throwUnchecked (e);
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SharedQueueNonBlockingImpl.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
|
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
|
private long taskOffset (long l) {
return OFFS_TASKS + SCALE_TASKS * (l & mask);
}
private int asArrayIndex (long l) {
return (int) (l & mask);
}
//------------- Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_TASKS;
private static final long SCALE_TASKS;
private static final long OFFS_BASE;
private static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_TASKS = UNSAFE.arrayBaseOffset (Runnable[].class);
SCALE_TASKS = UNSAFE.arrayIndexScale (Runnable[].class);
OFFS_BASE = UNSAFE.objectFieldOffset (SharedQueueNonBlockingImpl.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (SharedQueueNonBlockingImpl.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/util/AUnchecker.java
// public class AUnchecker {
// public static void throwUnchecked(Throwable th) {
// AUnchecker.<RuntimeException> doIt(th);
// }
//
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> void doIt(Throwable th) throws T {
// throw (T) th;
// }
//
// @SuppressWarnings("unused")
// public static void executeUnchecked(AStatement0<? extends Throwable> callback) {
// try {
// callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// }
// }
//
// public static <R> R executeUnchecked(AFunction0<R, ? extends Throwable> callback) {
// try {
// return callback.apply();
// }
// catch (Throwable exc) {
// throwUnchecked (exc);
// return null; //for the compiler
// }
// }
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/SharedQueueNonBlockingImpl.java
import com.ajjpj.afoundation.util.AUnchecker;
import sun.misc.Contended;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
private long taskOffset (long l) {
return OFFS_TASKS + SCALE_TASKS * (l & mask);
}
private int asArrayIndex (long l) {
return (int) (l & mask);
}
//------------- Unsafe stuff
private static final Unsafe UNSAFE;
private static final long OFFS_TASKS;
private static final long SCALE_TASKS;
private static final long OFFS_BASE;
private static final long OFFS_TOP;
static {
try {
final Field f = Unsafe.class.getDeclaredField ("theUnsafe");
f.setAccessible (true);
UNSAFE = (Unsafe) f.get (null);
OFFS_TASKS = UNSAFE.arrayBaseOffset (Runnable[].class);
SCALE_TASKS = UNSAFE.arrayIndexScale (Runnable[].class);
OFFS_BASE = UNSAFE.objectFieldOffset (SharedQueueNonBlockingImpl.class.getDeclaredField ("base"));
OFFS_TOP = UNSAFE.objectFieldOffset (SharedQueueNonBlockingImpl.class.getDeclaredField ("top"));
}
catch (Exception e) {
|
AUnchecker.throwUnchecked (e);
|
arnohaase/a-foundation
|
a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/AThreadPoolBuilder.java
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
|
import com.ajjpj.afoundation.function.AFunction0NoThrow;
import com.ajjpj.afoundation.function.AFunction1NoThrow;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.function.AStatement1NoThrow;
|
public AThreadPoolBuilder withDaemonThreads (boolean daemonThreads) {
this.isDaemon = daemonThreads;
return this;
}
public AThreadPoolBuilder withThreadNamePrefix (String threadNamePrefix) {
this.threadNameFactory = new DefaultThreadNameFactory (threadNamePrefix);
return this;
}
public AThreadPoolBuilder withThreadNameFactory (AFunction0NoThrow<String> threadNameFactory) {
this.threadNameFactory = threadNameFactory;
return this;
}
public AThreadPoolBuilder withExceptionHandler (AStatement1NoThrow<Throwable> exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
public AThreadPoolBuilder withSharedQueueAffinityStrategy (ASharedQueueAffinityStrategy sharedQueueAffinityStrategy) {
this.sharedQueueAffinityStrategy = sharedQueueAffinityStrategy;
return this;
}
public AThreadPoolBuilder withWorkerThreadLifecycleCallback (AWorkerThreadLifecycleCallback callback) {
this.workerThreadLifecycleCallback = callback;
return this;
}
|
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/function/AStatement1.java
// public interface AStatement1<P, E extends Throwable> extends Serializable {
// void apply(P param) throws E;
// }
// Path: a-foundation/src/main/java/com/ajjpj/afoundation/concurrent/AThreadPoolBuilder.java
import com.ajjpj.afoundation.function.AFunction0NoThrow;
import com.ajjpj.afoundation.function.AFunction1NoThrow;
import com.ajjpj.afoundation.function.AStatement1;
import com.ajjpj.afoundation.function.AStatement1NoThrow;
public AThreadPoolBuilder withDaemonThreads (boolean daemonThreads) {
this.isDaemon = daemonThreads;
return this;
}
public AThreadPoolBuilder withThreadNamePrefix (String threadNamePrefix) {
this.threadNameFactory = new DefaultThreadNameFactory (threadNamePrefix);
return this;
}
public AThreadPoolBuilder withThreadNameFactory (AFunction0NoThrow<String> threadNameFactory) {
this.threadNameFactory = threadNameFactory;
return this;
}
public AThreadPoolBuilder withExceptionHandler (AStatement1NoThrow<Throwable> exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
public AThreadPoolBuilder withSharedQueueAffinityStrategy (ASharedQueueAffinityStrategy sharedQueueAffinityStrategy) {
this.sharedQueueAffinityStrategy = sharedQueueAffinityStrategy;
return this;
}
public AThreadPoolBuilder withWorkerThreadLifecycleCallback (AWorkerThreadLifecycleCallback callback) {
this.workerThreadLifecycleCallback = callback;
return this;
}
|
public <T extends Throwable> AThreadPoolBuilder log (AStatement1<String, T> logOperation) throws T {
|
intuit/Autumn
|
modules/web/src/test/java/com/intuit/autumn/web/WebServletModuleTest.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public class PropertyFactory {
//
// private static final Logger LOGGER = getLogger(PropertyFactory.class);
//
// private PropertyFactory() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Properties creator given the provided resource name.
// *
// * @param propertyResourceName to be instantiated property resource name
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// /**
// * Properties creator given the provided resource name and package local reference class
// *
// * @param propertyResourceName to be instantiated property resource name
// * @param base package local reference class
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName, @Nullable final Class base) {
// LOGGER.debug("creating property: {}", propertyResourceName);
// Properties properties = new Properties();
//
// if (propertyResourceName != null) {
// LOGGER.debug("reading property: {}", propertyResourceName);
//
// try (InputStream is = PropertyFactory.class.getResourceAsStream(propertyResourceName)) {
// LOGGER.debug("loading property: {}", propertyResourceName);
//
// properties.load(is);
// } catch (IOException e) {
// String msg = "unable to start service: " + propertyResourceName + " properties, cause: " +
// e.getMessage();
//
// LOGGER.warn(msg, e);
// }
//
// fromJar(propertyResourceName, base, properties);
// }
//
// return properties;
// }
//
// private static void fromJar(final String propertyResourceName, @Nullable final Class base,
// final Properties properties) {
// if (base == null) {
// return;
// }
//
// CodeSource src = base.getProtectionDomain().getCodeSource();
//
// if (src == null) {
// return;
// }
//
// Properties propertiesFromJar = getPropertyFromJar(base, propertyResourceName.substring(1), src);
//
// for (Entry<Object, Object> entry : propertiesFromJar.entrySet()) {
// if (!properties.containsKey(entry.getKey())) {
// LOGGER.debug("overriding key: {}, newValue: {}, originalValue: {}",
// new Object[]{entry.getKey(), propertiesFromJar, entry.getValue()});
//
// properties.setProperty((String) entry.getKey(), (String) entry.getValue());
// }
// }
// }
//
// private static Properties getPropertyFromJar(final Class base, final String property, final CodeSource src) {
// Properties properties = new Properties();
// URL jar = src.getLocation();
//
// return jar != null ? readZip(base, jar, property, properties) : properties;
// }
//
// private static Properties readZip(final Class base, final URL jar, final String property,
// final Properties properties) {
// try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
// for (ZipEntry ze = zip.getNextEntry(); ze != null; ze = zip.getNextEntry()) {
// if (ze.getName().equals(property)) {
// properties.load(zip);
//
// break;
// }
// }
// } catch (IOException e) {
// LOGGER.warn("unable to read jar: {}, property: {}, class: {}, cause: {}",
// new Object[]{jar, property, base.getSimpleName(), e.getMessage()}, e);
// }
//
// return properties;
// }
//
// /**
// * Property value getter.
// *
// * @param key property key
// * @param properties properties object
// * @return return named property value
// */
//
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
//
// /**
// * Property resolve order
// * 1. Environment Variable set at System level
// * 2. Java System Property set by the -D flag at runtime
// * 3. The property File it self
// *
// * @param key property key
// * @param properties property collection
// * @param defaultValue default value
// * @return resolved value
// */
//
// public static String getProperty(final String key, final Properties properties, final String defaultValue) {
// String value = getenv(key);
//
// if (!isEmpty(value)) {
// return value;
// }
//
// value = System.getProperty(key, properties.getProperty(key));
//
// return !isEmpty(value) ? value : defaultValue;
// }
// }
//
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public static final String PROPERTY_NAME = "/web.properties";
|
import static org.hamcrest.Matchers.notNullValue;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;
import com.intuit.autumn.utils.PropertyFactory;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Properties;
import static com.google.inject.Guice.createInjector;
import static com.intuit.autumn.web.WebModule.PROPERTY_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
@RunWith(PowerMockRunner.class)
@PrepareForTest(PropertyFactory.class)
public class WebServletModuleTest {
@Test
public void injectable() throws Exception {
Properties properties = new Properties();
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public class PropertyFactory {
//
// private static final Logger LOGGER = getLogger(PropertyFactory.class);
//
// private PropertyFactory() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Properties creator given the provided resource name.
// *
// * @param propertyResourceName to be instantiated property resource name
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// /**
// * Properties creator given the provided resource name and package local reference class
// *
// * @param propertyResourceName to be instantiated property resource name
// * @param base package local reference class
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName, @Nullable final Class base) {
// LOGGER.debug("creating property: {}", propertyResourceName);
// Properties properties = new Properties();
//
// if (propertyResourceName != null) {
// LOGGER.debug("reading property: {}", propertyResourceName);
//
// try (InputStream is = PropertyFactory.class.getResourceAsStream(propertyResourceName)) {
// LOGGER.debug("loading property: {}", propertyResourceName);
//
// properties.load(is);
// } catch (IOException e) {
// String msg = "unable to start service: " + propertyResourceName + " properties, cause: " +
// e.getMessage();
//
// LOGGER.warn(msg, e);
// }
//
// fromJar(propertyResourceName, base, properties);
// }
//
// return properties;
// }
//
// private static void fromJar(final String propertyResourceName, @Nullable final Class base,
// final Properties properties) {
// if (base == null) {
// return;
// }
//
// CodeSource src = base.getProtectionDomain().getCodeSource();
//
// if (src == null) {
// return;
// }
//
// Properties propertiesFromJar = getPropertyFromJar(base, propertyResourceName.substring(1), src);
//
// for (Entry<Object, Object> entry : propertiesFromJar.entrySet()) {
// if (!properties.containsKey(entry.getKey())) {
// LOGGER.debug("overriding key: {}, newValue: {}, originalValue: {}",
// new Object[]{entry.getKey(), propertiesFromJar, entry.getValue()});
//
// properties.setProperty((String) entry.getKey(), (String) entry.getValue());
// }
// }
// }
//
// private static Properties getPropertyFromJar(final Class base, final String property, final CodeSource src) {
// Properties properties = new Properties();
// URL jar = src.getLocation();
//
// return jar != null ? readZip(base, jar, property, properties) : properties;
// }
//
// private static Properties readZip(final Class base, final URL jar, final String property,
// final Properties properties) {
// try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
// for (ZipEntry ze = zip.getNextEntry(); ze != null; ze = zip.getNextEntry()) {
// if (ze.getName().equals(property)) {
// properties.load(zip);
//
// break;
// }
// }
// } catch (IOException e) {
// LOGGER.warn("unable to read jar: {}, property: {}, class: {}, cause: {}",
// new Object[]{jar, property, base.getSimpleName(), e.getMessage()}, e);
// }
//
// return properties;
// }
//
// /**
// * Property value getter.
// *
// * @param key property key
// * @param properties properties object
// * @return return named property value
// */
//
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
//
// /**
// * Property resolve order
// * 1. Environment Variable set at System level
// * 2. Java System Property set by the -D flag at runtime
// * 3. The property File it self
// *
// * @param key property key
// * @param properties property collection
// * @param defaultValue default value
// * @return resolved value
// */
//
// public static String getProperty(final String key, final Properties properties, final String defaultValue) {
// String value = getenv(key);
//
// if (!isEmpty(value)) {
// return value;
// }
//
// value = System.getProperty(key, properties.getProperty(key));
//
// return !isEmpty(value) ? value : defaultValue;
// }
// }
//
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public static final String PROPERTY_NAME = "/web.properties";
// Path: modules/web/src/test/java/com/intuit/autumn/web/WebServletModuleTest.java
import static org.hamcrest.Matchers.notNullValue;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceFilter;
import com.intuit.autumn.utils.PropertyFactory;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Properties;
import static com.google.inject.Guice.createInjector;
import static com.intuit.autumn.web.WebModule.PROPERTY_NAME;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
@RunWith(PowerMockRunner.class)
@PrepareForTest(PropertyFactory.class)
public class WebServletModuleTest {
@Test
public void injectable() throws Exception {
Properties properties = new Properties();
|
properties.load(WebServletModule.class.getResourceAsStream(PROPERTY_NAME));
|
intuit/Autumn
|
modules/metrics/src/test/java/com/intuit/autumn/metrics/MetricsModuleTest.java
|
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
// public static final String PROPERTY_NAME = "/metrics.properties";
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
|
import static org.hamcrest.Matchers.equalTo;
import com.google.inject.Injector;
import com.google.inject.Key;
import org.junit.Test;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.metrics.MetricsModule.PROPERTY_NAME;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.hamcrest.MatcherAssert.assertThat;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
public class MetricsModuleTest {
@Test
public void injector() throws Exception {
Injector injector = createInjector(new MetricsModule());
|
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
// public static final String PROPERTY_NAME = "/metrics.properties";
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
// Path: modules/metrics/src/test/java/com/intuit/autumn/metrics/MetricsModuleTest.java
import static org.hamcrest.Matchers.equalTo;
import com.google.inject.Injector;
import com.google.inject.Key;
import org.junit.Test;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.metrics.MetricsModule.PROPERTY_NAME;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
public class MetricsModuleTest {
@Test
public void injector() throws Exception {
Injector injector = createInjector(new MetricsModule());
|
Properties properties = create(PROPERTY_NAME);
|
intuit/Autumn
|
modules/metrics/src/test/java/com/intuit/autumn/metrics/MetricsModuleTest.java
|
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
// public static final String PROPERTY_NAME = "/metrics.properties";
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
|
import static org.hamcrest.Matchers.equalTo;
import com.google.inject.Injector;
import com.google.inject.Key;
import org.junit.Test;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.metrics.MetricsModule.PROPERTY_NAME;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.hamcrest.MatcherAssert.assertThat;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
public class MetricsModuleTest {
@Test
public void injector() throws Exception {
Injector injector = createInjector(new MetricsModule());
|
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
// public static final String PROPERTY_NAME = "/metrics.properties";
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
// Path: modules/metrics/src/test/java/com/intuit/autumn/metrics/MetricsModuleTest.java
import static org.hamcrest.Matchers.equalTo;
import com.google.inject.Injector;
import com.google.inject.Key;
import org.junit.Test;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.metrics.MetricsModule.PROPERTY_NAME;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.hamcrest.MatcherAssert.assertThat;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
public class MetricsModuleTest {
@Test
public void injector() throws Exception {
Injector injector = createInjector(new MetricsModule());
|
Properties properties = create(PROPERTY_NAME);
|
intuit/Autumn
|
modules/view/src/main/java/com/intuit/autumn/view/ViewModule.java
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
/**
* An injector that includes application content provisioning implementation dependencies, e.g.: html, css, js
*/
public class ViewModule extends AbstractModule {
public static final String PROPERTY_NAME = "/view.properties";
private static final Logger LOGGER = getLogger(ViewModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/view/src/main/java/com/intuit/autumn/view/ViewModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
/**
* An injector that includes application content provisioning implementation dependencies, e.g.: html, css, js
*/
public class ViewModule extends AbstractModule {
public static final String PROPERTY_NAME = "/view.properties";
private static final Logger LOGGER = getLogger(ViewModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
install(new WebModule());
|
intuit/Autumn
|
modules/view/src/main/java/com/intuit/autumn/view/ViewModule.java
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
/**
* An injector that includes application content provisioning implementation dependencies, e.g.: html, css, js
*/
public class ViewModule extends AbstractModule {
public static final String PROPERTY_NAME = "/view.properties";
private static final Logger LOGGER = getLogger(ViewModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new WebModule());
LOGGER.debug("binding properties: {}", "null");
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/view/src/main/java/com/intuit/autumn/view/ViewModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
/**
* An injector that includes application content provisioning implementation dependencies, e.g.: html, css, js
*/
public class ViewModule extends AbstractModule {
public static final String PROPERTY_NAME = "/view.properties";
private static final Logger LOGGER = getLogger(ViewModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new WebModule());
LOGGER.debug("binding properties: {}", "null");
|
Properties properties = create(PROPERTY_NAME, ViewModule.class);
|
intuit/Autumn
|
modules/view/src/main/java/com/intuit/autumn/view/ViewModule.java
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
/**
* An injector that includes application content provisioning implementation dependencies, e.g.: html, css, js
*/
public class ViewModule extends AbstractModule {
public static final String PROPERTY_NAME = "/view.properties";
private static final Logger LOGGER = getLogger(ViewModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new WebModule());
LOGGER.debug("binding properties: {}", "null");
Properties properties = create(PROPERTY_NAME, ViewModule.class);
bind(Integer.class).annotatedWith(named("resource.expiryTimeInSeconds"))
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/view/src/main/java/com/intuit/autumn/view/ViewModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
/**
* An injector that includes application content provisioning implementation dependencies, e.g.: html, css, js
*/
public class ViewModule extends AbstractModule {
public static final String PROPERTY_NAME = "/view.properties";
private static final Logger LOGGER = getLogger(ViewModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new WebModule());
LOGGER.debug("binding properties: {}", "null");
Properties properties = create(PROPERTY_NAME, ViewModule.class);
bind(Integer.class).annotatedWith(named("resource.expiryTimeInSeconds"))
|
.toInstance(valueOf(getProperty("resource.expiryTimeInSeconds", properties)));
|
intuit/Autumn
|
modules/view/src/test/java/com/intuit/autumn/view/ViewModuleTest.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
|
import com.google.inject.Injector;
import com.google.inject.Key;
import org.junit.Test;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
public class ViewModuleTest {
@Test
public void injectable() throws Exception {
Injector injector = createInjector(new ViewModule());
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
// Path: modules/view/src/test/java/com/intuit/autumn/view/ViewModuleTest.java
import com.google.inject.Injector;
import com.google.inject.Key;
import org.junit.Test;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.view;
public class ViewModuleTest {
@Test
public void injectable() throws Exception {
Injector injector = createInjector(new ViewModule());
|
Properties properties = create(ViewModule.PROPERTY_NAME);
|
intuit/Autumn
|
modules/web/src/main/java/com/intuit/autumn/web/WebServices.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* A provider for enabled web services.
*/
public class WebServices {
public static final String PROPERTY_NAME = "/web.properties";
private static final ImmutableMap<String, Class<? extends Service>> WEB_SERVICES =
new Builder<String, Class<? extends Service>>()
.put("application.http.enabled", HttpService.class)
.put("application.https.enabled", HttpsService.class)
.build();
private static final Logger LOGGER = getLogger(WebServices.class);
private WebServices() {
throw new UnsupportedOperationException();
}
/**
* Http services configuration utility.
*
* @return collection of enabled http services.
*/
public static Set<Class<? extends Service>> getEnabledWebServices() {
LOGGER.debug("getting enabled web services");
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebServices.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* A provider for enabled web services.
*/
public class WebServices {
public static final String PROPERTY_NAME = "/web.properties";
private static final ImmutableMap<String, Class<? extends Service>> WEB_SERVICES =
new Builder<String, Class<? extends Service>>()
.put("application.http.enabled", HttpService.class)
.put("application.https.enabled", HttpsService.class)
.build();
private static final Logger LOGGER = getLogger(WebServices.class);
private WebServices() {
throw new UnsupportedOperationException();
}
/**
* Http services configuration utility.
*
* @return collection of enabled http services.
*/
public static Set<Class<? extends Service>> getEnabledWebServices() {
LOGGER.debug("getting enabled web services");
|
Properties properties = create(PROPERTY_NAME, WebModule.class);
|
intuit/Autumn
|
modules/web/src/main/java/com/intuit/autumn/web/WebServices.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* A provider for enabled web services.
*/
public class WebServices {
public static final String PROPERTY_NAME = "/web.properties";
private static final ImmutableMap<String, Class<? extends Service>> WEB_SERVICES =
new Builder<String, Class<? extends Service>>()
.put("application.http.enabled", HttpService.class)
.put("application.https.enabled", HttpsService.class)
.build();
private static final Logger LOGGER = getLogger(WebServices.class);
private WebServices() {
throw new UnsupportedOperationException();
}
/**
* Http services configuration utility.
*
* @return collection of enabled http services.
*/
public static Set<Class<? extends Service>> getEnabledWebServices() {
LOGGER.debug("getting enabled web services");
Properties properties = create(PROPERTY_NAME, WebModule.class);
Set<Class<? extends Service>> webServices = newHashSet();
loadIfEnabled(properties, webServices, "application.http.enabled");
loadIfEnabled(properties, webServices, "application.https.enabled");
LOGGER.debug("got enabled web services count: {}", webServices.size());
return webServices;
}
private static void loadIfEnabled(final Properties properties, Set<Class<? extends Service>> services,
final String key) {
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebServices.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* A provider for enabled web services.
*/
public class WebServices {
public static final String PROPERTY_NAME = "/web.properties";
private static final ImmutableMap<String, Class<? extends Service>> WEB_SERVICES =
new Builder<String, Class<? extends Service>>()
.put("application.http.enabled", HttpService.class)
.put("application.https.enabled", HttpsService.class)
.build();
private static final Logger LOGGER = getLogger(WebServices.class);
private WebServices() {
throw new UnsupportedOperationException();
}
/**
* Http services configuration utility.
*
* @return collection of enabled http services.
*/
public static Set<Class<? extends Service>> getEnabledWebServices() {
LOGGER.debug("getting enabled web services");
Properties properties = create(PROPERTY_NAME, WebModule.class);
Set<Class<? extends Service>> webServices = newHashSet();
loadIfEnabled(properties, webServices, "application.http.enabled");
loadIfEnabled(properties, webServices, "application.https.enabled");
LOGGER.debug("got enabled web services count: {}", webServices.size());
return webServices;
}
private static void loadIfEnabled(final Properties properties, Set<Class<? extends Service>> services,
final String key) {
|
if (toBoolean(getProperty(key, properties))) {
|
intuit/Autumn
|
modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes wire protocol implementation dependencies, e.g.: Jetty (HTTP/S)
*/
public class WebModule extends AbstractModule {
public static final String PROPERTY_NAME = "/web.properties";
public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
private static final Logger LOGGER = getLogger(WebModule.class);
/**
* Inject module dependencies.
*/
@Override
protected void configure() {
install(new WebServletModule());
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes wire protocol implementation dependencies, e.g.: Jetty (HTTP/S)
*/
public class WebModule extends AbstractModule {
public static final String PROPERTY_NAME = "/web.properties";
public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
private static final Logger LOGGER = getLogger(WebModule.class);
/**
* Inject module dependencies.
*/
@Override
protected void configure() {
install(new WebServletModule());
|
install(new ManageModule());
|
intuit/Autumn
|
modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes wire protocol implementation dependencies, e.g.: Jetty (HTTP/S)
*/
public class WebModule extends AbstractModule {
public static final String PROPERTY_NAME = "/web.properties";
public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
private static final Logger LOGGER = getLogger(WebModule.class);
/**
* Inject module dependencies.
*/
@Override
protected void configure() {
install(new WebServletModule());
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes wire protocol implementation dependencies, e.g.: Jetty (HTTP/S)
*/
public class WebModule extends AbstractModule {
public static final String PROPERTY_NAME = "/web.properties";
public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
private static final Logger LOGGER = getLogger(WebModule.class);
/**
* Inject module dependencies.
*/
@Override
protected void configure() {
install(new WebServletModule());
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
|
Properties properties = create(PROPERTY_NAME, WebModule.class);
|
intuit/Autumn
|
modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes wire protocol implementation dependencies, e.g.: Jetty (HTTP/S)
*/
public class WebModule extends AbstractModule {
public static final String PROPERTY_NAME = "/web.properties";
public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
private static final Logger LOGGER = getLogger(WebModule.class);
/**
* Inject module dependencies.
*/
@Override
protected void configure() {
install(new WebServletModule());
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
Properties properties = create(PROPERTY_NAME, WebModule.class);
Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
bind(Integer.class).annotatedWith(named("application.http.port"))
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes wire protocol implementation dependencies, e.g.: Jetty (HTTP/S)
*/
public class WebModule extends AbstractModule {
public static final String PROPERTY_NAME = "/web.properties";
public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
private static final Logger LOGGER = getLogger(WebModule.class);
/**
* Inject module dependencies.
*/
@Override
protected void configure() {
install(new WebServletModule());
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
Properties properties = create(PROPERTY_NAME, WebModule.class);
Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
bind(Integer.class).annotatedWith(named("application.http.port"))
|
.toInstance(valueOf(getProperty("application.http.port", properties)));
|
intuit/Autumn
|
modules/crypto/src/main/java/com/intuit/autumn/crypto/CryptoModule.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.multibindings.MapBinder;
import java.util.Properties;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Boolean.TRUE;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.crypto;
/**
* An injector that includes Cryptography implementation details.
*/
public class CryptoModule extends AbstractModule {
public static final String PROPERTY_NAME = "/crypto.properties";
public static final String SECRETS_PROPERTY_NAME = "/crypto-secrets.properties";
public static final String DECRYPTION_KEYS_PROPERTY_NAME = "/decryption-keys.properties";
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/crypto/src/main/java/com/intuit/autumn/crypto/CryptoModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.multibindings.MapBinder;
import java.util.Properties;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Boolean.TRUE;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.crypto;
/**
* An injector that includes Cryptography implementation details.
*/
public class CryptoModule extends AbstractModule {
public static final String PROPERTY_NAME = "/crypto.properties";
public static final String SECRETS_PROPERTY_NAME = "/crypto-secrets.properties";
public static final String DECRYPTION_KEYS_PROPERTY_NAME = "/decryption-keys.properties";
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
Properties properties = create(PROPERTY_NAME, CryptoModule.class);
|
intuit/Autumn
|
modules/crypto/src/main/java/com/intuit/autumn/crypto/CryptoModule.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.multibindings.MapBinder;
import java.util.Properties;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Boolean.TRUE;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.crypto;
/**
* An injector that includes Cryptography implementation details.
*/
public class CryptoModule extends AbstractModule {
public static final String PROPERTY_NAME = "/crypto.properties";
public static final String SECRETS_PROPERTY_NAME = "/crypto-secrets.properties";
public static final String DECRYPTION_KEYS_PROPERTY_NAME = "/decryption-keys.properties";
/**
* Install module dependencies.
*/
@Override
protected void configure() {
Properties properties = create(PROPERTY_NAME, CryptoModule.class);
Properties secretProperties = create(SECRETS_PROPERTY_NAME, CryptoModule.class);
Properties decryptionProperties = create(DECRYPTION_KEYS_PROPERTY_NAME, CryptoModule.class);
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/crypto/src/main/java/com/intuit/autumn/crypto/CryptoModule.java
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.multibindings.MapBinder;
import java.util.Properties;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Boolean.TRUE;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.crypto;
/**
* An injector that includes Cryptography implementation details.
*/
public class CryptoModule extends AbstractModule {
public static final String PROPERTY_NAME = "/crypto.properties";
public static final String SECRETS_PROPERTY_NAME = "/crypto-secrets.properties";
public static final String DECRYPTION_KEYS_PROPERTY_NAME = "/decryption-keys.properties";
/**
* Install module dependencies.
*/
@Override
protected void configure() {
Properties properties = create(PROPERTY_NAME, CryptoModule.class);
Properties secretProperties = create(SECRETS_PROPERTY_NAME, CryptoModule.class);
Properties decryptionProperties = create(DECRYPTION_KEYS_PROPERTY_NAME, CryptoModule.class);
|
boolean cryptoEnabled = Boolean.valueOf(getProperty("crypto.enabled", properties, TRUE.toString()));
|
intuit/Autumn
|
modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import static org.slf4j.LoggerFactory.getLogger;
import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* An injector that includes operational metrics implemementation dependencies.
*/
public class MetricsModule extends AbstractModule {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final Logger LOGGER = getLogger(MetricsModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
import static org.slf4j.LoggerFactory.getLogger;
import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* An injector that includes operational metrics implemementation dependencies.
*/
public class MetricsModule extends AbstractModule {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final Logger LOGGER = getLogger(MetricsModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
install(new ManageModule());
|
intuit/Autumn
|
modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import static org.slf4j.LoggerFactory.getLogger;
import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* An injector that includes operational metrics implemementation dependencies.
*/
public class MetricsModule extends AbstractModule {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final Logger LOGGER = getLogger(MetricsModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
import static org.slf4j.LoggerFactory.getLogger;
import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* An injector that includes operational metrics implemementation dependencies.
*/
public class MetricsModule extends AbstractModule {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final Logger LOGGER = getLogger(MetricsModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
|
Properties properties = create(PROPERTY_NAME, MetricsModule.class);
|
intuit/Autumn
|
modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import static org.slf4j.LoggerFactory.getLogger;
import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* An injector that includes operational metrics implemementation dependencies.
*/
public class MetricsModule extends AbstractModule {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final Logger LOGGER = getLogger(MetricsModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
Properties properties = create(PROPERTY_NAME, MetricsModule.class);
bind(Boolean.class).annotatedWith(named("metrics.csv.enabled"))
|
// Path: modules/manage/src/main/java/com/intuit/autumn/manage/ManageModule.java
// public class ManageModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ManageModule.class);
//
// // note: configure the jmx ephemeral port, needs to be done before the jmx subsystem is instantiated
// static {
// // todo: ?should we provide a means to set the back-channel port, vs one-up the public port?
// String portStr = getProperty("com.sun.management.jmxremote.port");
// int port = (portStr != null) ? parseInt(portStr) + 1 : 18099;
//
// try {
// createRegistry(port);
// } catch (RemoteException e) {
// LOGGER.warn("unable to create registry on port: {}, cause: {}", port, e.getMessage());
//
// throw new ManageException(e);
// }
// }
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// bind(MBeanServer.class).toInstance(ManagementFactory.getPlatformMBeanServer());
// bind(MBeanRegistry.class).in(SINGLETON);
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsModule.java
import static org.slf4j.LoggerFactory.getLogger;
import com.codahale.metrics.MetricRegistry;
import com.google.inject.AbstractModule;
import com.intuit.autumn.manage.ManageModule;
import org.slf4j.Logger;
import java.io.File;
import java.net.URI;
import java.util.Properties;
import static com.google.inject.Scopes.SINGLETON;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static java.lang.Integer.valueOf;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* An injector that includes operational metrics implemementation dependencies.
*/
public class MetricsModule extends AbstractModule {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final Logger LOGGER = getLogger(MetricsModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
install(new ManageModule());
LOGGER.debug("binding properties: {}", PROPERTY_NAME);
Properties properties = create(PROPERTY_NAME, MetricsModule.class);
bind(Boolean.class).annotatedWith(named("metrics.csv.enabled"))
|
.toInstance(Boolean.valueOf(getProperty("metrics.csv.enabled", properties)));
|
intuit/Autumn
|
modules/api/src/main/java/com/intuit/autumn/api/ApiModule.java
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.api;
/**
* An injector that includes API implementation dependencies, e.g.: serialization (JSON), wire protocol (HTTP/S)
*/
public class ApiModule extends AbstractModule {
private static final Logger LOGGER = getLogger(ApiModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebModule.java
// public class WebModule extends AbstractModule {
//
// public static final String PROPERTY_NAME = "/web.properties";
// public static final String SECRETS_PROPERTY_NAME = "/web-secrets.properties";
// private static final Logger LOGGER = getLogger(WebModule.class);
//
// /**
// * Inject module dependencies.
// */
//
// @Override
// protected void configure() {
// install(new WebServletModule());
// install(new ManageModule());
//
// LOGGER.debug("binding properties: {}", PROPERTY_NAME);
//
// Properties properties = create(PROPERTY_NAME, WebModule.class);
// Properties secretsProperties = create(SECRETS_PROPERTY_NAME, WebModule.class);
//
// bind(Integer.class).annotatedWith(named("application.http.port"))
// .toInstance(valueOf(getProperty("application.http.port", properties)));
// bind(String.class).annotatedWith(named("application.http.context.path"))
// .toInstance(String.valueOf(getProperty(
// "application.http.context.path", properties)));
// bind(String.class).annotatedWith(named("application.http.content.directory"))
// .toInstance(String.valueOf(getProperty(
// "application.http.content.directory", properties)));
//
// Boolean isHttpsOn = Boolean.valueOf(getProperty("application.https.enabled",
// properties, "false"));
// bind(Boolean.class).annotatedWith(named("application.https.enabled"))
// .toInstance(isHttpsOn);
// bind(Boolean.class).annotatedWith(named("application.http.enabled"))
// .toInstance(Boolean.valueOf(getProperty("application.http.enabled", properties, "false")));
// bind(Integer.class).annotatedWith(named("application.https.port"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.port", properties)) : -1);
// bind(Integer.class).annotatedWith(
// named("application.httpconfig.output.buffersize"))
// .toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.httpconfig.output.buffersize", properties)) : -1);
// bind(Integer.class).annotatedWith(named("application.https.idletimeout")).
// toInstance(isHttpsOn ? Integer.parseInt(getProperty(
// "application.https.idletimeout", properties)) : -1);
// bind(String.class).annotatedWith(named("application.ssl.keystore.path"))
// .toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.path", properties)) : "");
//
// bind(String.class).annotatedWith(named("application.ssl.keystore.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keystore.password", secretsProperties)) : "");
// bind(String.class).annotatedWith(named("application.ssl.keymanager.password")).
// toInstance(isHttpsOn ? String.valueOf(getProperty(
// "application.ssl.keymanager.password", secretsProperties)) : "");
//
// bind(HttpHeader.class).in(SINGLETON);
// bind(HttpService.class).in(SINGLETON);
// bind(HttpsService.class).in(SINGLETON);
//
// LOGGER.debug("bound properties: {}", PROPERTY_NAME);
// }
// }
// Path: modules/api/src/main/java/com/intuit/autumn/api/ApiModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.web.WebModule;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.api;
/**
* An injector that includes API implementation dependencies, e.g.: serialization (JSON), wire protocol (HTTP/S)
*/
public class ApiModule extends AbstractModule {
private static final Logger LOGGER = getLogger(ApiModule.class);
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
LOGGER.debug("installing module: {}", WebModule.class.getSimpleName());
|
intuit/Autumn
|
modules/exemplary/src/main/java/com/intuit/autumn/exemplary/server/ExemplaryApiModule.java
|
// Path: modules/api/src/main/java/com/intuit/autumn/api/ApiModule.java
// public class ApiModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ApiModule.class);
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// LOGGER.debug("installing module: {}", WebModule.class.getSimpleName());
//
// install(new WebModule());
//
// LOGGER.debug("installed module: {}", WebModule.class.getSimpleName());
// }
// }
|
import com.google.inject.AbstractModule;
import com.intuit.autumn.api.ApiModule;
import static com.google.inject.Scopes.SINGLETON;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.exemplary.server;
/**
* An injector that includes prototypical application implementation dependencies.
*/
public class ExemplaryApiModule extends AbstractModule {
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
// Path: modules/api/src/main/java/com/intuit/autumn/api/ApiModule.java
// public class ApiModule extends AbstractModule {
//
// private static final Logger LOGGER = getLogger(ApiModule.class);
//
// /**
// * Install module dependencies.
// */
//
// @Override
// protected void configure() {
// LOGGER.debug("installing module: {}", WebModule.class.getSimpleName());
//
// install(new WebModule());
//
// LOGGER.debug("installed module: {}", WebModule.class.getSimpleName());
// }
// }
// Path: modules/exemplary/src/main/java/com/intuit/autumn/exemplary/server/ExemplaryApiModule.java
import com.google.inject.AbstractModule;
import com.intuit.autumn.api.ApiModule;
import static com.google.inject.Scopes.SINGLETON;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.exemplary.server;
/**
* An injector that includes prototypical application implementation dependencies.
*/
public class ExemplaryApiModule extends AbstractModule {
/**
* Install module dependencies.
*/
@Override
protected void configure() {
|
install(new ApiModule());
|
intuit/Autumn
|
modules/web/src/test/java/com/intuit/autumn/web/WebModuleTest.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public class PropertyFactory {
//
// private static final Logger LOGGER = getLogger(PropertyFactory.class);
//
// private PropertyFactory() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Properties creator given the provided resource name.
// *
// * @param propertyResourceName to be instantiated property resource name
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// /**
// * Properties creator given the provided resource name and package local reference class
// *
// * @param propertyResourceName to be instantiated property resource name
// * @param base package local reference class
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName, @Nullable final Class base) {
// LOGGER.debug("creating property: {}", propertyResourceName);
// Properties properties = new Properties();
//
// if (propertyResourceName != null) {
// LOGGER.debug("reading property: {}", propertyResourceName);
//
// try (InputStream is = PropertyFactory.class.getResourceAsStream(propertyResourceName)) {
// LOGGER.debug("loading property: {}", propertyResourceName);
//
// properties.load(is);
// } catch (IOException e) {
// String msg = "unable to start service: " + propertyResourceName + " properties, cause: " +
// e.getMessage();
//
// LOGGER.warn(msg, e);
// }
//
// fromJar(propertyResourceName, base, properties);
// }
//
// return properties;
// }
//
// private static void fromJar(final String propertyResourceName, @Nullable final Class base,
// final Properties properties) {
// if (base == null) {
// return;
// }
//
// CodeSource src = base.getProtectionDomain().getCodeSource();
//
// if (src == null) {
// return;
// }
//
// Properties propertiesFromJar = getPropertyFromJar(base, propertyResourceName.substring(1), src);
//
// for (Entry<Object, Object> entry : propertiesFromJar.entrySet()) {
// if (!properties.containsKey(entry.getKey())) {
// LOGGER.debug("overriding key: {}, newValue: {}, originalValue: {}",
// new Object[]{entry.getKey(), propertiesFromJar, entry.getValue()});
//
// properties.setProperty((String) entry.getKey(), (String) entry.getValue());
// }
// }
// }
//
// private static Properties getPropertyFromJar(final Class base, final String property, final CodeSource src) {
// Properties properties = new Properties();
// URL jar = src.getLocation();
//
// return jar != null ? readZip(base, jar, property, properties) : properties;
// }
//
// private static Properties readZip(final Class base, final URL jar, final String property,
// final Properties properties) {
// try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
// for (ZipEntry ze = zip.getNextEntry(); ze != null; ze = zip.getNextEntry()) {
// if (ze.getName().equals(property)) {
// properties.load(zip);
//
// break;
// }
// }
// } catch (IOException e) {
// LOGGER.warn("unable to read jar: {}, property: {}, class: {}, cause: {}",
// new Object[]{jar, property, base.getSimpleName(), e.getMessage()}, e);
// }
//
// return properties;
// }
//
// /**
// * Property value getter.
// *
// * @param key property key
// * @param properties properties object
// * @return return named property value
// */
//
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
//
// /**
// * Property resolve order
// * 1. Environment Variable set at System level
// * 2. Java System Property set by the -D flag at runtime
// * 3. The property File it self
// *
// * @param key property key
// * @param properties property collection
// * @param defaultValue default value
// * @return resolved value
// */
//
// public static String getProperty(final String key, final Properties properties, final String defaultValue) {
// String value = getenv(key);
//
// if (!isEmpty(value)) {
// return value;
// }
//
// value = System.getProperty(key, properties.getProperty(key));
//
// return !isEmpty(value) ? value : defaultValue;
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
|
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.intuit.autumn.utils.PropertyFactory;
import org.easymock.IAnswer;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.easymock.EasyMock.*;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
public class WebModuleTest {
@Test
public void injector() throws Exception {
Injector injector = createInjector(new WebModule());
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public class PropertyFactory {
//
// private static final Logger LOGGER = getLogger(PropertyFactory.class);
//
// private PropertyFactory() {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Properties creator given the provided resource name.
// *
// * @param propertyResourceName to be instantiated property resource name
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// /**
// * Properties creator given the provided resource name and package local reference class
// *
// * @param propertyResourceName to be instantiated property resource name
// * @param base package local reference class
// * @return instantiated Properties instance
// */
//
// public static Properties create(final String propertyResourceName, @Nullable final Class base) {
// LOGGER.debug("creating property: {}", propertyResourceName);
// Properties properties = new Properties();
//
// if (propertyResourceName != null) {
// LOGGER.debug("reading property: {}", propertyResourceName);
//
// try (InputStream is = PropertyFactory.class.getResourceAsStream(propertyResourceName)) {
// LOGGER.debug("loading property: {}", propertyResourceName);
//
// properties.load(is);
// } catch (IOException e) {
// String msg = "unable to start service: " + propertyResourceName + " properties, cause: " +
// e.getMessage();
//
// LOGGER.warn(msg, e);
// }
//
// fromJar(propertyResourceName, base, properties);
// }
//
// return properties;
// }
//
// private static void fromJar(final String propertyResourceName, @Nullable final Class base,
// final Properties properties) {
// if (base == null) {
// return;
// }
//
// CodeSource src = base.getProtectionDomain().getCodeSource();
//
// if (src == null) {
// return;
// }
//
// Properties propertiesFromJar = getPropertyFromJar(base, propertyResourceName.substring(1), src);
//
// for (Entry<Object, Object> entry : propertiesFromJar.entrySet()) {
// if (!properties.containsKey(entry.getKey())) {
// LOGGER.debug("overriding key: {}, newValue: {}, originalValue: {}",
// new Object[]{entry.getKey(), propertiesFromJar, entry.getValue()});
//
// properties.setProperty((String) entry.getKey(), (String) entry.getValue());
// }
// }
// }
//
// private static Properties getPropertyFromJar(final Class base, final String property, final CodeSource src) {
// Properties properties = new Properties();
// URL jar = src.getLocation();
//
// return jar != null ? readZip(base, jar, property, properties) : properties;
// }
//
// private static Properties readZip(final Class base, final URL jar, final String property,
// final Properties properties) {
// try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
// for (ZipEntry ze = zip.getNextEntry(); ze != null; ze = zip.getNextEntry()) {
// if (ze.getName().equals(property)) {
// properties.load(zip);
//
// break;
// }
// }
// } catch (IOException e) {
// LOGGER.warn("unable to read jar: {}, property: {}, class: {}, cause: {}",
// new Object[]{jar, property, base.getSimpleName(), e.getMessage()}, e);
// }
//
// return properties;
// }
//
// /**
// * Property value getter.
// *
// * @param key property key
// * @param properties properties object
// * @return return named property value
// */
//
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
//
// /**
// * Property resolve order
// * 1. Environment Variable set at System level
// * 2. Java System Property set by the -D flag at runtime
// * 3. The property File it self
// *
// * @param key property key
// * @param properties property collection
// * @param defaultValue default value
// * @return resolved value
// */
//
// public static String getProperty(final String key, final Properties properties, final String defaultValue) {
// String value = getenv(key);
//
// if (!isEmpty(value)) {
// return value;
// }
//
// value = System.getProperty(key, properties.getProperty(key));
//
// return !isEmpty(value) ? value : defaultValue;
// }
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
// Path: modules/web/src/test/java/com/intuit/autumn/web/WebModuleTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.intuit.autumn.utils.PropertyFactory;
import org.easymock.IAnswer;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Properties;
import static com.google.common.primitives.Ints.tryParse;
import static com.google.inject.Guice.createInjector;
import static com.google.inject.name.Names.named;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static org.easymock.EasyMock.*;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
public class WebModuleTest {
@Test
public void injector() throws Exception {
Injector injector = createInjector(new WebModule());
|
Properties properties = create(WebModule.PROPERTY_NAME);
|
intuit/Autumn
|
modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsServices.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* A utility providing a list of enabled operational metrics reporters.
*/
public class MetricsServices {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final String METRICS_GRAPHITE_ENABLED_KEY = "metrics.graphite.enabled";
private static final ImmutableMap<String, Class<? extends Service>> METRICS_SERVICES =
new Builder<String, Class<? extends Service>>()
.put("metrics.csv.enabled", CsvMetricsService.class)
.put(METRICS_GRAPHITE_ENABLED_KEY, GraphiteMetricsService.class)
.put("metrics.hystrix.enabled", HystrixMetricsService.class)
.put("metrics.jmx.enabled", JmxMetricsService.class)
.build();
private static final Logger LOGGER = getLogger(MetricsServices.class);
private MetricsServices() {
throw new UnsupportedOperationException();
}
/**
* Metrics services configuration utility.
*
* @return collection of enabled metrics services.
*/
// todo: ?do better?
public static Set<Class<? extends Service>> getEnabledMetricsServices() {
LOGGER.debug("getting enabled metrics services");
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsServices.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.metrics;
/**
* A utility providing a list of enabled operational metrics reporters.
*/
public class MetricsServices {
public static final String PROPERTY_NAME = "/metrics.properties";
private static final String METRICS_GRAPHITE_ENABLED_KEY = "metrics.graphite.enabled";
private static final ImmutableMap<String, Class<? extends Service>> METRICS_SERVICES =
new Builder<String, Class<? extends Service>>()
.put("metrics.csv.enabled", CsvMetricsService.class)
.put(METRICS_GRAPHITE_ENABLED_KEY, GraphiteMetricsService.class)
.put("metrics.hystrix.enabled", HystrixMetricsService.class)
.put("metrics.jmx.enabled", JmxMetricsService.class)
.build();
private static final Logger LOGGER = getLogger(MetricsServices.class);
private MetricsServices() {
throw new UnsupportedOperationException();
}
/**
* Metrics services configuration utility.
*
* @return collection of enabled metrics services.
*/
// todo: ?do better?
public static Set<Class<? extends Service>> getEnabledMetricsServices() {
LOGGER.debug("getting enabled metrics services");
|
Properties properties = create(PROPERTY_NAME, MetricsModule.class);
|
intuit/Autumn
|
modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsServices.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
|
* Metrics services configuration utility.
*
* @return collection of enabled metrics services.
*/
// todo: ?do better?
public static Set<Class<? extends Service>> getEnabledMetricsServices() {
LOGGER.debug("getting enabled metrics services");
Properties properties = create(PROPERTY_NAME, MetricsModule.class);
Set<Class<? extends Service>> metricsServices = newHashSet();
addIfEnabled(properties, metricsServices, "metrics.csv.enabled");
addIfEnabled(properties, metricsServices, METRICS_GRAPHITE_ENABLED_KEY);
// note: graphite is needed for hystrix ( don't be alarmed )
addIfEnabled(properties, metricsServices, "metrics.hystrix.enabled", METRICS_GRAPHITE_ENABLED_KEY);
addIfEnabled(properties, metricsServices, "metrics.jmx.enabled");
LOGGER.debug("got enabled metrics services count: {}", metricsServices.size());
return metricsServices;
}
private static void addIfEnabled(final Properties properties, Set<Class<? extends Service>> services,
final String... keys) {
int keyCounter = 0;
boolean isEnabled = false;
for (String key : keys) {
if (++keyCounter == 1) {
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/metrics/src/main/java/com/intuit/autumn/metrics/MetricsServices.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.util.concurrent.Service;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static org.apache.commons.lang.BooleanUtils.toBoolean;
import static org.slf4j.LoggerFactory.getLogger;
* Metrics services configuration utility.
*
* @return collection of enabled metrics services.
*/
// todo: ?do better?
public static Set<Class<? extends Service>> getEnabledMetricsServices() {
LOGGER.debug("getting enabled metrics services");
Properties properties = create(PROPERTY_NAME, MetricsModule.class);
Set<Class<? extends Service>> metricsServices = newHashSet();
addIfEnabled(properties, metricsServices, "metrics.csv.enabled");
addIfEnabled(properties, metricsServices, METRICS_GRAPHITE_ENABLED_KEY);
// note: graphite is needed for hystrix ( don't be alarmed )
addIfEnabled(properties, metricsServices, "metrics.hystrix.enabled", METRICS_GRAPHITE_ENABLED_KEY);
addIfEnabled(properties, metricsServices, "metrics.jmx.enabled");
LOGGER.debug("got enabled metrics services count: {}", metricsServices.size());
return metricsServices;
}
private static void addIfEnabled(final Properties properties, Set<Class<? extends Service>> services,
final String... keys) {
int keyCounter = 0;
boolean isEnabled = false;
for (String key : keys) {
if (++keyCounter == 1) {
|
isEnabled = toBoolean(getProperty(key, properties));
|
intuit/Autumn
|
modules/exemplary/src/main/java/com/intuit/autumn/exemplary/server/PingService.java
|
// Path: modules/exemplary/src/main/java/com/intuit/autumn/exemplary/data/Ping.java
// public class Ping {
//
// private String id;
// private String message;
//
// /**
// * Empty constructor.
// *
// * note: necessary default constructor used by jackson for serialization/deserialization
// */
//
// public Ping() {
// }
//
// /**
// * Constructor with configurable state.
// *
// * @param id instance id
// * @param message instance payload
// */
//
// public Ping(String id, String message) {
// this.id = id;
// this.message = message;
// }
//
// /**
// * Get instance id.
// *
// * @return instance id
// */
//
// public String getId() {
// return id;
// }
//
// /**
// * Set instance id.
// *
// * @param id instance id
// */
//
// public void setId(String id) {
// this.id = id;
// }
//
// /**
// * Get instance payload.
// *
// * @return instance payload
// */
//
// public String getMessage() {
// return message;
// }
//
// /**
// * Set instance payload.
// *
// * @param message instance payload
// */
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// /**
// * Instance JSON representation.
// *
// * @return json representation
// */
//
// @Override
// public String toString() {
// return format("Ping{id='%s',message='%s'}", id, message);
// }
// }
//
// Path: modules/web/src/main/java/com/intuit/autumn/web/HttpHeader.java
// public class HttpHeader {
//
// private final CacheControl cacheControl;
//
// @Inject
// public HttpHeader() {
// cacheControl = new CacheControl();
//
// cacheControl.setPrivate(TRUE);
// cacheControl.setNoCache(TRUE);
// }
//
// public Response.ResponseBuilder headers() {
// return headers(OK);
// }
//
// public Response.ResponseBuilder headers(Response.Status status) {
// return headers(status.getStatusCode());
// }
//
// public Response.ResponseBuilder headers(int status) {
// return status(status)
// .cacheControl(cacheControl)
// .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
// .header(ACCESS_CONTROL_ALLOW_HEADERS, "Authorization,X-Forwarded-For,Accept-Language,Content-Type")
// .header(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS")
// .header(ACCESS_CONTROL_REQUEST_METHOD, "GET,POST,OPTIONS");
// // .header("X-Application-Id", applicationName);
// }
// }
|
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import com.intuit.autumn.exemplary.data.Ping;
import com.intuit.autumn.web.HttpHeader;
import org.slf4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.util.List;
import java.util.UUID;
import static com.google.common.base.Joiner.on;
import static java.util.Arrays.asList;
import static java.util.UUID.fromString;
import static java.util.UUID.randomUUID;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.exemplary.server;
/**
* Prototypical application endpoint implementation.
*/
@Provider
@Path("/proto")
public class PingService {
private static final Joiner JOINER = on(",");
private static final Logger LOGGER = getLogger(PingService.class);
|
// Path: modules/exemplary/src/main/java/com/intuit/autumn/exemplary/data/Ping.java
// public class Ping {
//
// private String id;
// private String message;
//
// /**
// * Empty constructor.
// *
// * note: necessary default constructor used by jackson for serialization/deserialization
// */
//
// public Ping() {
// }
//
// /**
// * Constructor with configurable state.
// *
// * @param id instance id
// * @param message instance payload
// */
//
// public Ping(String id, String message) {
// this.id = id;
// this.message = message;
// }
//
// /**
// * Get instance id.
// *
// * @return instance id
// */
//
// public String getId() {
// return id;
// }
//
// /**
// * Set instance id.
// *
// * @param id instance id
// */
//
// public void setId(String id) {
// this.id = id;
// }
//
// /**
// * Get instance payload.
// *
// * @return instance payload
// */
//
// public String getMessage() {
// return message;
// }
//
// /**
// * Set instance payload.
// *
// * @param message instance payload
// */
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// /**
// * Instance JSON representation.
// *
// * @return json representation
// */
//
// @Override
// public String toString() {
// return format("Ping{id='%s',message='%s'}", id, message);
// }
// }
//
// Path: modules/web/src/main/java/com/intuit/autumn/web/HttpHeader.java
// public class HttpHeader {
//
// private final CacheControl cacheControl;
//
// @Inject
// public HttpHeader() {
// cacheControl = new CacheControl();
//
// cacheControl.setPrivate(TRUE);
// cacheControl.setNoCache(TRUE);
// }
//
// public Response.ResponseBuilder headers() {
// return headers(OK);
// }
//
// public Response.ResponseBuilder headers(Response.Status status) {
// return headers(status.getStatusCode());
// }
//
// public Response.ResponseBuilder headers(int status) {
// return status(status)
// .cacheControl(cacheControl)
// .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
// .header(ACCESS_CONTROL_ALLOW_HEADERS, "Authorization,X-Forwarded-For,Accept-Language,Content-Type")
// .header(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS")
// .header(ACCESS_CONTROL_REQUEST_METHOD, "GET,POST,OPTIONS");
// // .header("X-Application-Id", applicationName);
// }
// }
// Path: modules/exemplary/src/main/java/com/intuit/autumn/exemplary/server/PingService.java
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import com.intuit.autumn.exemplary.data.Ping;
import com.intuit.autumn.web.HttpHeader;
import org.slf4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.util.List;
import java.util.UUID;
import static com.google.common.base.Joiner.on;
import static java.util.Arrays.asList;
import static java.util.UUID.fromString;
import static java.util.UUID.randomUUID;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.exemplary.server;
/**
* Prototypical application endpoint implementation.
*/
@Provider
@Path("/proto")
public class PingService {
private static final Joiner JOINER = on(",");
private static final Logger LOGGER = getLogger(PingService.class);
|
private final HttpHeader httpHeader;
|
intuit/Autumn
|
modules/exemplary/src/main/java/com/intuit/autumn/exemplary/server/PingService.java
|
// Path: modules/exemplary/src/main/java/com/intuit/autumn/exemplary/data/Ping.java
// public class Ping {
//
// private String id;
// private String message;
//
// /**
// * Empty constructor.
// *
// * note: necessary default constructor used by jackson for serialization/deserialization
// */
//
// public Ping() {
// }
//
// /**
// * Constructor with configurable state.
// *
// * @param id instance id
// * @param message instance payload
// */
//
// public Ping(String id, String message) {
// this.id = id;
// this.message = message;
// }
//
// /**
// * Get instance id.
// *
// * @return instance id
// */
//
// public String getId() {
// return id;
// }
//
// /**
// * Set instance id.
// *
// * @param id instance id
// */
//
// public void setId(String id) {
// this.id = id;
// }
//
// /**
// * Get instance payload.
// *
// * @return instance payload
// */
//
// public String getMessage() {
// return message;
// }
//
// /**
// * Set instance payload.
// *
// * @param message instance payload
// */
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// /**
// * Instance JSON representation.
// *
// * @return json representation
// */
//
// @Override
// public String toString() {
// return format("Ping{id='%s',message='%s'}", id, message);
// }
// }
//
// Path: modules/web/src/main/java/com/intuit/autumn/web/HttpHeader.java
// public class HttpHeader {
//
// private final CacheControl cacheControl;
//
// @Inject
// public HttpHeader() {
// cacheControl = new CacheControl();
//
// cacheControl.setPrivate(TRUE);
// cacheControl.setNoCache(TRUE);
// }
//
// public Response.ResponseBuilder headers() {
// return headers(OK);
// }
//
// public Response.ResponseBuilder headers(Response.Status status) {
// return headers(status.getStatusCode());
// }
//
// public Response.ResponseBuilder headers(int status) {
// return status(status)
// .cacheControl(cacheControl)
// .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
// .header(ACCESS_CONTROL_ALLOW_HEADERS, "Authorization,X-Forwarded-For,Accept-Language,Content-Type")
// .header(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS")
// .header(ACCESS_CONTROL_REQUEST_METHOD, "GET,POST,OPTIONS");
// // .header("X-Application-Id", applicationName);
// }
// }
|
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import com.intuit.autumn.exemplary.data.Ping;
import com.intuit.autumn.web.HttpHeader;
import org.slf4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.util.List;
import java.util.UUID;
import static com.google.common.base.Joiner.on;
import static java.util.Arrays.asList;
import static java.util.UUID.fromString;
import static java.util.UUID.randomUUID;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.slf4j.LoggerFactory.getLogger;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.exemplary.server;
/**
* Prototypical application endpoint implementation.
*/
@Provider
@Path("/proto")
public class PingService {
private static final Joiner JOINER = on(",");
private static final Logger LOGGER = getLogger(PingService.class);
private final HttpHeader httpHeader;
private final Counter getPingCounter;
private final Timer getPingTimer;
private final Counter postPingCounter;
private final Counter getPingsCounter;
private final Timer getPingsTimer;
/**
* Instantiation method.
*
* @param metricRegistry operational metrics registry
*/
@Inject
public PingService(final HttpHeader httpHeader, final MetricRegistry metricRegistry) {
this.httpHeader = httpHeader;
getPingCounter = metricRegistry.counter("get-ping-counter");
getPingTimer = metricRegistry.timer("get-ping-timer");
postPingCounter = metricRegistry.counter("post-ping-counter");
getPingsCounter = metricRegistry.counter("get-pings-counter");
getPingsTimer = metricRegistry.timer("get-pings-timer");
}
/**
* Object reader, retrieving the object associated with the provided ID.
*
* @param id object ID
* @return representative object
* @throws Exception
*/
@GET
@Path("/ping/{id}")
@Produces(APPLICATION_JSON)
public Response ping(@PathParam("id") String id) throws Exception {
getPingCounter.inc();
LOGGER.debug("getting ping id: {}, count: {}", id, getPingCounter.getCount());
|
// Path: modules/exemplary/src/main/java/com/intuit/autumn/exemplary/data/Ping.java
// public class Ping {
//
// private String id;
// private String message;
//
// /**
// * Empty constructor.
// *
// * note: necessary default constructor used by jackson for serialization/deserialization
// */
//
// public Ping() {
// }
//
// /**
// * Constructor with configurable state.
// *
// * @param id instance id
// * @param message instance payload
// */
//
// public Ping(String id, String message) {
// this.id = id;
// this.message = message;
// }
//
// /**
// * Get instance id.
// *
// * @return instance id
// */
//
// public String getId() {
// return id;
// }
//
// /**
// * Set instance id.
// *
// * @param id instance id
// */
//
// public void setId(String id) {
// this.id = id;
// }
//
// /**
// * Get instance payload.
// *
// * @return instance payload
// */
//
// public String getMessage() {
// return message;
// }
//
// /**
// * Set instance payload.
// *
// * @param message instance payload
// */
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// /**
// * Instance JSON representation.
// *
// * @return json representation
// */
//
// @Override
// public String toString() {
// return format("Ping{id='%s',message='%s'}", id, message);
// }
// }
//
// Path: modules/web/src/main/java/com/intuit/autumn/web/HttpHeader.java
// public class HttpHeader {
//
// private final CacheControl cacheControl;
//
// @Inject
// public HttpHeader() {
// cacheControl = new CacheControl();
//
// cacheControl.setPrivate(TRUE);
// cacheControl.setNoCache(TRUE);
// }
//
// public Response.ResponseBuilder headers() {
// return headers(OK);
// }
//
// public Response.ResponseBuilder headers(Response.Status status) {
// return headers(status.getStatusCode());
// }
//
// public Response.ResponseBuilder headers(int status) {
// return status(status)
// .cacheControl(cacheControl)
// .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
// .header(ACCESS_CONTROL_ALLOW_HEADERS, "Authorization,X-Forwarded-For,Accept-Language,Content-Type")
// .header(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,OPTIONS")
// .header(ACCESS_CONTROL_REQUEST_METHOD, "GET,POST,OPTIONS");
// // .header("X-Application-Id", applicationName);
// }
// }
// Path: modules/exemplary/src/main/java/com/intuit/autumn/exemplary/server/PingService.java
import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import com.intuit.autumn.exemplary.data.Ping;
import com.intuit.autumn.web.HttpHeader;
import org.slf4j.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.util.List;
import java.util.UUID;
import static com.google.common.base.Joiner.on;
import static java.util.Arrays.asList;
import static java.util.UUID.fromString;
import static java.util.UUID.randomUUID;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.slf4j.LoggerFactory.getLogger;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.exemplary.server;
/**
* Prototypical application endpoint implementation.
*/
@Provider
@Path("/proto")
public class PingService {
private static final Joiner JOINER = on(",");
private static final Logger LOGGER = getLogger(PingService.class);
private final HttpHeader httpHeader;
private final Counter getPingCounter;
private final Timer getPingTimer;
private final Counter postPingCounter;
private final Counter getPingsCounter;
private final Timer getPingsTimer;
/**
* Instantiation method.
*
* @param metricRegistry operational metrics registry
*/
@Inject
public PingService(final HttpHeader httpHeader, final MetricRegistry metricRegistry) {
this.httpHeader = httpHeader;
getPingCounter = metricRegistry.counter("get-ping-counter");
getPingTimer = metricRegistry.timer("get-ping-timer");
postPingCounter = metricRegistry.counter("post-ping-counter");
getPingsCounter = metricRegistry.counter("get-pings-counter");
getPingsTimer = metricRegistry.timer("get-pings-timer");
}
/**
* Object reader, retrieving the object associated with the provided ID.
*
* @param id object ID
* @return representative object
* @throws Exception
*/
@GET
@Path("/ping/{id}")
@Produces(APPLICATION_JSON)
public Response ping(@PathParam("id") String id) throws Exception {
getPingCounter.inc();
LOGGER.debug("getting ping id: {}, count: {}", id, getPingCounter.getCount());
|
Ping ping;
|
intuit/Autumn
|
modules/web/src/main/java/com/intuit/autumn/web/WebServletModule.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import static java.lang.Boolean.TRUE;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Singleton;
import com.google.inject.servlet.ServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static com.sun.jersey.api.core.PackagesResourceConfig.PROPERTY_PACKAGES;
import static com.sun.jersey.api.core.ResourceConfig.*;
import static com.sun.jersey.api.json.JSONConfiguration.FEATURE_POJO_MAPPING;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes HTTP/S binding implementation dependencies, e.g.: servlet, guice
*/
public class WebServletModule extends ServletModule {
private ImmutableMap<String, KeyValue<String>> keys = ImmutableMap.<String, KeyValue<String>>builder()
.put("application.jersey.provider.paths", new KeyValue<>(PROPERTY_PACKAGES, ""))
.put("application.jersey.pojo.enabled", new KeyValue<>(FEATURE_POJO_MAPPING, TRUE.toString()))
.put("application.jersey.request.filters", new KeyValue<>(PROPERTY_CONTAINER_REQUEST_FILTERS, ""))
.put("application.jersey.response.filters", new KeyValue<>(PROPERTY_CONTAINER_RESPONSE_FILTERS, ""))
.put("application.jersey.wadl.enabled", new KeyValue<>(FEATURE_DISABLE_WADL, TRUE.toString()))
.build();
/**
* Inject module dependencies and bind guice filter delegates.
*/
@Override
protected void configureServlets() {
bind(WebFilter.class).in(Singleton.class);
bind(GuiceContainer.class);
Map<String, String> params = new HashMap<>();
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebServletModule.java
import static java.lang.Boolean.TRUE;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Singleton;
import com.google.inject.servlet.ServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static com.sun.jersey.api.core.PackagesResourceConfig.PROPERTY_PACKAGES;
import static com.sun.jersey.api.core.ResourceConfig.*;
import static com.sun.jersey.api.json.JSONConfiguration.FEATURE_POJO_MAPPING;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes HTTP/S binding implementation dependencies, e.g.: servlet, guice
*/
public class WebServletModule extends ServletModule {
private ImmutableMap<String, KeyValue<String>> keys = ImmutableMap.<String, KeyValue<String>>builder()
.put("application.jersey.provider.paths", new KeyValue<>(PROPERTY_PACKAGES, ""))
.put("application.jersey.pojo.enabled", new KeyValue<>(FEATURE_POJO_MAPPING, TRUE.toString()))
.put("application.jersey.request.filters", new KeyValue<>(PROPERTY_CONTAINER_REQUEST_FILTERS, ""))
.put("application.jersey.response.filters", new KeyValue<>(PROPERTY_CONTAINER_RESPONSE_FILTERS, ""))
.put("application.jersey.wadl.enabled", new KeyValue<>(FEATURE_DISABLE_WADL, TRUE.toString()))
.build();
/**
* Inject module dependencies and bind guice filter delegates.
*/
@Override
protected void configureServlets() {
bind(WebFilter.class).in(Singleton.class);
bind(GuiceContainer.class);
Map<String, String> params = new HashMap<>();
|
Properties properties = create(WebModule.PROPERTY_NAME, WebServletModule.class);
|
intuit/Autumn
|
modules/web/src/main/java/com/intuit/autumn/web/WebServletModule.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
|
import static java.lang.Boolean.TRUE;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Singleton;
import com.google.inject.servlet.ServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static com.sun.jersey.api.core.PackagesResourceConfig.PROPERTY_PACKAGES;
import static com.sun.jersey.api.core.ResourceConfig.*;
import static com.sun.jersey.api.json.JSONConfiguration.FEATURE_POJO_MAPPING;
|
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes HTTP/S binding implementation dependencies, e.g.: servlet, guice
*/
public class WebServletModule extends ServletModule {
private ImmutableMap<String, KeyValue<String>> keys = ImmutableMap.<String, KeyValue<String>>builder()
.put("application.jersey.provider.paths", new KeyValue<>(PROPERTY_PACKAGES, ""))
.put("application.jersey.pojo.enabled", new KeyValue<>(FEATURE_POJO_MAPPING, TRUE.toString()))
.put("application.jersey.request.filters", new KeyValue<>(PROPERTY_CONTAINER_REQUEST_FILTERS, ""))
.put("application.jersey.response.filters", new KeyValue<>(PROPERTY_CONTAINER_RESPONSE_FILTERS, ""))
.put("application.jersey.wadl.enabled", new KeyValue<>(FEATURE_DISABLE_WADL, TRUE.toString()))
.build();
/**
* Inject module dependencies and bind guice filter delegates.
*/
@Override
protected void configureServlets() {
bind(WebFilter.class).in(Singleton.class);
bind(GuiceContainer.class);
Map<String, String> params = new HashMap<>();
Properties properties = create(WebModule.PROPERTY_NAME, WebServletModule.class);
for (Map.Entry<String, KeyValue<String>> entry : keys.entrySet()) {
String key = entry.getKey();
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
//
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static String getProperty(final String key, final Properties properties) {
// return getProperty(key, properties, null);
// }
// Path: modules/web/src/main/java/com/intuit/autumn/web/WebServletModule.java
import static java.lang.Boolean.TRUE;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.trimToNull;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Singleton;
import com.google.inject.servlet.ServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static com.intuit.autumn.utils.PropertyFactory.getProperty;
import static com.sun.jersey.api.core.PackagesResourceConfig.PROPERTY_PACKAGES;
import static com.sun.jersey.api.core.ResourceConfig.*;
import static com.sun.jersey.api.json.JSONConfiguration.FEATURE_POJO_MAPPING;
/*
* Copyright 2016 Intuit
*
* 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.intuit.autumn.web;
/**
* An injector that includes HTTP/S binding implementation dependencies, e.g.: servlet, guice
*/
public class WebServletModule extends ServletModule {
private ImmutableMap<String, KeyValue<String>> keys = ImmutableMap.<String, KeyValue<String>>builder()
.put("application.jersey.provider.paths", new KeyValue<>(PROPERTY_PACKAGES, ""))
.put("application.jersey.pojo.enabled", new KeyValue<>(FEATURE_POJO_MAPPING, TRUE.toString()))
.put("application.jersey.request.filters", new KeyValue<>(PROPERTY_CONTAINER_REQUEST_FILTERS, ""))
.put("application.jersey.response.filters", new KeyValue<>(PROPERTY_CONTAINER_RESPONSE_FILTERS, ""))
.put("application.jersey.wadl.enabled", new KeyValue<>(FEATURE_DISABLE_WADL, TRUE.toString()))
.build();
/**
* Inject module dependencies and bind guice filter delegates.
*/
@Override
protected void configureServlets() {
bind(WebFilter.class).in(Singleton.class);
bind(GuiceContainer.class);
Map<String, String> params = new HashMap<>();
Properties properties = create(WebModule.PROPERTY_NAME, WebServletModule.class);
for (Map.Entry<String, KeyValue<String>> entry : keys.entrySet()) {
String key = entry.getKey();
|
String jerseyProperty = trimToNull(getProperty(key, properties, entry.getValue().getValue()));
|
intuit/Autumn
|
modules/service/src/main/java/com/intuit/autumn/service/ServiceManager.java
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
|
import com.google.common.util.concurrent.Service;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.netflix.governator.configuration.CompositeConfigurationProvider;
import com.netflix.governator.configuration.PropertiesConfigurationProvider;
import com.netflix.governator.configuration.SystemConfigurationProvider;
import com.netflix.governator.guice.BootstrapBinder;
import com.netflix.governator.guice.BootstrapModule;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.governator.lifecycle.LifecycleManager;
import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static java.util.Arrays.asList;
import static java.util.Collections.EMPTY_LIST;
import static org.slf4j.LoggerFactory.getLogger;
|
@Override
public void configure(BootstrapBinder binder) {
CompositeConfigurationProvider compositeConfigurationProvider = new CompositeConfigurationProvider();
for (Properties property : getConfigurations()) {
compositeConfigurationProvider.add(new PropertiesConfigurationProvider(property));
}
binder.bindConfigurationProvider().toInstance(compositeConfigurationProvider);
}
})
.withModuleClasses(modules.getResources())
.build()
.createInjector();
lifecycleManager = injector.getInstance(LifecycleManager.class);
try {
lifecycleManager.start();
} catch (Exception e) {
throw new ServiceManagerException("unable to start the lifecycle manager", e);
}
return injector;
}
private Set<Properties> getConfigurations() {
Set<Properties> configs = newHashSet();
for (String configurationResource : this.configurations.getResources()) {
|
// Path: modules/utils/src/main/java/com/intuit/autumn/utils/PropertyFactory.java
// public static Properties create(final String propertyResourceName) {
// return create(propertyResourceName, null);
// }
// Path: modules/service/src/main/java/com/intuit/autumn/service/ServiceManager.java
import com.google.common.util.concurrent.Service;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.netflix.governator.configuration.CompositeConfigurationProvider;
import com.netflix.governator.configuration.PropertiesConfigurationProvider;
import com.netflix.governator.configuration.SystemConfigurationProvider;
import com.netflix.governator.guice.BootstrapBinder;
import com.netflix.governator.guice.BootstrapModule;
import com.netflix.governator.guice.LifecycleInjector;
import com.netflix.governator.lifecycle.LifecycleManager;
import org.slf4j.Logger;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Properties;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static com.intuit.autumn.utils.PropertyFactory.create;
import static java.util.Arrays.asList;
import static java.util.Collections.EMPTY_LIST;
import static org.slf4j.LoggerFactory.getLogger;
@Override
public void configure(BootstrapBinder binder) {
CompositeConfigurationProvider compositeConfigurationProvider = new CompositeConfigurationProvider();
for (Properties property : getConfigurations()) {
compositeConfigurationProvider.add(new PropertiesConfigurationProvider(property));
}
binder.bindConfigurationProvider().toInstance(compositeConfigurationProvider);
}
})
.withModuleClasses(modules.getResources())
.build()
.createInjector();
lifecycleManager = injector.getInstance(LifecycleManager.class);
try {
lifecycleManager.start();
} catch (Exception e) {
throw new ServiceManagerException("unable to start the lifecycle manager", e);
}
return injector;
}
private Set<Properties> getConfigurations() {
Set<Properties> configs = newHashSet();
for (String configurationResource : this.configurations.getResources()) {
|
configs.add(create(configurationResource));
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/listadapter/UnitEditorAdapter.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/sorting/AlphabeticalUnitComparator.java
// public class AlphabeticalUnitComparator implements Comparator<Unit> {
//
// private static AlphabeticalUnitComparator sInstance;
//
// @Override
// public int compare(Unit _lhs, Unit _rhs) {
// if (_lhs.equals(_rhs)) {
// return 0;
// }
// return Collator.getInstance().compare(_lhs.mName, _rhs.mName);
// }
//
// public static AlphabeticalUnitComparator getInstance() {
// if (sInstance == null) {
// sInstance = new AlphabeticalUnitComparator();
// }
// return sInstance;
// }
// }
|
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.noorganization.instalist.R;
import org.noorganization.instalist.model.Unit;
import org.noorganization.instalist.view.sorting.AlphabeticalUnitComparator;
import java.util.ArrayList;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.listadapter;
/**
* An Adapter that is based on a always alphabetically sorted List for Units.
* Created by daMihe on 22.07.2015.
*/
public class UnitEditorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_TEXTVIEW = 0;
private static final int TYPE_EDITTEXT = 1;
private Activity mActivity;
private List<Unit> mUnderLyingUnits;
private ActionMode.Callback mEditingMode;
private int mEditingPosition;
public UnitEditorAdapter(Activity _activity, List<Unit> _elements, ActionMode.Callback _editorCallback) {
mActivity = _activity;
mUnderLyingUnits = new ArrayList<>();
if (_elements != null) {
mUnderLyingUnits.addAll(_elements);
|
// Path: app/src/main/java/org/noorganization/instalist/view/sorting/AlphabeticalUnitComparator.java
// public class AlphabeticalUnitComparator implements Comparator<Unit> {
//
// private static AlphabeticalUnitComparator sInstance;
//
// @Override
// public int compare(Unit _lhs, Unit _rhs) {
// if (_lhs.equals(_rhs)) {
// return 0;
// }
// return Collator.getInstance().compare(_lhs.mName, _rhs.mName);
// }
//
// public static AlphabeticalUnitComparator getInstance() {
// if (sInstance == null) {
// sInstance = new AlphabeticalUnitComparator();
// }
// return sInstance;
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/view/listadapter/UnitEditorAdapter.java
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import org.noorganization.instalist.R;
import org.noorganization.instalist.model.Unit;
import org.noorganization.instalist.view.sorting.AlphabeticalUnitComparator;
import java.util.ArrayList;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.listadapter;
/**
* An Adapter that is based on a always alphabetically sorted List for Units.
* Created by daMihe on 22.07.2015.
*/
public class UnitEditorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_TEXTVIEW = 0;
private static final int TYPE_EDITTEXT = 1;
private Activity mActivity;
private List<Unit> mUnderLyingUnits;
private ActionMode.Callback mEditingMode;
private int mEditingPosition;
public UnitEditorAdapter(Activity _activity, List<Unit> _elements, ActionMode.Callback _editorCallback) {
mActivity = _activity;
mUnderLyingUnits = new ArrayList<>();
if (_elements != null) {
mUnderLyingUnits.addAll(_elements);
|
Collections.sort(mUnderLyingUnits, AlphabeticalUnitComparator.getInstance());
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/modelwrappers/ProductListEntry.java
|
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
// public class GlobalApplication extends Application {
//
// private final static String LOG_TAG = GlobalApplication.class.getName();
//
// private static GlobalApplication mInstance;
// private ShoppingList mCurrentShoppingList;
//
// private boolean mBufferItemChangedMessages;
// private boolean mHandlingProductSelectedMessages;
// private List<ListItemChangedMessage> mBufferedMessages;
//
// public static GlobalApplication getInstance() {
// return mInstance;
// }
//
// public static Context getContext() {
// return getInstance().getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mInstance = this;
// EventBus.getDefault().register(this);
// mBufferedMessages = new LinkedList<>();
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// public void onEvent(ActivityStateMessage _message) {
// mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
// }
//
// public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
// mCurrentShoppingList = _selectedShoppingList.mShoppingList;
// }
//
// public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
// mBufferItemChangedMessages = !_event.mActive;
// if (!mBufferItemChangedMessages) {
// for (ListItemChangedMessage message : mBufferedMessages)
// EventBus.getDefault().post(message);
//
// mBufferedMessages.clear();
// }
// }
//
// public void onEvent(ListItemChangedMessage _message) {
// if (mBufferItemChangedMessages) {
// mBufferedMessages.add(_message);
// }
// }
//
// public void onEvent(ProductSelectMessage _message) {
// if (mCurrentShoppingList == null) {
// Toast.makeText(getContext(), R.string.abc_no_shopping_list_selected, Toast.LENGTH_SHORT).show();
// return;
// }
// if (mHandlingProductSelectedMessages) {
// Map<Product, Float> productAmounts = _message.mProducts;
// IListController controller = ControllerFactory.getListController(getContext());
// for (Product currentProduct : productAmounts.keySet()) {
// controller.addOrChangeItem(mCurrentShoppingList, currentProduct,
// productAmounts.get(currentProduct), true);
// }
// }
// }
//
// }
|
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseBooleanArray;
import org.noorganization.instalist.GlobalApplication;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.Product;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.modelwrappers;
/**
* Wrapper for Products to strike/unstrike them.
* Created by TS on 25.05.2015.
*/
public class ProductListEntry implements IBaseListEntry {
public static final int CHECKED_PROPERTY = 0;
private Product mProduct;
private boolean mChecked;
public ProductListEntry(Product _Product) {
mProduct = _Product;
}
private ProductListEntry(Parcel _In) {
mChecked = _In.readSparseBooleanArray().get(CHECKED_PROPERTY);
|
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
// public class GlobalApplication extends Application {
//
// private final static String LOG_TAG = GlobalApplication.class.getName();
//
// private static GlobalApplication mInstance;
// private ShoppingList mCurrentShoppingList;
//
// private boolean mBufferItemChangedMessages;
// private boolean mHandlingProductSelectedMessages;
// private List<ListItemChangedMessage> mBufferedMessages;
//
// public static GlobalApplication getInstance() {
// return mInstance;
// }
//
// public static Context getContext() {
// return getInstance().getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mInstance = this;
// EventBus.getDefault().register(this);
// mBufferedMessages = new LinkedList<>();
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// public void onEvent(ActivityStateMessage _message) {
// mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
// }
//
// public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
// mCurrentShoppingList = _selectedShoppingList.mShoppingList;
// }
//
// public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
// mBufferItemChangedMessages = !_event.mActive;
// if (!mBufferItemChangedMessages) {
// for (ListItemChangedMessage message : mBufferedMessages)
// EventBus.getDefault().post(message);
//
// mBufferedMessages.clear();
// }
// }
//
// public void onEvent(ListItemChangedMessage _message) {
// if (mBufferItemChangedMessages) {
// mBufferedMessages.add(_message);
// }
// }
//
// public void onEvent(ProductSelectMessage _message) {
// if (mCurrentShoppingList == null) {
// Toast.makeText(getContext(), R.string.abc_no_shopping_list_selected, Toast.LENGTH_SHORT).show();
// return;
// }
// if (mHandlingProductSelectedMessages) {
// Map<Product, Float> productAmounts = _message.mProducts;
// IListController controller = ControllerFactory.getListController(getContext());
// for (Product currentProduct : productAmounts.keySet()) {
// controller.addOrChangeItem(mCurrentShoppingList, currentProduct,
// productAmounts.get(currentProduct), true);
// }
// }
// }
//
// }
// Path: app/src/main/java/org/noorganization/instalist/view/modelwrappers/ProductListEntry.java
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseBooleanArray;
import org.noorganization.instalist.GlobalApplication;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.Product;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.modelwrappers;
/**
* Wrapper for Products to strike/unstrike them.
* Created by TS on 25.05.2015.
*/
public class ProductListEntry implements IBaseListEntry {
public static final int CHECKED_PROPERTY = 0;
private Product mProduct;
private boolean mChecked;
public ProductListEntry(Product _Product) {
mProduct = _Product;
}
private ProductListEntry(Parcel _In) {
mChecked = _In.readSparseBooleanArray().get(CHECKED_PROPERTY);
|
mProduct = ControllerFactory.getProductController(GlobalApplication.getContext()).findById(_In.readString());
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/GlobalApplication.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
|
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist;
/**
* Global application class.
* Created by TS on 21.04.2015.
*/
public class GlobalApplication extends Application {
private final static String LOG_TAG = GlobalApplication.class.getName();
private static GlobalApplication mInstance;
private ShoppingList mCurrentShoppingList;
private boolean mBufferItemChangedMessages;
private boolean mHandlingProductSelectedMessages;
private List<ListItemChangedMessage> mBufferedMessages;
public static GlobalApplication getInstance() {
return mInstance;
}
public static Context getContext() {
return getInstance().getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
EventBus.getDefault().register(this);
mBufferedMessages = new LinkedList<>();
}
@Override
public void onTerminate() {
super.onTerminate();
}
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist;
/**
* Global application class.
* Created by TS on 21.04.2015.
*/
public class GlobalApplication extends Application {
private final static String LOG_TAG = GlobalApplication.class.getName();
private static GlobalApplication mInstance;
private ShoppingList mCurrentShoppingList;
private boolean mBufferItemChangedMessages;
private boolean mHandlingProductSelectedMessages;
private List<ListItemChangedMessage> mBufferedMessages;
public static GlobalApplication getInstance() {
return mInstance;
}
public static Context getContext() {
return getInstance().getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
EventBus.getDefault().register(this);
mBufferedMessages = new LinkedList<>();
}
@Override
public void onTerminate() {
super.onTerminate();
}
|
public void onEvent(ActivityStateMessage _message) {
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/GlobalApplication.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
|
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist;
/**
* Global application class.
* Created by TS on 21.04.2015.
*/
public class GlobalApplication extends Application {
private final static String LOG_TAG = GlobalApplication.class.getName();
private static GlobalApplication mInstance;
private ShoppingList mCurrentShoppingList;
private boolean mBufferItemChangedMessages;
private boolean mHandlingProductSelectedMessages;
private List<ListItemChangedMessage> mBufferedMessages;
public static GlobalApplication getInstance() {
return mInstance;
}
public static Context getContext() {
return getInstance().getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
EventBus.getDefault().register(this);
mBufferedMessages = new LinkedList<>();
}
@Override
public void onTerminate() {
super.onTerminate();
}
public void onEvent(ActivityStateMessage _message) {
mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
}
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist;
/**
* Global application class.
* Created by TS on 21.04.2015.
*/
public class GlobalApplication extends Application {
private final static String LOG_TAG = GlobalApplication.class.getName();
private static GlobalApplication mInstance;
private ShoppingList mCurrentShoppingList;
private boolean mBufferItemChangedMessages;
private boolean mHandlingProductSelectedMessages;
private List<ListItemChangedMessage> mBufferedMessages;
public static GlobalApplication getInstance() {
return mInstance;
}
public static Context getContext() {
return getInstance().getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
EventBus.getDefault().register(this);
mBufferedMessages = new LinkedList<>();
}
@Override
public void onTerminate() {
super.onTerminate();
}
public void onEvent(ActivityStateMessage _message) {
mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
}
|
public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/GlobalApplication.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
|
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
|
public static GlobalApplication getInstance() {
return mInstance;
}
public static Context getContext() {
return getInstance().getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
EventBus.getDefault().register(this);
mBufferedMessages = new LinkedList<>();
}
@Override
public void onTerminate() {
super.onTerminate();
}
public void onEvent(ActivityStateMessage _message) {
mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
}
public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
mCurrentShoppingList = _selectedShoppingList.mShoppingList;
}
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
public static GlobalApplication getInstance() {
return mInstance;
}
public static Context getContext() {
return getInstance().getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
EventBus.getDefault().register(this);
mBufferedMessages = new LinkedList<>();
}
@Override
public void onTerminate() {
super.onTerminate();
}
public void onEvent(ActivityStateMessage _message) {
mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
}
public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
mCurrentShoppingList = _selectedShoppingList.mShoppingList;
}
|
public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/GlobalApplication.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
|
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
|
@Override
public void onTerminate() {
super.onTerminate();
}
public void onEvent(ActivityStateMessage _message) {
mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
}
public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
mCurrentShoppingList = _selectedShoppingList.mShoppingList;
}
public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
mBufferItemChangedMessages = !_event.mActive;
if (!mBufferItemChangedMessages) {
for (ListItemChangedMessage message : mBufferedMessages)
EventBus.getDefault().post(message);
mBufferedMessages.clear();
}
}
public void onEvent(ListItemChangedMessage _message) {
if (mBufferItemChangedMessages) {
mBufferedMessages.add(_message);
}
}
|
// Path: app/src/main/java/org/noorganization/instalist/view/event/ActivityStateMessage.java
// public class ActivityStateMessage {
// public enum State {
// PAUSED,
// RESUMED
// }
//
// /**
// * The activity which state changes.
// */
// public Activity mActivity;
//
// /**
// * The new state of the activity.
// */
// public State mState;
//
// public ActivityStateMessage(Activity _activity, State _state) {
// mActivity = _activity;
// mState = _state;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ProductSelectMessage.java
// public class ProductSelectMessage {
// public Map<Product, Float> mProducts;
//
// public ProductSelectMessage(Map<Product, Float> _products) {
// mProducts = _products;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListOverviewFragmentActiveEvent.java
// public class ShoppingListOverviewFragmentActiveEvent {
//
// public boolean mActive;
//
// public ShoppingListOverviewFragmentActiveEvent(boolean _active){
// mActive = _active;
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/event/ShoppingListSelectedMessage.java
// public class ShoppingListSelectedMessage {
//
// /**
// * The attribute ShoppingList.
// */
// public ShoppingList mShoppingList;
//
// /**
// * Constructor of the EventMessage.
// * @param _shoppingList the shoppingList that was selected.
// */
// public ShoppingListSelectedMessage(@NonNull ShoppingList _shoppingList) {
// mShoppingList = _shoppingList;
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import de.greenrobot.event.EventBus;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;
import org.noorganization.instalist.model.Product;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.event.ListItemChangedMessage;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.view.event.ActivityStateMessage;
import org.noorganization.instalist.view.event.ProductSelectMessage;
import org.noorganization.instalist.view.event.ShoppingListOverviewFragmentActiveEvent;
import org.noorganization.instalist.view.event.ShoppingListSelectedMessage;
@Override
public void onTerminate() {
super.onTerminate();
}
public void onEvent(ActivityStateMessage _message) {
mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
}
public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
mCurrentShoppingList = _selectedShoppingList.mShoppingList;
}
public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
mBufferItemChangedMessages = !_event.mActive;
if (!mBufferItemChangedMessages) {
for (ListItemChangedMessage message : mBufferedMessages)
EventBus.getDefault().post(message);
mBufferedMessages.clear();
}
}
public void onEvent(ListItemChangedMessage _message) {
if (mBufferItemChangedMessages) {
mBufferedMessages.add(_message);
}
}
|
public void onEvent(ProductSelectMessage _message) {
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginController.java
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/IPluginController.java
// public interface IPluginController {
//
// /**
// * Starts a search for the Plugins. This Process is asynchronous and it's return value will be
// * delivered via the bus.
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/IPluginBroadCast.java
// public interface IPluginBroadCast {
//
// /**
// * @see IPluginBroadCast#searchPlugins()
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/implementation/PluginBroadcastReceiver.java
// public class PluginBroadcastReceiver extends BroadcastReceiver implements IPluginBroadCast {
//
// static final String PLUGIN_INFO_KEY_NAME = "name";
// static final String PLUGIN_INFO_KEY_SETTINGS_ACTIVITY = "settings";
// static final String PLUGIN_INFO_KEY_MAIN_ACTIVITY = "main";
// static final String PLUGIN_INFO_KEY_PACKAGE = "package";
//
// private Context mContext;
//
// /**
// * Empty construtor for receive.
// */
// public PluginBroadcastReceiver() {
// super();
// }
//
// public PluginBroadcastReceiver(Context _context) {
// super();
// mContext = _context;
// }
//
// @Override
// public void searchPlugins() {
// Log.d("PluginBroadcastReceiver", "Sending " + PluginControllerActions.ACTION_PING);
// Intent pingBroadcast = new Intent(PluginControllerActions.ACTION_PING);
// pingBroadcast.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// pingBroadcast.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// mContext.sendBroadcast(pingBroadcast);
// Log.d(getClass().getCanonicalName(), "Sent searchPlugins broadcast.");
// }
//
// @Override
// public void onReceive(Context _context, Intent _intent) {
// Log.d(getClass().getCanonicalName(), "Got Intent.");
//
// if (!_intent.getAction().equals(PluginControllerActions.ACTION_PONG)) {
// Log.d(getClass().getCanonicalName(), "No Pong action.");
// return;
// }
//
// Bundle pluginInfo = _intent.getExtras();
// PluginFoundMessage event = new PluginFoundMessage(pluginInfo.getString(PLUGIN_INFO_KEY_NAME),
// pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE));
// Log.d(getClass().getCanonicalName(), "Trying find main activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_MAIN_ACTIVITY)) {
// try {
// event.mMainActivity = Class.forName(
// pluginInfo.getString(PLUGIN_INFO_KEY_MAIN_ACTIVITY));
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Trying find settings activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY)) {
// try {
// // load classes from other apks
// String sourceDir = _context.getPackageManager().getApplicationInfo(pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE), PackageManager.GET_ACTIVITIES).sourceDir;
// PathClassLoader pathClassLoader = new dalvik.system.PathClassLoader(sourceDir, ClassLoader.getSystemClassLoader());
// event.mSettingsActivity = Class.forName(pluginInfo.getString(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY), true, pathClassLoader);
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Found Plugin! " + event.mName + " in " + event.mPackage);
// // TODO: implement translator to event for bus.
//
// EventBus.getDefault().post(event);
// }
// }
|
import android.content.Context;
import org.noorganization.instalist.presenter.IPluginController;
import org.noorganization.instalist.presenter.broadcast.IPluginBroadCast;
import org.noorganization.instalist.presenter.broadcast.implementation.PluginBroadcastReceiver;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.presenter.implementation;
/**
* The PluginController delivers functionality to trigger a plugin search.
* It delivers the {@link org.noorganization.instalist.presenter.event.PluginFoundMessage} when detected.
*
* Type: Singleton.
*
* Created by damihe on 06.01.16.
*/
public class PluginController implements IPluginController {
private static PluginController sInstance;
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/IPluginController.java
// public interface IPluginController {
//
// /**
// * Starts a search for the Plugins. This Process is asynchronous and it's return value will be
// * delivered via the bus.
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/IPluginBroadCast.java
// public interface IPluginBroadCast {
//
// /**
// * @see IPluginBroadCast#searchPlugins()
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/implementation/PluginBroadcastReceiver.java
// public class PluginBroadcastReceiver extends BroadcastReceiver implements IPluginBroadCast {
//
// static final String PLUGIN_INFO_KEY_NAME = "name";
// static final String PLUGIN_INFO_KEY_SETTINGS_ACTIVITY = "settings";
// static final String PLUGIN_INFO_KEY_MAIN_ACTIVITY = "main";
// static final String PLUGIN_INFO_KEY_PACKAGE = "package";
//
// private Context mContext;
//
// /**
// * Empty construtor for receive.
// */
// public PluginBroadcastReceiver() {
// super();
// }
//
// public PluginBroadcastReceiver(Context _context) {
// super();
// mContext = _context;
// }
//
// @Override
// public void searchPlugins() {
// Log.d("PluginBroadcastReceiver", "Sending " + PluginControllerActions.ACTION_PING);
// Intent pingBroadcast = new Intent(PluginControllerActions.ACTION_PING);
// pingBroadcast.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// pingBroadcast.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// mContext.sendBroadcast(pingBroadcast);
// Log.d(getClass().getCanonicalName(), "Sent searchPlugins broadcast.");
// }
//
// @Override
// public void onReceive(Context _context, Intent _intent) {
// Log.d(getClass().getCanonicalName(), "Got Intent.");
//
// if (!_intent.getAction().equals(PluginControllerActions.ACTION_PONG)) {
// Log.d(getClass().getCanonicalName(), "No Pong action.");
// return;
// }
//
// Bundle pluginInfo = _intent.getExtras();
// PluginFoundMessage event = new PluginFoundMessage(pluginInfo.getString(PLUGIN_INFO_KEY_NAME),
// pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE));
// Log.d(getClass().getCanonicalName(), "Trying find main activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_MAIN_ACTIVITY)) {
// try {
// event.mMainActivity = Class.forName(
// pluginInfo.getString(PLUGIN_INFO_KEY_MAIN_ACTIVITY));
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Trying find settings activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY)) {
// try {
// // load classes from other apks
// String sourceDir = _context.getPackageManager().getApplicationInfo(pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE), PackageManager.GET_ACTIVITIES).sourceDir;
// PathClassLoader pathClassLoader = new dalvik.system.PathClassLoader(sourceDir, ClassLoader.getSystemClassLoader());
// event.mSettingsActivity = Class.forName(pluginInfo.getString(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY), true, pathClassLoader);
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Found Plugin! " + event.mName + " in " + event.mPackage);
// // TODO: implement translator to event for bus.
//
// EventBus.getDefault().post(event);
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginController.java
import android.content.Context;
import org.noorganization.instalist.presenter.IPluginController;
import org.noorganization.instalist.presenter.broadcast.IPluginBroadCast;
import org.noorganization.instalist.presenter.broadcast.implementation.PluginBroadcastReceiver;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.presenter.implementation;
/**
* The PluginController delivers functionality to trigger a plugin search.
* It delivers the {@link org.noorganization.instalist.presenter.event.PluginFoundMessage} when detected.
*
* Type: Singleton.
*
* Created by damihe on 06.01.16.
*/
public class PluginController implements IPluginController {
private static PluginController sInstance;
|
private IPluginBroadCast mPluginBroadcastReceiver;
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginController.java
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/IPluginController.java
// public interface IPluginController {
//
// /**
// * Starts a search for the Plugins. This Process is asynchronous and it's return value will be
// * delivered via the bus.
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/IPluginBroadCast.java
// public interface IPluginBroadCast {
//
// /**
// * @see IPluginBroadCast#searchPlugins()
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/implementation/PluginBroadcastReceiver.java
// public class PluginBroadcastReceiver extends BroadcastReceiver implements IPluginBroadCast {
//
// static final String PLUGIN_INFO_KEY_NAME = "name";
// static final String PLUGIN_INFO_KEY_SETTINGS_ACTIVITY = "settings";
// static final String PLUGIN_INFO_KEY_MAIN_ACTIVITY = "main";
// static final String PLUGIN_INFO_KEY_PACKAGE = "package";
//
// private Context mContext;
//
// /**
// * Empty construtor for receive.
// */
// public PluginBroadcastReceiver() {
// super();
// }
//
// public PluginBroadcastReceiver(Context _context) {
// super();
// mContext = _context;
// }
//
// @Override
// public void searchPlugins() {
// Log.d("PluginBroadcastReceiver", "Sending " + PluginControllerActions.ACTION_PING);
// Intent pingBroadcast = new Intent(PluginControllerActions.ACTION_PING);
// pingBroadcast.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// pingBroadcast.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// mContext.sendBroadcast(pingBroadcast);
// Log.d(getClass().getCanonicalName(), "Sent searchPlugins broadcast.");
// }
//
// @Override
// public void onReceive(Context _context, Intent _intent) {
// Log.d(getClass().getCanonicalName(), "Got Intent.");
//
// if (!_intent.getAction().equals(PluginControllerActions.ACTION_PONG)) {
// Log.d(getClass().getCanonicalName(), "No Pong action.");
// return;
// }
//
// Bundle pluginInfo = _intent.getExtras();
// PluginFoundMessage event = new PluginFoundMessage(pluginInfo.getString(PLUGIN_INFO_KEY_NAME),
// pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE));
// Log.d(getClass().getCanonicalName(), "Trying find main activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_MAIN_ACTIVITY)) {
// try {
// event.mMainActivity = Class.forName(
// pluginInfo.getString(PLUGIN_INFO_KEY_MAIN_ACTIVITY));
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Trying find settings activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY)) {
// try {
// // load classes from other apks
// String sourceDir = _context.getPackageManager().getApplicationInfo(pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE), PackageManager.GET_ACTIVITIES).sourceDir;
// PathClassLoader pathClassLoader = new dalvik.system.PathClassLoader(sourceDir, ClassLoader.getSystemClassLoader());
// event.mSettingsActivity = Class.forName(pluginInfo.getString(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY), true, pathClassLoader);
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Found Plugin! " + event.mName + " in " + event.mPackage);
// // TODO: implement translator to event for bus.
//
// EventBus.getDefault().post(event);
// }
// }
|
import android.content.Context;
import org.noorganization.instalist.presenter.IPluginController;
import org.noorganization.instalist.presenter.broadcast.IPluginBroadCast;
import org.noorganization.instalist.presenter.broadcast.implementation.PluginBroadcastReceiver;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.presenter.implementation;
/**
* The PluginController delivers functionality to trigger a plugin search.
* It delivers the {@link org.noorganization.instalist.presenter.event.PluginFoundMessage} when detected.
*
* Type: Singleton.
*
* Created by damihe on 06.01.16.
*/
public class PluginController implements IPluginController {
private static PluginController sInstance;
private IPluginBroadCast mPluginBroadcastReceiver;
@Override
public void searchPlugins() {
mPluginBroadcastReceiver.searchPlugins();
}
static PluginController getInstance(Context _context) {
if (sInstance == null) {
sInstance = new PluginController(_context);
}
return sInstance;
}
private PluginController() {
}
private PluginController(Context _context) {
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/IPluginController.java
// public interface IPluginController {
//
// /**
// * Starts a search for the Plugins. This Process is asynchronous and it's return value will be
// * delivered via the bus.
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/IPluginBroadCast.java
// public interface IPluginBroadCast {
//
// /**
// * @see IPluginBroadCast#searchPlugins()
// */
// void searchPlugins();
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/implementation/PluginBroadcastReceiver.java
// public class PluginBroadcastReceiver extends BroadcastReceiver implements IPluginBroadCast {
//
// static final String PLUGIN_INFO_KEY_NAME = "name";
// static final String PLUGIN_INFO_KEY_SETTINGS_ACTIVITY = "settings";
// static final String PLUGIN_INFO_KEY_MAIN_ACTIVITY = "main";
// static final String PLUGIN_INFO_KEY_PACKAGE = "package";
//
// private Context mContext;
//
// /**
// * Empty construtor for receive.
// */
// public PluginBroadcastReceiver() {
// super();
// }
//
// public PluginBroadcastReceiver(Context _context) {
// super();
// mContext = _context;
// }
//
// @Override
// public void searchPlugins() {
// Log.d("PluginBroadcastReceiver", "Sending " + PluginControllerActions.ACTION_PING);
// Intent pingBroadcast = new Intent(PluginControllerActions.ACTION_PING);
// pingBroadcast.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
// pingBroadcast.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// mContext.sendBroadcast(pingBroadcast);
// Log.d(getClass().getCanonicalName(), "Sent searchPlugins broadcast.");
// }
//
// @Override
// public void onReceive(Context _context, Intent _intent) {
// Log.d(getClass().getCanonicalName(), "Got Intent.");
//
// if (!_intent.getAction().equals(PluginControllerActions.ACTION_PONG)) {
// Log.d(getClass().getCanonicalName(), "No Pong action.");
// return;
// }
//
// Bundle pluginInfo = _intent.getExtras();
// PluginFoundMessage event = new PluginFoundMessage(pluginInfo.getString(PLUGIN_INFO_KEY_NAME),
// pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE));
// Log.d(getClass().getCanonicalName(), "Trying find main activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_MAIN_ACTIVITY)) {
// try {
// event.mMainActivity = Class.forName(
// pluginInfo.getString(PLUGIN_INFO_KEY_MAIN_ACTIVITY));
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Trying find settings activity");
// if (pluginInfo.containsKey(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY)) {
// try {
// // load classes from other apks
// String sourceDir = _context.getPackageManager().getApplicationInfo(pluginInfo.getString(PLUGIN_INFO_KEY_PACKAGE), PackageManager.GET_ACTIVITIES).sourceDir;
// PathClassLoader pathClassLoader = new dalvik.system.PathClassLoader(sourceDir, ClassLoader.getSystemClassLoader());
// event.mSettingsActivity = Class.forName(pluginInfo.getString(PLUGIN_INFO_KEY_SETTINGS_ACTIVITY), true, pathClassLoader);
// } catch (Exception e) {
// Log.e(getClass().getCanonicalName(), "Plugin loading failed: " + e.getMessage());
// return;
// }
// }
// Log.d(getClass().getCanonicalName(), "Found Plugin! " + event.mName + " in " + event.mPackage);
// // TODO: implement translator to event for bus.
//
// EventBus.getDefault().post(event);
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginController.java
import android.content.Context;
import org.noorganization.instalist.presenter.IPluginController;
import org.noorganization.instalist.presenter.broadcast.IPluginBroadCast;
import org.noorganization.instalist.presenter.broadcast.implementation.PluginBroadcastReceiver;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.presenter.implementation;
/**
* The PluginController delivers functionality to trigger a plugin search.
* It delivers the {@link org.noorganization.instalist.presenter.event.PluginFoundMessage} when detected.
*
* Type: Singleton.
*
* Created by damihe on 06.01.16.
*/
public class PluginController implements IPluginController {
private static PluginController sInstance;
private IPluginBroadCast mPluginBroadcastReceiver;
@Override
public void searchPlugins() {
mPluginBroadcastReceiver.searchPlugins();
}
static PluginController getInstance(Context _context) {
if (sInstance == null) {
sInstance = new PluginController(_context);
}
return sInstance;
}
private PluginController() {
}
private PluginController(Context _context) {
|
mPluginBroadcastReceiver = new PluginBroadcastReceiver(_context);
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/modelwrappers/RecipeListEntry.java
|
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
// public class GlobalApplication extends Application {
//
// private final static String LOG_TAG = GlobalApplication.class.getName();
//
// private static GlobalApplication mInstance;
// private ShoppingList mCurrentShoppingList;
//
// private boolean mBufferItemChangedMessages;
// private boolean mHandlingProductSelectedMessages;
// private List<ListItemChangedMessage> mBufferedMessages;
//
// public static GlobalApplication getInstance() {
// return mInstance;
// }
//
// public static Context getContext() {
// return getInstance().getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mInstance = this;
// EventBus.getDefault().register(this);
// mBufferedMessages = new LinkedList<>();
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// public void onEvent(ActivityStateMessage _message) {
// mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
// }
//
// public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
// mCurrentShoppingList = _selectedShoppingList.mShoppingList;
// }
//
// public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
// mBufferItemChangedMessages = !_event.mActive;
// if (!mBufferItemChangedMessages) {
// for (ListItemChangedMessage message : mBufferedMessages)
// EventBus.getDefault().post(message);
//
// mBufferedMessages.clear();
// }
// }
//
// public void onEvent(ListItemChangedMessage _message) {
// if (mBufferItemChangedMessages) {
// mBufferedMessages.add(_message);
// }
// }
//
// public void onEvent(ProductSelectMessage _message) {
// if (mCurrentShoppingList == null) {
// Toast.makeText(getContext(), R.string.abc_no_shopping_list_selected, Toast.LENGTH_SHORT).show();
// return;
// }
// if (mHandlingProductSelectedMessages) {
// Map<Product, Float> productAmounts = _message.mProducts;
// IListController controller = ControllerFactory.getListController(getContext());
// for (Product currentProduct : productAmounts.keySet()) {
// controller.addOrChangeItem(mCurrentShoppingList, currentProduct,
// productAmounts.get(currentProduct), true);
// }
// }
// }
//
// }
|
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseBooleanArray;
import org.noorganization.instalist.GlobalApplication;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.Recipe;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.modelwrappers;
/**
* The wrapper for Recipes to strike/unstrike them.
* Created by TS on 25.05.2015.
*/
public class RecipeListEntry implements IBaseListEntry {
public static final int CHECKED_PROPERTY = 0;
private Recipe mRecipe;
private boolean mChecked;
public RecipeListEntry(Recipe _Recipe) {
mRecipe = _Recipe;
}
private RecipeListEntry(Parcel _In) {
|
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
// public class GlobalApplication extends Application {
//
// private final static String LOG_TAG = GlobalApplication.class.getName();
//
// private static GlobalApplication mInstance;
// private ShoppingList mCurrentShoppingList;
//
// private boolean mBufferItemChangedMessages;
// private boolean mHandlingProductSelectedMessages;
// private List<ListItemChangedMessage> mBufferedMessages;
//
// public static GlobalApplication getInstance() {
// return mInstance;
// }
//
// public static Context getContext() {
// return getInstance().getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mInstance = this;
// EventBus.getDefault().register(this);
// mBufferedMessages = new LinkedList<>();
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// public void onEvent(ActivityStateMessage _message) {
// mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
// }
//
// public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
// mCurrentShoppingList = _selectedShoppingList.mShoppingList;
// }
//
// public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
// mBufferItemChangedMessages = !_event.mActive;
// if (!mBufferItemChangedMessages) {
// for (ListItemChangedMessage message : mBufferedMessages)
// EventBus.getDefault().post(message);
//
// mBufferedMessages.clear();
// }
// }
//
// public void onEvent(ListItemChangedMessage _message) {
// if (mBufferItemChangedMessages) {
// mBufferedMessages.add(_message);
// }
// }
//
// public void onEvent(ProductSelectMessage _message) {
// if (mCurrentShoppingList == null) {
// Toast.makeText(getContext(), R.string.abc_no_shopping_list_selected, Toast.LENGTH_SHORT).show();
// return;
// }
// if (mHandlingProductSelectedMessages) {
// Map<Product, Float> productAmounts = _message.mProducts;
// IListController controller = ControllerFactory.getListController(getContext());
// for (Product currentProduct : productAmounts.keySet()) {
// controller.addOrChangeItem(mCurrentShoppingList, currentProduct,
// productAmounts.get(currentProduct), true);
// }
// }
// }
//
// }
// Path: app/src/main/java/org/noorganization/instalist/view/modelwrappers/RecipeListEntry.java
import android.os.Parcel;
import android.os.Parcelable;
import android.util.SparseBooleanArray;
import org.noorganization.instalist.GlobalApplication;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.Recipe;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.modelwrappers;
/**
* The wrapper for Recipes to strike/unstrike them.
* Created by TS on 25.05.2015.
*/
public class RecipeListEntry implements IBaseListEntry {
public static final int CHECKED_PROPERTY = 0;
private Recipe mRecipe;
private boolean mChecked;
public RecipeListEntry(Recipe _Recipe) {
mRecipe = _Recipe;
}
private RecipeListEntry(Parcel _In) {
|
mRecipe = ControllerFactory.getRecipeController(GlobalApplication.getContext()).findById(_In.readString());
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/activity/SettingsActivity.java
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginControllerFactory.java
// public class PluginControllerFactory {
// public static IPluginController getPluginController(Context _context) {
// return PluginController.getInstance(_context);
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/fragment/settings/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment {
//
// private static final String LOG_TAG = SettingsFragment.class.getSimpleName();
//
// private LayoutInflater mInflater;
// private ViewGroup mViewContainer;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// EventBus.getDefault().register(this);
//
// // Load the preferences from an XML resource
// addPreferencesFromResource(R.xml.preferences);
// }
//
//
// @Override
// public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
//
// if (preference.getKey() != null && preference.getKey().equals("open_source_licenses")) {
// WebView view = (WebView) LayoutInflater.from(this.getActivity()).inflate(R.layout.licenses, null);
// view.loadUrl("file:///android_asset/open_source_licenses.html");
// AlertDialog mAlertDialog = new AlertDialog.Builder(this.getActivity(), R.style.Theme_AppCompat_Light_Dialog_Alert)
// .setTitle(getString(R.string.open_source_licenses))
// .setView(view)
// .setPositiveButton(android.R.string.ok, null)
// .show();
// return true;
// }
//
// return super.onPreferenceTreeClick(preferenceScreen, preference);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mInflater = inflater;
// mViewContainer = container;
// return super.onCreateView(inflater, container, savedInstanceState);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// EventBus.getDefault().unregister(this);
// }
//
// public void onEvent(final PluginFoundMessage _msg) {
// if (mInflater == null || mViewContainer == null) {
// Log.e(LOG_TAG, "onEvent: Faster than light, onCreateView was not called yet.");
// return;
// }
//
// PreferenceGroup preferenceGroup = new PreferenceCategory(mViewContainer.getContext());
// preferenceGroup.setTitle(_msg.mName);
//
//
// View prefView = preferenceGroup.getView(null, mViewContainer);
// /*prefView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = new Intent(getActivity(), _msg.mSettingsActivity);
// startActivity(intent);
// }
// });*/
// ViewGroup viewGroup = (ViewGroup) mViewContainer.getChildAt(0);
// viewGroup.addView(prefView, viewGroup.getChildCount());
//
// }
//
//
// }
|
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.implementation.PluginControllerFactory;
import org.noorganization.instalist.view.fragment.settings.SettingsFragment;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.activity;
/**
* The Activity for setting Settings.
* Created by TS on 04.07.2015.
*/
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clean_w_actionbar);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginControllerFactory.java
// public class PluginControllerFactory {
// public static IPluginController getPluginController(Context _context) {
// return PluginController.getInstance(_context);
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/fragment/settings/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment {
//
// private static final String LOG_TAG = SettingsFragment.class.getSimpleName();
//
// private LayoutInflater mInflater;
// private ViewGroup mViewContainer;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// EventBus.getDefault().register(this);
//
// // Load the preferences from an XML resource
// addPreferencesFromResource(R.xml.preferences);
// }
//
//
// @Override
// public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
//
// if (preference.getKey() != null && preference.getKey().equals("open_source_licenses")) {
// WebView view = (WebView) LayoutInflater.from(this.getActivity()).inflate(R.layout.licenses, null);
// view.loadUrl("file:///android_asset/open_source_licenses.html");
// AlertDialog mAlertDialog = new AlertDialog.Builder(this.getActivity(), R.style.Theme_AppCompat_Light_Dialog_Alert)
// .setTitle(getString(R.string.open_source_licenses))
// .setView(view)
// .setPositiveButton(android.R.string.ok, null)
// .show();
// return true;
// }
//
// return super.onPreferenceTreeClick(preferenceScreen, preference);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mInflater = inflater;
// mViewContainer = container;
// return super.onCreateView(inflater, container, savedInstanceState);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// EventBus.getDefault().unregister(this);
// }
//
// public void onEvent(final PluginFoundMessage _msg) {
// if (mInflater == null || mViewContainer == null) {
// Log.e(LOG_TAG, "onEvent: Faster than light, onCreateView was not called yet.");
// return;
// }
//
// PreferenceGroup preferenceGroup = new PreferenceCategory(mViewContainer.getContext());
// preferenceGroup.setTitle(_msg.mName);
//
//
// View prefView = preferenceGroup.getView(null, mViewContainer);
// /*prefView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = new Intent(getActivity(), _msg.mSettingsActivity);
// startActivity(intent);
// }
// });*/
// ViewGroup viewGroup = (ViewGroup) mViewContainer.getChildAt(0);
// viewGroup.addView(prefView, viewGroup.getChildCount());
//
// }
//
//
// }
// Path: app/src/main/java/org/noorganization/instalist/view/activity/SettingsActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.implementation.PluginControllerFactory;
import org.noorganization.instalist.view.fragment.settings.SettingsFragment;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.activity;
/**
* The Activity for setting Settings.
* Created by TS on 04.07.2015.
*/
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clean_w_actionbar);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
|
.replace(R.id.container, new SettingsFragment())
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/activity/SettingsActivity.java
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginControllerFactory.java
// public class PluginControllerFactory {
// public static IPluginController getPluginController(Context _context) {
// return PluginController.getInstance(_context);
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/fragment/settings/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment {
//
// private static final String LOG_TAG = SettingsFragment.class.getSimpleName();
//
// private LayoutInflater mInflater;
// private ViewGroup mViewContainer;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// EventBus.getDefault().register(this);
//
// // Load the preferences from an XML resource
// addPreferencesFromResource(R.xml.preferences);
// }
//
//
// @Override
// public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
//
// if (preference.getKey() != null && preference.getKey().equals("open_source_licenses")) {
// WebView view = (WebView) LayoutInflater.from(this.getActivity()).inflate(R.layout.licenses, null);
// view.loadUrl("file:///android_asset/open_source_licenses.html");
// AlertDialog mAlertDialog = new AlertDialog.Builder(this.getActivity(), R.style.Theme_AppCompat_Light_Dialog_Alert)
// .setTitle(getString(R.string.open_source_licenses))
// .setView(view)
// .setPositiveButton(android.R.string.ok, null)
// .show();
// return true;
// }
//
// return super.onPreferenceTreeClick(preferenceScreen, preference);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mInflater = inflater;
// mViewContainer = container;
// return super.onCreateView(inflater, container, savedInstanceState);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// EventBus.getDefault().unregister(this);
// }
//
// public void onEvent(final PluginFoundMessage _msg) {
// if (mInflater == null || mViewContainer == null) {
// Log.e(LOG_TAG, "onEvent: Faster than light, onCreateView was not called yet.");
// return;
// }
//
// PreferenceGroup preferenceGroup = new PreferenceCategory(mViewContainer.getContext());
// preferenceGroup.setTitle(_msg.mName);
//
//
// View prefView = preferenceGroup.getView(null, mViewContainer);
// /*prefView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = new Intent(getActivity(), _msg.mSettingsActivity);
// startActivity(intent);
// }
// });*/
// ViewGroup viewGroup = (ViewGroup) mViewContainer.getChildAt(0);
// viewGroup.addView(prefView, viewGroup.getChildCount());
//
// }
//
//
// }
|
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.implementation.PluginControllerFactory;
import org.noorganization.instalist.view.fragment.settings.SettingsFragment;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.activity;
/**
* The Activity for setting Settings.
* Created by TS on 04.07.2015.
*/
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clean_w_actionbar);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(R.id.container, new SettingsFragment())
.commit();
// init and setup toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/implementation/PluginControllerFactory.java
// public class PluginControllerFactory {
// public static IPluginController getPluginController(Context _context) {
// return PluginController.getInstance(_context);
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/fragment/settings/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment {
//
// private static final String LOG_TAG = SettingsFragment.class.getSimpleName();
//
// private LayoutInflater mInflater;
// private ViewGroup mViewContainer;
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// EventBus.getDefault().register(this);
//
// // Load the preferences from an XML resource
// addPreferencesFromResource(R.xml.preferences);
// }
//
//
// @Override
// public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
//
// if (preference.getKey() != null && preference.getKey().equals("open_source_licenses")) {
// WebView view = (WebView) LayoutInflater.from(this.getActivity()).inflate(R.layout.licenses, null);
// view.loadUrl("file:///android_asset/open_source_licenses.html");
// AlertDialog mAlertDialog = new AlertDialog.Builder(this.getActivity(), R.style.Theme_AppCompat_Light_Dialog_Alert)
// .setTitle(getString(R.string.open_source_licenses))
// .setView(view)
// .setPositiveButton(android.R.string.ok, null)
// .show();
// return true;
// }
//
// return super.onPreferenceTreeClick(preferenceScreen, preference);
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mInflater = inflater;
// mViewContainer = container;
// return super.onCreateView(inflater, container, savedInstanceState);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// EventBus.getDefault().unregister(this);
// }
//
// public void onEvent(final PluginFoundMessage _msg) {
// if (mInflater == null || mViewContainer == null) {
// Log.e(LOG_TAG, "onEvent: Faster than light, onCreateView was not called yet.");
// return;
// }
//
// PreferenceGroup preferenceGroup = new PreferenceCategory(mViewContainer.getContext());
// preferenceGroup.setTitle(_msg.mName);
//
//
// View prefView = preferenceGroup.getView(null, mViewContainer);
// /*prefView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = new Intent(getActivity(), _msg.mSettingsActivity);
// startActivity(intent);
// }
// });*/
// ViewGroup viewGroup = (ViewGroup) mViewContainer.getChildAt(0);
// viewGroup.addView(prefView, viewGroup.getChildCount());
//
// }
//
//
// }
// Path: app/src/main/java/org/noorganization/instalist/view/activity/SettingsActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.implementation.PluginControllerFactory;
import org.noorganization.instalist.view.fragment.settings.SettingsFragment;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.activity;
/**
* The Activity for setting Settings.
* Created by TS on 04.07.2015.
*/
public class SettingsActivity extends AppCompatActivity {
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clean_w_actionbar);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(R.id.container, new SettingsFragment())
.commit();
// init and setup toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
|
PluginControllerFactory.getPluginController(this).searchPlugins();
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/presenter/broadcast/implementation/PluginBroadcastReceiver.java
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/PluginControllerActions.java
// public class PluginControllerActions {
// public static final String ACTION_PING = "org.noorganization.instalist.action.PING_PLUGIN";
// public static final String ACTION_PONG = "org.noorganization.instalist.action.PONG_PLUGIN";
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/IPluginBroadCast.java
// public interface IPluginBroadCast {
//
// /**
// * @see IPluginBroadCast#searchPlugins()
// */
// void searchPlugins();
// }
|
import java.util.List;
import dalvik.system.DexClassLoader;
import dalvik.system.PathClassLoader;
import de.greenrobot.event.EventBus;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import org.noorganization.instalist.presenter.PluginControllerActions;
import org.noorganization.instalist.presenter.broadcast.IPluginBroadCast;
import org.noorganization.instalist.presenter.event.PluginFoundMessage;
import java.io.File;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.presenter.broadcast.implementation;
/**
* Broadcast Receiver for the Plugin infrastructure.
* Created by tinos_000 on 07.01.2016.
*/
public class PluginBroadcastReceiver extends BroadcastReceiver implements IPluginBroadCast {
static final String PLUGIN_INFO_KEY_NAME = "name";
static final String PLUGIN_INFO_KEY_SETTINGS_ACTIVITY = "settings";
static final String PLUGIN_INFO_KEY_MAIN_ACTIVITY = "main";
static final String PLUGIN_INFO_KEY_PACKAGE = "package";
private Context mContext;
/**
* Empty construtor for receive.
*/
public PluginBroadcastReceiver() {
super();
}
public PluginBroadcastReceiver(Context _context) {
super();
mContext = _context;
}
@Override
public void searchPlugins() {
|
// Path: app/src/main/java/org/noorganization/instalist/presenter/PluginControllerActions.java
// public class PluginControllerActions {
// public static final String ACTION_PING = "org.noorganization.instalist.action.PING_PLUGIN";
// public static final String ACTION_PONG = "org.noorganization.instalist.action.PONG_PLUGIN";
// }
//
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/IPluginBroadCast.java
// public interface IPluginBroadCast {
//
// /**
// * @see IPluginBroadCast#searchPlugins()
// */
// void searchPlugins();
// }
// Path: app/src/main/java/org/noorganization/instalist/presenter/broadcast/implementation/PluginBroadcastReceiver.java
import java.util.List;
import dalvik.system.DexClassLoader;
import dalvik.system.PathClassLoader;
import de.greenrobot.event.EventBus;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import org.noorganization.instalist.presenter.PluginControllerActions;
import org.noorganization.instalist.presenter.broadcast.IPluginBroadCast;
import org.noorganization.instalist.presenter.event.PluginFoundMessage;
import java.io.File;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.presenter.broadcast.implementation;
/**
* Broadcast Receiver for the Plugin infrastructure.
* Created by tinos_000 on 07.01.2016.
*/
public class PluginBroadcastReceiver extends BroadcastReceiver implements IPluginBroadCast {
static final String PLUGIN_INFO_KEY_NAME = "name";
static final String PLUGIN_INFO_KEY_SETTINGS_ACTIVITY = "settings";
static final String PLUGIN_INFO_KEY_MAIN_ACTIVITY = "main";
static final String PLUGIN_INFO_KEY_PACKAGE = "package";
private Context mContext;
/**
* Empty construtor for receive.
*/
public PluginBroadcastReceiver() {
super();
}
public PluginBroadcastReceiver(Context _context) {
super();
mContext = _context;
}
@Override
public void searchPlugins() {
|
Log.d("PluginBroadcastReceiver", "Sending " + PluginControllerActions.ACTION_PING);
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/touchlistener/sidebar/OnShoppingListLongClickListener.java
|
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
// public class GlobalApplication extends Application {
//
// private final static String LOG_TAG = GlobalApplication.class.getName();
//
// private static GlobalApplication mInstance;
// private ShoppingList mCurrentShoppingList;
//
// private boolean mBufferItemChangedMessages;
// private boolean mHandlingProductSelectedMessages;
// private List<ListItemChangedMessage> mBufferedMessages;
//
// public static GlobalApplication getInstance() {
// return mInstance;
// }
//
// public static Context getContext() {
// return getInstance().getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mInstance = this;
// EventBus.getDefault().register(this);
// mBufferedMessages = new LinkedList<>();
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// public void onEvent(ActivityStateMessage _message) {
// mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
// }
//
// public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
// mCurrentShoppingList = _selectedShoppingList.mShoppingList;
// }
//
// public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
// mBufferItemChangedMessages = !_event.mActive;
// if (!mBufferItemChangedMessages) {
// for (ListItemChangedMessage message : mBufferedMessages)
// EventBus.getDefault().post(message);
//
// mBufferedMessages.clear();
// }
// }
//
// public void onEvent(ListItemChangedMessage _message) {
// if (mBufferItemChangedMessages) {
// mBufferedMessages.add(_message);
// }
// }
//
// public void onEvent(ProductSelectMessage _message) {
// if (mCurrentShoppingList == null) {
// Toast.makeText(getContext(), R.string.abc_no_shopping_list_selected, Toast.LENGTH_SHORT).show();
// return;
// }
// if (mHandlingProductSelectedMessages) {
// Map<Product, Float> productAmounts = _message.mProducts;
// IListController controller = ControllerFactory.getListController(getContext());
// for (Product currentProduct : productAmounts.keySet()) {
// controller.addOrChangeItem(mCurrentShoppingList, currentProduct,
// productAmounts.get(currentProduct), true);
// }
// }
// }
//
// }
|
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import org.noorganization.instalist.GlobalApplication;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.ShoppingList;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.touchlistener.sidebar;
// TODO: delete?
/**
* Handles the viewchange from textview to edittext.
*/
public class OnShoppingListLongClickListener implements View.OnLongClickListener {
private String mShoppingListId;
public OnShoppingListLongClickListener(String _ShoppingListId) {
mShoppingListId = _ShoppingListId;
}
@Override
public boolean onLongClick(View _View) {
EditText editText;
ShoppingList shoppingList;
ViewSwitcher viewSwitcher;
ImageView cancelView, submitView;
cancelView = (ImageView) _View.findViewById(R.id.expandable_list_view_edit_cancel);
submitView = (ImageView) _View.findViewById(R.id.expandable_list_view_edit_submit);
viewSwitcher = (ViewSwitcher) _View.findViewById(R.id.expandable_list_view_view_switcher);
editText = (EditText) _View.findViewById(R.id.expandable_list_view_list_edit_name);
|
// Path: app/src/main/java/org/noorganization/instalist/GlobalApplication.java
// public class GlobalApplication extends Application {
//
// private final static String LOG_TAG = GlobalApplication.class.getName();
//
// private static GlobalApplication mInstance;
// private ShoppingList mCurrentShoppingList;
//
// private boolean mBufferItemChangedMessages;
// private boolean mHandlingProductSelectedMessages;
// private List<ListItemChangedMessage> mBufferedMessages;
//
// public static GlobalApplication getInstance() {
// return mInstance;
// }
//
// public static Context getContext() {
// return getInstance().getApplicationContext();
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// mInstance = this;
// EventBus.getDefault().register(this);
// mBufferedMessages = new LinkedList<>();
// }
//
// @Override
// public void onTerminate() {
// super.onTerminate();
// }
//
// public void onEvent(ActivityStateMessage _message) {
// mHandlingProductSelectedMessages = (_message.mState == ActivityStateMessage.State.RESUMED);
// }
//
// public void onEvent(ShoppingListSelectedMessage _selectedShoppingList) {
// mCurrentShoppingList = _selectedShoppingList.mShoppingList;
// }
//
// public void onEvent(ShoppingListOverviewFragmentActiveEvent _event) {
// mBufferItemChangedMessages = !_event.mActive;
// if (!mBufferItemChangedMessages) {
// for (ListItemChangedMessage message : mBufferedMessages)
// EventBus.getDefault().post(message);
//
// mBufferedMessages.clear();
// }
// }
//
// public void onEvent(ListItemChangedMessage _message) {
// if (mBufferItemChangedMessages) {
// mBufferedMessages.add(_message);
// }
// }
//
// public void onEvent(ProductSelectMessage _message) {
// if (mCurrentShoppingList == null) {
// Toast.makeText(getContext(), R.string.abc_no_shopping_list_selected, Toast.LENGTH_SHORT).show();
// return;
// }
// if (mHandlingProductSelectedMessages) {
// Map<Product, Float> productAmounts = _message.mProducts;
// IListController controller = ControllerFactory.getListController(getContext());
// for (Product currentProduct : productAmounts.keySet()) {
// controller.addOrChangeItem(mCurrentShoppingList, currentProduct,
// productAmounts.get(currentProduct), true);
// }
// }
// }
//
// }
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/sidebar/OnShoppingListLongClickListener.java
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import org.noorganization.instalist.GlobalApplication;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.ShoppingList;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.touchlistener.sidebar;
// TODO: delete?
/**
* Handles the viewchange from textview to edittext.
*/
public class OnShoppingListLongClickListener implements View.OnLongClickListener {
private String mShoppingListId;
public OnShoppingListLongClickListener(String _ShoppingListId) {
mShoppingListId = _ShoppingListId;
}
@Override
public boolean onLongClick(View _View) {
EditText editText;
ShoppingList shoppingList;
ViewSwitcher viewSwitcher;
ImageView cancelView, submitView;
cancelView = (ImageView) _View.findViewById(R.id.expandable_list_view_edit_cancel);
submitView = (ImageView) _View.findViewById(R.id.expandable_list_view_edit_submit);
viewSwitcher = (ViewSwitcher) _View.findViewById(R.id.expandable_list_view_view_switcher);
editText = (EditText) _View.findViewById(R.id.expandable_list_view_list_edit_name);
|
shoppingList = ControllerFactory.getListController(GlobalApplication.getContext()).getListById(mShoppingListId);
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/interfaces/IShoppingListEntryAction.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/modelwrappers/ListEntryItemWrapper.java
// public class ListEntryItemWrapper {
//
// /**
// * Flag that holds the current actionmode of an item. It should not hold multiple actions at once,
// * it can but do not missuse it!
// */
// private int mActionMode;
//
// /**
// * The possible Action mode codes of ListEntry.
// */
// public final static class ACTION_MODE {
//
// /**
// * The code that indicates that this entry is in normal mode.
// */
// public final static int NORMAL_MODE = 0x00000001;
//
// /**
// * The code that indicates that this entry is in edit mode.
// */
// public final static int EDIT_MODE = 0x00000002;
//
// /**
// * The code that indicates that this entry is in select mode.
// */
// public final static int SELECT_MODE = 0x00000004;
// }
//
// /**
// * Reference to the @Link{ListEntry]
// */
// private ListEntry mListEntry;
//
// /**
// * Flag if @Link{ListEntry} is selected.
// */
// private boolean mEditMode;
//
// /**
// * Flag if current @Link{ListEntry}
// */
// private boolean mSelected;
//
//
// public ListEntryItemWrapper(ListEntry _ListEntry){
// mListEntry = _ListEntry;
// mActionMode = ACTION_MODE.NORMAL_MODE;
// }
//
// /**
// * Getter for @Link{ListEntry].}
// * @return The @Link{ListEntry}.
// */
// public ListEntry getListEntry() {
// return mListEntry;
// }
//
//
// /**
// * Get the current Mode of this ListItem. Therefore see @see{ACTION_MODE}.
// * @return the current Action Mode of this ListItem.
// */
// public int getMode(){
// return mActionMode;
// }
// /**
// * Checks if entity is currently in EditMode.
// * @return true, if in Edit Mode, else false.
// */
// public boolean isEditMode() {
// return mActionMode == ACTION_MODE.EDIT_MODE;
// }
//
// /**
// * Setter EditMode.
// * @param _EditMode true for EditMode, false for normal Mode.
// */
// public void setEditMode(boolean _EditMode) {
// mActionMode = ACTION_MODE.EDIT_MODE;
// }
//
// /**
// * Checks if current ListItem is selected.
// * @return true if selected, else false.
// */
// public boolean isSelected() {
// return mActionMode == ACTION_MODE.SELECT_MODE;
// }
//
// /**
// * Setter for Selected value.
// * @param _Selected true for selected, else false.
// */
// public void setSelected(boolean _Selected) {
// mActionMode = ACTION_MODE.SELECT_MODE;
// }
//
// public void resetModeToNormalView(){
// mActionMode = ACTION_MODE.NORMAL_MODE;
// }
// }
|
import org.noorganization.instalist.model.ListEntry;
import org.noorganization.instalist.view.modelwrappers.ListEntryItemWrapper;
import java.util.Comparator;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.interfaces;
/**
* Created by TS on 09.07.2015.
*/
public interface IShoppingListEntryAction {
/**
* Adds the given ListEntry to the adapter.
* @param _ListEntryId the Id of the ListEntry to add.
*/
void addListEntry(String _ListEntryId);
/**
* Removes the ListEntry corresponding to the given Id.
* @param _ListEntryId The id of the ListEntry that should be removed.
*/
void removeListEntry(String _ListEntryId);
/**
* Updates the given ListEntry corresponding to the given Id.
* @param _ListEntry The Id of the ListEntry to update.
*/
void updateListEntry(ListEntry _ListEntry);
/**
* Resets the view back to normal view mode. So one unified view will be displayed.
*/
void resetEditModeView();
/**
* The Entry that was choosed to be edited.
*
* @param _Position position of the selected list.
*/
void setToEditMode(int _Position);
/**
* Sorts the entries by the given Comparator.
* @param _Comparator the Comparator.
*/
|
// Path: app/src/main/java/org/noorganization/instalist/view/modelwrappers/ListEntryItemWrapper.java
// public class ListEntryItemWrapper {
//
// /**
// * Flag that holds the current actionmode of an item. It should not hold multiple actions at once,
// * it can but do not missuse it!
// */
// private int mActionMode;
//
// /**
// * The possible Action mode codes of ListEntry.
// */
// public final static class ACTION_MODE {
//
// /**
// * The code that indicates that this entry is in normal mode.
// */
// public final static int NORMAL_MODE = 0x00000001;
//
// /**
// * The code that indicates that this entry is in edit mode.
// */
// public final static int EDIT_MODE = 0x00000002;
//
// /**
// * The code that indicates that this entry is in select mode.
// */
// public final static int SELECT_MODE = 0x00000004;
// }
//
// /**
// * Reference to the @Link{ListEntry]
// */
// private ListEntry mListEntry;
//
// /**
// * Flag if @Link{ListEntry} is selected.
// */
// private boolean mEditMode;
//
// /**
// * Flag if current @Link{ListEntry}
// */
// private boolean mSelected;
//
//
// public ListEntryItemWrapper(ListEntry _ListEntry){
// mListEntry = _ListEntry;
// mActionMode = ACTION_MODE.NORMAL_MODE;
// }
//
// /**
// * Getter for @Link{ListEntry].}
// * @return The @Link{ListEntry}.
// */
// public ListEntry getListEntry() {
// return mListEntry;
// }
//
//
// /**
// * Get the current Mode of this ListItem. Therefore see @see{ACTION_MODE}.
// * @return the current Action Mode of this ListItem.
// */
// public int getMode(){
// return mActionMode;
// }
// /**
// * Checks if entity is currently in EditMode.
// * @return true, if in Edit Mode, else false.
// */
// public boolean isEditMode() {
// return mActionMode == ACTION_MODE.EDIT_MODE;
// }
//
// /**
// * Setter EditMode.
// * @param _EditMode true for EditMode, false for normal Mode.
// */
// public void setEditMode(boolean _EditMode) {
// mActionMode = ACTION_MODE.EDIT_MODE;
// }
//
// /**
// * Checks if current ListItem is selected.
// * @return true if selected, else false.
// */
// public boolean isSelected() {
// return mActionMode == ACTION_MODE.SELECT_MODE;
// }
//
// /**
// * Setter for Selected value.
// * @param _Selected true for selected, else false.
// */
// public void setSelected(boolean _Selected) {
// mActionMode = ACTION_MODE.SELECT_MODE;
// }
//
// public void resetModeToNormalView(){
// mActionMode = ACTION_MODE.NORMAL_MODE;
// }
// }
// Path: app/src/main/java/org/noorganization/instalist/view/interfaces/IShoppingListEntryAction.java
import org.noorganization.instalist.model.ListEntry;
import org.noorganization.instalist.view.modelwrappers.ListEntryItemWrapper;
import java.util.Comparator;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.interfaces;
/**
* Created by TS on 09.07.2015.
*/
public interface IShoppingListEntryAction {
/**
* Adds the given ListEntry to the adapter.
* @param _ListEntryId the Id of the ListEntry to add.
*/
void addListEntry(String _ListEntryId);
/**
* Removes the ListEntry corresponding to the given Id.
* @param _ListEntryId The id of the ListEntry that should be removed.
*/
void removeListEntry(String _ListEntryId);
/**
* Updates the given ListEntry corresponding to the given Id.
* @param _ListEntry The Id of the ListEntry to update.
*/
void updateListEntry(ListEntry _ListEntry);
/**
* Resets the view back to normal view mode. So one unified view will be displayed.
*/
void resetEditModeView();
/**
* The Entry that was choosed to be edited.
*
* @param _Position position of the selected list.
*/
void setToEditMode(int _Position);
/**
* Sorts the entries by the given Comparator.
* @param _Comparator the Comparator.
*/
|
void sortByComparator(Comparator<ListEntryItemWrapper> _Comparator);
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/listadapter/PlainShoppingListOverviewAdapter.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/IOnShoppingListClickListenerEvents.java
// public interface IOnShoppingListClickListenerEvents {
//
// /**
// * Called when a ShoppingList was clicked.
// * @param _ShoppingList the ShoppingList object that was clicked.
// */
// void onShoppingListClicked(ShoppingList _ShoppingList);
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/OnShoppingListClickListener.java
// public class OnShoppingListClickListener implements View.OnClickListener {
//
// private ShoppingList mShoppingList;
// private IOnShoppingListClickListenerEvents mOnShoppingListClickEvent;
//
// /**
// * Constructor of OnShoppingListClickListener.
// * @param _IOnShoppingListClickEvent The interface for handling ShoppingList clicks.
// * @param _ShoppingList The ShoppingList that is handled when a click on it occurs.
// */
// public OnShoppingListClickListener(IOnShoppingListClickListenerEvents _IOnShoppingListClickEvent, ShoppingList _ShoppingList){
// mShoppingList = _ShoppingList;
// mOnShoppingListClickEvent = _IOnShoppingListClickEvent;
// }
//
// @Override
// public void onClick(View v) {
// mOnShoppingListClickEvent.onShoppingListClicked(mShoppingList);
// //EventBus.getDefault().post(new ShoppingListSelectedMessage(mShoppingList));
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/interfaces/IShoppingListAdapter.java
// public interface IShoppingListAdapter {
// /**
// * Adds the given ShoppingList to the adapter.
// * @param _ShoppingList the ShoppingList to be added.
// */
// void addList(ShoppingList _ShoppingList);
//
// /**
// * Updates the given ShoppingList in Adapter.
// * @param _ShoppingList the ShoppingList to be updated.
// */
// void updateList(ShoppingList _ShoppingList);
//
// /**
// * Removes the given ShoppingList from the adapter.
// * @param _ShoppingList The ShoppingList to remove.
// */
// void removeList(ShoppingList _ShoppingList);
// }
|
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.view.touchlistener.IOnShoppingListClickListenerEvents;
import org.noorganization.instalist.view.touchlistener.OnShoppingListClickListener;
import org.noorganization.instalist.view.interfaces.IShoppingListAdapter;
|
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.listadapter;
/**
* The adapter handles the display of a single list of shoppinglists in the sidebar.
* Should only be used when there is no Category.
* Created by TS on 25.04.2015.
*/
public class PlainShoppingListOverviewAdapter extends ArrayAdapter<ShoppingList> implements IShoppingListAdapter{
private static String LOG_TAG = PlainShoppingListOverviewAdapter.class.getName();
private final List<ShoppingList> mShoppingLists;
private final Context mContext;
|
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/IOnShoppingListClickListenerEvents.java
// public interface IOnShoppingListClickListenerEvents {
//
// /**
// * Called when a ShoppingList was clicked.
// * @param _ShoppingList the ShoppingList object that was clicked.
// */
// void onShoppingListClicked(ShoppingList _ShoppingList);
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/OnShoppingListClickListener.java
// public class OnShoppingListClickListener implements View.OnClickListener {
//
// private ShoppingList mShoppingList;
// private IOnShoppingListClickListenerEvents mOnShoppingListClickEvent;
//
// /**
// * Constructor of OnShoppingListClickListener.
// * @param _IOnShoppingListClickEvent The interface for handling ShoppingList clicks.
// * @param _ShoppingList The ShoppingList that is handled when a click on it occurs.
// */
// public OnShoppingListClickListener(IOnShoppingListClickListenerEvents _IOnShoppingListClickEvent, ShoppingList _ShoppingList){
// mShoppingList = _ShoppingList;
// mOnShoppingListClickEvent = _IOnShoppingListClickEvent;
// }
//
// @Override
// public void onClick(View v) {
// mOnShoppingListClickEvent.onShoppingListClicked(mShoppingList);
// //EventBus.getDefault().post(new ShoppingListSelectedMessage(mShoppingList));
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/interfaces/IShoppingListAdapter.java
// public interface IShoppingListAdapter {
// /**
// * Adds the given ShoppingList to the adapter.
// * @param _ShoppingList the ShoppingList to be added.
// */
// void addList(ShoppingList _ShoppingList);
//
// /**
// * Updates the given ShoppingList in Adapter.
// * @param _ShoppingList the ShoppingList to be updated.
// */
// void updateList(ShoppingList _ShoppingList);
//
// /**
// * Removes the given ShoppingList from the adapter.
// * @param _ShoppingList The ShoppingList to remove.
// */
// void removeList(ShoppingList _ShoppingList);
// }
// Path: app/src/main/java/org/noorganization/instalist/view/listadapter/PlainShoppingListOverviewAdapter.java
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.view.touchlistener.IOnShoppingListClickListenerEvents;
import org.noorganization.instalist.view.touchlistener.OnShoppingListClickListener;
import org.noorganization.instalist.view.interfaces.IShoppingListAdapter;
/*
* Copyright 2016 Tino Siegmund, Michael Wodniok
*
* 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 org.noorganization.instalist.view.listadapter;
/**
* The adapter handles the display of a single list of shoppinglists in the sidebar.
* Should only be used when there is no Category.
* Created by TS on 25.04.2015.
*/
public class PlainShoppingListOverviewAdapter extends ArrayAdapter<ShoppingList> implements IShoppingListAdapter{
private static String LOG_TAG = PlainShoppingListOverviewAdapter.class.getName();
private final List<ShoppingList> mShoppingLists;
private final Context mContext;
|
private IOnShoppingListClickListenerEvents mIOnShoppingListClickEvents;
|
InstaList/instalist-android
|
app/src/main/java/org/noorganization/instalist/view/listadapter/PlainShoppingListOverviewAdapter.java
|
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/IOnShoppingListClickListenerEvents.java
// public interface IOnShoppingListClickListenerEvents {
//
// /**
// * Called when a ShoppingList was clicked.
// * @param _ShoppingList the ShoppingList object that was clicked.
// */
// void onShoppingListClicked(ShoppingList _ShoppingList);
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/OnShoppingListClickListener.java
// public class OnShoppingListClickListener implements View.OnClickListener {
//
// private ShoppingList mShoppingList;
// private IOnShoppingListClickListenerEvents mOnShoppingListClickEvent;
//
// /**
// * Constructor of OnShoppingListClickListener.
// * @param _IOnShoppingListClickEvent The interface for handling ShoppingList clicks.
// * @param _ShoppingList The ShoppingList that is handled when a click on it occurs.
// */
// public OnShoppingListClickListener(IOnShoppingListClickListenerEvents _IOnShoppingListClickEvent, ShoppingList _ShoppingList){
// mShoppingList = _ShoppingList;
// mOnShoppingListClickEvent = _IOnShoppingListClickEvent;
// }
//
// @Override
// public void onClick(View v) {
// mOnShoppingListClickEvent.onShoppingListClicked(mShoppingList);
// //EventBus.getDefault().post(new ShoppingListSelectedMessage(mShoppingList));
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/interfaces/IShoppingListAdapter.java
// public interface IShoppingListAdapter {
// /**
// * Adds the given ShoppingList to the adapter.
// * @param _ShoppingList the ShoppingList to be added.
// */
// void addList(ShoppingList _ShoppingList);
//
// /**
// * Updates the given ShoppingList in Adapter.
// * @param _ShoppingList the ShoppingList to be updated.
// */
// void updateList(ShoppingList _ShoppingList);
//
// /**
// * Removes the given ShoppingList from the adapter.
// * @param _ShoppingList The ShoppingList to remove.
// */
// void removeList(ShoppingList _ShoppingList);
// }
|
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.view.touchlistener.IOnShoppingListClickListenerEvents;
import org.noorganization.instalist.view.touchlistener.OnShoppingListClickListener;
import org.noorganization.instalist.view.interfaces.IShoppingListAdapter;
|
private static class ViewHolder {
TextView mtvListName;
TextView mtvListItemCount;
}
@Override
public View getView(int _Position, View _ConvertView, ViewGroup _Parent) {
View shoppingListNamesView = null;
if (_ConvertView == null) {
ViewHolder holder = new ViewHolder();
LayoutInflater shoppingListNamesInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
shoppingListNamesView = shoppingListNamesInflater.inflate(R.layout.expandable_list_view_list_entry, null);
holder.mtvListName = (TextView) shoppingListNamesView.findViewById(R.id.expandable_list_view_list_name);
holder.mtvListItemCount = (TextView) shoppingListNamesView.findViewById(R.id.expandable_list_view_list_entries);
shoppingListNamesView.setLongClickable(true);
shoppingListNamesView.setTag(holder);
} else {
shoppingListNamesView = _ConvertView;
}
ViewHolder holder = (ViewHolder) shoppingListNamesView.getTag();
ShoppingList shoppingList = getItem(_Position);
String listName = shoppingList.mName;
holder.mtvListName.setText(listName);
holder.mtvListName.setSelected(true);
holder.mtvListItemCount.setText(String.valueOf(mListController.getEntryCount(shoppingList)));
shoppingListNamesView.setOnClickListener(
|
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/IOnShoppingListClickListenerEvents.java
// public interface IOnShoppingListClickListenerEvents {
//
// /**
// * Called when a ShoppingList was clicked.
// * @param _ShoppingList the ShoppingList object that was clicked.
// */
// void onShoppingListClicked(ShoppingList _ShoppingList);
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/touchlistener/OnShoppingListClickListener.java
// public class OnShoppingListClickListener implements View.OnClickListener {
//
// private ShoppingList mShoppingList;
// private IOnShoppingListClickListenerEvents mOnShoppingListClickEvent;
//
// /**
// * Constructor of OnShoppingListClickListener.
// * @param _IOnShoppingListClickEvent The interface for handling ShoppingList clicks.
// * @param _ShoppingList The ShoppingList that is handled when a click on it occurs.
// */
// public OnShoppingListClickListener(IOnShoppingListClickListenerEvents _IOnShoppingListClickEvent, ShoppingList _ShoppingList){
// mShoppingList = _ShoppingList;
// mOnShoppingListClickEvent = _IOnShoppingListClickEvent;
// }
//
// @Override
// public void onClick(View v) {
// mOnShoppingListClickEvent.onShoppingListClicked(mShoppingList);
// //EventBus.getDefault().post(new ShoppingListSelectedMessage(mShoppingList));
// }
// }
//
// Path: app/src/main/java/org/noorganization/instalist/view/interfaces/IShoppingListAdapter.java
// public interface IShoppingListAdapter {
// /**
// * Adds the given ShoppingList to the adapter.
// * @param _ShoppingList the ShoppingList to be added.
// */
// void addList(ShoppingList _ShoppingList);
//
// /**
// * Updates the given ShoppingList in Adapter.
// * @param _ShoppingList the ShoppingList to be updated.
// */
// void updateList(ShoppingList _ShoppingList);
//
// /**
// * Removes the given ShoppingList from the adapter.
// * @param _ShoppingList The ShoppingList to remove.
// */
// void removeList(ShoppingList _ShoppingList);
// }
// Path: app/src/main/java/org/noorganization/instalist/view/listadapter/PlainShoppingListOverviewAdapter.java
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.noorganization.instalist.R;
import org.noorganization.instalist.presenter.IListController;
import org.noorganization.instalist.presenter.implementation.ControllerFactory;
import org.noorganization.instalist.model.ShoppingList;
import org.noorganization.instalist.view.touchlistener.IOnShoppingListClickListenerEvents;
import org.noorganization.instalist.view.touchlistener.OnShoppingListClickListener;
import org.noorganization.instalist.view.interfaces.IShoppingListAdapter;
private static class ViewHolder {
TextView mtvListName;
TextView mtvListItemCount;
}
@Override
public View getView(int _Position, View _ConvertView, ViewGroup _Parent) {
View shoppingListNamesView = null;
if (_ConvertView == null) {
ViewHolder holder = new ViewHolder();
LayoutInflater shoppingListNamesInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
shoppingListNamesView = shoppingListNamesInflater.inflate(R.layout.expandable_list_view_list_entry, null);
holder.mtvListName = (TextView) shoppingListNamesView.findViewById(R.id.expandable_list_view_list_name);
holder.mtvListItemCount = (TextView) shoppingListNamesView.findViewById(R.id.expandable_list_view_list_entries);
shoppingListNamesView.setLongClickable(true);
shoppingListNamesView.setTag(holder);
} else {
shoppingListNamesView = _ConvertView;
}
ViewHolder holder = (ViewHolder) shoppingListNamesView.getTag();
ShoppingList shoppingList = getItem(_Position);
String listName = shoppingList.mName;
holder.mtvListName.setText(listName);
holder.mtvListName.setSelected(true);
holder.mtvListItemCount.setText(String.valueOf(mListController.getEntryCount(shoppingList)));
shoppingListNamesView.setOnClickListener(
|
new OnShoppingListClickListener(mIOnShoppingListClickEvents, mShoppingLists.get(_Position)));
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
|
// Path: src/com/noticeditorteam/noticeditor/io/IOUtil.java
// public final class IOUtil {
//
// private static final int FILENAME_LIMIT = 60;
//
// public static String readContent(File file) throws IOException {
// return stringFromStream(new FileInputStream(file));
// }
//
// public static void writeContent(File file, String content) throws IOException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// writer.write(content);
// }
// }
//
// public static void writeContent(File file, byte[] content) throws IOException {
// try (OutputStream os = new FileOutputStream(file)) {
// os.write(content);
// }
// }
//
// public static void writeJson(File file, JSONObject json) throws IOException, JSONException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// json.write(writer);
// }
// }
//
// public static void removeDirectory(File directory) {
// if (directory.isFile() || !directory.exists())
// return;
// removeDirectoryHelper(directory);
// }
//
// private static void removeDirectoryHelper(File file) {
// if (file.isDirectory()) {
// for (File f : file.listFiles()) {
// removeDirectoryHelper(f);
// }
// }
// file.delete();
// }
//
// public static String sanitizeFilename(String name) {
// if (name == null || name.isEmpty())
// return "empty";
//
// String newName = name;
// // Quick transliteration
// newName = Junidecode.unidecode(newName);
// // Convert non-ascii chars to char code
// try {
// newName = URLEncoder.encode(newName, "UTF-8");
// } catch (UnsupportedEncodingException ex) {
// }
// // Allow only english chars, numbers and some specific symbols
// newName = newName.toLowerCase().replaceAll("[^a-z0-9._\\(\\)]", "_");
// // Limit filename length
// if (newName.length() > FILENAME_LIMIT) {
// newName = newName.substring(0, FILENAME_LIMIT);
// }
// return newName;
// }
//
// public static InputStream toStream(String content) throws IOException {
// return toStream(content, "UTF-8");
// }
//
// public static InputStream toStream(String content, String charset) throws IOException {
// return new ByteArrayInputStream(content.getBytes(charset));
// }
//
// public static String stringFromStream(InputStream stream) throws IOException {
// return stringFromStream(stream, "UTF-8");
// }
//
// public static String stringFromStream(InputStream stream, String charset) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// copy(stream, result);
// stream.close();
// return result.toString("UTF-8");
// }
//
// public static boolean isResourceExists(String resource) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return is != null;
// } catch (IOException ioe) {
// return false;
// }
// }
//
// public static List<String> linesFromResource(String resource) {
// return linesFromResource(resource, "UTF-8");
// }
//
// public static List<String> linesFromResource(String resource, String charset) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return linesFromStream(is, charset);
// } catch (IOException ioe) {
// return Collections.emptyList();
// }
// }
//
// public static List<String> linesFromStream(InputStream stream) throws IOException {
// return linesFromStream(stream, "UTF-8");
// }
//
// public static List<String> linesFromStream(InputStream stream, String charset) throws IOException {
// if (stream == null) return Collections.emptyList();
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
// return reader.lines().collect(Collectors.toList());
// }
// }
//
// public static byte[] download(String url) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// try (InputStream is = new URL(url).openStream()) {
// copy(is, result);
// }
// return result.toByteArray();
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// final int bufferSize = 8192;
// final byte[] buffer = new byte[bufferSize];
// int readed;
// while ((readed = is.read(buffer, 0, bufferSize)) != -1) {
// os.write(buffer, 0, readed);
// }
// }
// }
|
import com.noticeditorteam.noticeditor.io.IOUtil;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.jsoup.safety.Whitelist;
|
package com.noticeditorteam.noticeditor.io.importers;
/**
* Load page from Internet, insert scripts, styles, images directly to html.
*
* @author Naik
*/
public class WebImporter extends HtmlImporter {
private final Map<String, String> cache = new HashMap<>();
@Override
protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
String html;
if (cache.containsKey(url)) {
html = cache.get(url);
} else {
|
// Path: src/com/noticeditorteam/noticeditor/io/IOUtil.java
// public final class IOUtil {
//
// private static final int FILENAME_LIMIT = 60;
//
// public static String readContent(File file) throws IOException {
// return stringFromStream(new FileInputStream(file));
// }
//
// public static void writeContent(File file, String content) throws IOException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// writer.write(content);
// }
// }
//
// public static void writeContent(File file, byte[] content) throws IOException {
// try (OutputStream os = new FileOutputStream(file)) {
// os.write(content);
// }
// }
//
// public static void writeJson(File file, JSONObject json) throws IOException, JSONException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// json.write(writer);
// }
// }
//
// public static void removeDirectory(File directory) {
// if (directory.isFile() || !directory.exists())
// return;
// removeDirectoryHelper(directory);
// }
//
// private static void removeDirectoryHelper(File file) {
// if (file.isDirectory()) {
// for (File f : file.listFiles()) {
// removeDirectoryHelper(f);
// }
// }
// file.delete();
// }
//
// public static String sanitizeFilename(String name) {
// if (name == null || name.isEmpty())
// return "empty";
//
// String newName = name;
// // Quick transliteration
// newName = Junidecode.unidecode(newName);
// // Convert non-ascii chars to char code
// try {
// newName = URLEncoder.encode(newName, "UTF-8");
// } catch (UnsupportedEncodingException ex) {
// }
// // Allow only english chars, numbers and some specific symbols
// newName = newName.toLowerCase().replaceAll("[^a-z0-9._\\(\\)]", "_");
// // Limit filename length
// if (newName.length() > FILENAME_LIMIT) {
// newName = newName.substring(0, FILENAME_LIMIT);
// }
// return newName;
// }
//
// public static InputStream toStream(String content) throws IOException {
// return toStream(content, "UTF-8");
// }
//
// public static InputStream toStream(String content, String charset) throws IOException {
// return new ByteArrayInputStream(content.getBytes(charset));
// }
//
// public static String stringFromStream(InputStream stream) throws IOException {
// return stringFromStream(stream, "UTF-8");
// }
//
// public static String stringFromStream(InputStream stream, String charset) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// copy(stream, result);
// stream.close();
// return result.toString("UTF-8");
// }
//
// public static boolean isResourceExists(String resource) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return is != null;
// } catch (IOException ioe) {
// return false;
// }
// }
//
// public static List<String> linesFromResource(String resource) {
// return linesFromResource(resource, "UTF-8");
// }
//
// public static List<String> linesFromResource(String resource, String charset) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return linesFromStream(is, charset);
// } catch (IOException ioe) {
// return Collections.emptyList();
// }
// }
//
// public static List<String> linesFromStream(InputStream stream) throws IOException {
// return linesFromStream(stream, "UTF-8");
// }
//
// public static List<String> linesFromStream(InputStream stream, String charset) throws IOException {
// if (stream == null) return Collections.emptyList();
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
// return reader.lines().collect(Collectors.toList());
// }
// }
//
// public static byte[] download(String url) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// try (InputStream is = new URL(url).openStream()) {
// copy(is, result);
// }
// return result.toByteArray();
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// final int bufferSize = 8192;
// final byte[] buffer = new byte[bufferSize];
// int readed;
// while ((readed = is.read(buffer, 0, bufferSize)) != -1) {
// os.write(buffer, 0, readed);
// }
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
import com.noticeditorteam.noticeditor.io.IOUtil;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.jsoup.safety.Whitelist;
package com.noticeditorteam.noticeditor.io.importers;
/**
* Load page from Internet, insert scripts, styles, images directly to html.
*
* @author Naik
*/
public class WebImporter extends HtmlImporter {
private final Map<String, String> cache = new HashMap<>();
@Override
protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
String html;
if (cache.containsKey(url)) {
html = cache.get(url);
} else {
|
html = IOUtil.stringFromStream(new URL(url).openStream());
|
NoticEditorTeam/NoticEditor
|
test/com/noticeditorteam/noticeditor/model/NoticeTreeItemBenchmarksTest.java
|
// Path: src/com/noticeditorteam/noticeditor/io/JsonFormat.java
// public class JsonFormat {
//
// public static JsonFormat with(File file) {
// return new JsonFormat(file);
// }
//
// private final File file;
//
// private JsonFormat(File file) {
// this.file = file;
// }
//
// public NoticeTree importDocument() throws IOException, JSONException {
// JSONObject json = new JSONObject(IOUtil.readContent(file));
//
// if (json.has(KEY_STATUSINFO)) {
// JSONArray statusList = json.getJSONArray(KEY_STATUSINFO);
// final int length = statusList.length();
// if (length > 0) {
// NoticeStatusList.clear();
// }
// for (int i = 0; i < length; i++) {
// JSONObject obj = (JSONObject) statusList.get(i);
// String name = obj.getString("name");
// int code = obj.getInt("code");
// NoticeStatusList.add(name, code);
// }
// } else {
// NoticeStatusList.restore();
// }
// return new NoticeTree(jsonToTree(json));
// }
//
// private NoticeTreeItem jsonToTree(JSONObject json) throws JSONException {
// NoticeTreeItem item = new NoticeTreeItem(json.getString(KEY_TITLE), json.optString(KEY_CONTENT, null),
// json.optInt(KEY_STATUS, NoticeItem.STATUS_NORMAL));
// if (json.has(KEY_ATTACHMENTS)) {
// Attachments attachments = readAttachments(json.getJSONArray(KEY_ATTACHMENTS));
// item.setAttachments(attachments);
// }
// JSONArray arr = json.getJSONArray(KEY_CHILDREN);
// for (int i = 0; i < arr.length(); i++) {
// item.addChild(jsonToTree(arr.getJSONObject(i)));
// }
// return item;
// }
//
// private Attachments readAttachments(JSONArray jsonAttachments) throws JSONException {
// Attachments attachments = new Attachments();
// final int length = jsonAttachments.length();
// for (int i = 0; i < length; i++) {
// JSONObject jsonAttachment = jsonAttachments.getJSONObject(i);
// Attachment attachment = new Attachment(
// jsonAttachment.getString(KEY_ATTACHMENT_NAME),
// Base64.getDecoder().decode(jsonAttachment.getString(KEY_ATTACHMENT_DATA)));
// attachments.add(attachment);
// }
// return attachments;
// }
//
// public void export(NoticeTree tree) throws JSONException, IOException {
// if (file.exists()) {
// file.delete();
// }
// IOUtil.writeJson(file, export(tree.getRoot()));
// }
//
// public JSONObject export(NoticeTreeItem root) throws JSONException {
// JSONObject json = new JSONObject();
// treeToJson(root, json);
//
// json.put(KEY_STATUSINFO, NoticeStatusList.asObservable());
//
// return json;
// }
//
// private void treeToJson(NoticeTreeItem item, JSONObject json) throws JSONException {
// json.put(KEY_TITLE, item.getTitle());
// JSONArray childs = new JSONArray();
// if (item.isBranch()) {
// for (TreeItem<NoticeItem> object : item.getInternalChildren()) {
// NoticeTreeItem child = (NoticeTreeItem) object;
// JSONObject entry = new JSONObject();
// treeToJson(child, entry);
// childs.put(entry);
// }
// } else {
// json.put(KEY_STATUS, item.getStatus());
// json.put(KEY_CONTENT, item.getContent());
// JSONArray jsonAttachments = writeAttachments(item.getAttachments());
// json.put(KEY_ATTACHMENTS, jsonAttachments);
// }
// json.put(KEY_CHILDREN, childs);
// }
//
// private JSONArray writeAttachments(Attachments attachments) throws JSONException {
// final JSONArray jsonAttachments = new JSONArray();
// for (Attachment attachment : attachments) {
// final JSONObject jsonAttachment = new JSONObject();
// jsonAttachment.put(KEY_ATTACHMENT_NAME, attachment.getName());
// jsonAttachment.put(KEY_ATTACHMENT_DATA, attachment.getDataAsBase64());
// jsonAttachments.put(jsonAttachment);
// }
// return jsonAttachments;
// }
//
// }
|
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;
import com.noticeditorteam.noticeditor.io.JsonFormat;
import org.json.JSONException;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
|
package com.noticeditorteam.noticeditor.model;
public class NoticeTreeItemBenchmarksTest {
@Rule
public TestRule benchmarkRun = new BenchmarkRule();
private static final int NESTING_LEVEL = 6000;
private static NoticeTreeItem root;
@BeforeClass
public static void beforeClass() {
root = new NoticeTreeItem("root");
NoticeTreeItem branch = root;
for (int i = 0; i < NESTING_LEVEL; i++) {
NoticeTreeItem node = new NoticeTreeItem("branch " + i);
branch.addChild(node);
branch = node;
}
}
@BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 1)
@Ignore
@Test
public void testJsonExport() throws JSONException {
|
// Path: src/com/noticeditorteam/noticeditor/io/JsonFormat.java
// public class JsonFormat {
//
// public static JsonFormat with(File file) {
// return new JsonFormat(file);
// }
//
// private final File file;
//
// private JsonFormat(File file) {
// this.file = file;
// }
//
// public NoticeTree importDocument() throws IOException, JSONException {
// JSONObject json = new JSONObject(IOUtil.readContent(file));
//
// if (json.has(KEY_STATUSINFO)) {
// JSONArray statusList = json.getJSONArray(KEY_STATUSINFO);
// final int length = statusList.length();
// if (length > 0) {
// NoticeStatusList.clear();
// }
// for (int i = 0; i < length; i++) {
// JSONObject obj = (JSONObject) statusList.get(i);
// String name = obj.getString("name");
// int code = obj.getInt("code");
// NoticeStatusList.add(name, code);
// }
// } else {
// NoticeStatusList.restore();
// }
// return new NoticeTree(jsonToTree(json));
// }
//
// private NoticeTreeItem jsonToTree(JSONObject json) throws JSONException {
// NoticeTreeItem item = new NoticeTreeItem(json.getString(KEY_TITLE), json.optString(KEY_CONTENT, null),
// json.optInt(KEY_STATUS, NoticeItem.STATUS_NORMAL));
// if (json.has(KEY_ATTACHMENTS)) {
// Attachments attachments = readAttachments(json.getJSONArray(KEY_ATTACHMENTS));
// item.setAttachments(attachments);
// }
// JSONArray arr = json.getJSONArray(KEY_CHILDREN);
// for (int i = 0; i < arr.length(); i++) {
// item.addChild(jsonToTree(arr.getJSONObject(i)));
// }
// return item;
// }
//
// private Attachments readAttachments(JSONArray jsonAttachments) throws JSONException {
// Attachments attachments = new Attachments();
// final int length = jsonAttachments.length();
// for (int i = 0; i < length; i++) {
// JSONObject jsonAttachment = jsonAttachments.getJSONObject(i);
// Attachment attachment = new Attachment(
// jsonAttachment.getString(KEY_ATTACHMENT_NAME),
// Base64.getDecoder().decode(jsonAttachment.getString(KEY_ATTACHMENT_DATA)));
// attachments.add(attachment);
// }
// return attachments;
// }
//
// public void export(NoticeTree tree) throws JSONException, IOException {
// if (file.exists()) {
// file.delete();
// }
// IOUtil.writeJson(file, export(tree.getRoot()));
// }
//
// public JSONObject export(NoticeTreeItem root) throws JSONException {
// JSONObject json = new JSONObject();
// treeToJson(root, json);
//
// json.put(KEY_STATUSINFO, NoticeStatusList.asObservable());
//
// return json;
// }
//
// private void treeToJson(NoticeTreeItem item, JSONObject json) throws JSONException {
// json.put(KEY_TITLE, item.getTitle());
// JSONArray childs = new JSONArray();
// if (item.isBranch()) {
// for (TreeItem<NoticeItem> object : item.getInternalChildren()) {
// NoticeTreeItem child = (NoticeTreeItem) object;
// JSONObject entry = new JSONObject();
// treeToJson(child, entry);
// childs.put(entry);
// }
// } else {
// json.put(KEY_STATUS, item.getStatus());
// json.put(KEY_CONTENT, item.getContent());
// JSONArray jsonAttachments = writeAttachments(item.getAttachments());
// json.put(KEY_ATTACHMENTS, jsonAttachments);
// }
// json.put(KEY_CHILDREN, childs);
// }
//
// private JSONArray writeAttachments(Attachments attachments) throws JSONException {
// final JSONArray jsonAttachments = new JSONArray();
// for (Attachment attachment : attachments) {
// final JSONObject jsonAttachment = new JSONObject();
// jsonAttachment.put(KEY_ATTACHMENT_NAME, attachment.getName());
// jsonAttachment.put(KEY_ATTACHMENT_DATA, attachment.getDataAsBase64());
// jsonAttachments.put(jsonAttachment);
// }
// return jsonAttachments;
// }
//
// }
// Path: test/com/noticeditorteam/noticeditor/model/NoticeTreeItemBenchmarksTest.java
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;
import com.noticeditorteam.noticeditor.io.JsonFormat;
import org.json.JSONException;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
package com.noticeditorteam.noticeditor.model;
public class NoticeTreeItemBenchmarksTest {
@Rule
public TestRule benchmarkRun = new BenchmarkRule();
private static final int NESTING_LEVEL = 6000;
private static NoticeTreeItem root;
@BeforeClass
public static void beforeClass() {
root = new NoticeTreeItem("root");
NoticeTreeItem branch = root;
for (int i = 0; i < NESTING_LEVEL; i++) {
NoticeTreeItem node = new NoticeTreeItem("branch " + i);
branch.addChild(node);
branch = node;
}
}
@BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 1)
@Ignore
@Test
public void testJsonExport() throws JSONException {
|
JsonFormat.with(null).export(root);
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/controller/SyntaxHighlighter.java
|
// Path: src/com/noticeditorteam/noticeditor/io/IOUtil.java
// public final class IOUtil {
//
// private static final int FILENAME_LIMIT = 60;
//
// public static String readContent(File file) throws IOException {
// return stringFromStream(new FileInputStream(file));
// }
//
// public static void writeContent(File file, String content) throws IOException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// writer.write(content);
// }
// }
//
// public static void writeContent(File file, byte[] content) throws IOException {
// try (OutputStream os = new FileOutputStream(file)) {
// os.write(content);
// }
// }
//
// public static void writeJson(File file, JSONObject json) throws IOException, JSONException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// json.write(writer);
// }
// }
//
// public static void removeDirectory(File directory) {
// if (directory.isFile() || !directory.exists())
// return;
// removeDirectoryHelper(directory);
// }
//
// private static void removeDirectoryHelper(File file) {
// if (file.isDirectory()) {
// for (File f : file.listFiles()) {
// removeDirectoryHelper(f);
// }
// }
// file.delete();
// }
//
// public static String sanitizeFilename(String name) {
// if (name == null || name.isEmpty())
// return "empty";
//
// String newName = name;
// // Quick transliteration
// newName = Junidecode.unidecode(newName);
// // Convert non-ascii chars to char code
// try {
// newName = URLEncoder.encode(newName, "UTF-8");
// } catch (UnsupportedEncodingException ex) {
// }
// // Allow only english chars, numbers and some specific symbols
// newName = newName.toLowerCase().replaceAll("[^a-z0-9._\\(\\)]", "_");
// // Limit filename length
// if (newName.length() > FILENAME_LIMIT) {
// newName = newName.substring(0, FILENAME_LIMIT);
// }
// return newName;
// }
//
// public static InputStream toStream(String content) throws IOException {
// return toStream(content, "UTF-8");
// }
//
// public static InputStream toStream(String content, String charset) throws IOException {
// return new ByteArrayInputStream(content.getBytes(charset));
// }
//
// public static String stringFromStream(InputStream stream) throws IOException {
// return stringFromStream(stream, "UTF-8");
// }
//
// public static String stringFromStream(InputStream stream, String charset) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// copy(stream, result);
// stream.close();
// return result.toString("UTF-8");
// }
//
// public static boolean isResourceExists(String resource) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return is != null;
// } catch (IOException ioe) {
// return false;
// }
// }
//
// public static List<String> linesFromResource(String resource) {
// return linesFromResource(resource, "UTF-8");
// }
//
// public static List<String> linesFromResource(String resource, String charset) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return linesFromStream(is, charset);
// } catch (IOException ioe) {
// return Collections.emptyList();
// }
// }
//
// public static List<String> linesFromStream(InputStream stream) throws IOException {
// return linesFromStream(stream, "UTF-8");
// }
//
// public static List<String> linesFromStream(InputStream stream, String charset) throws IOException {
// if (stream == null) return Collections.emptyList();
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
// return reader.lines().collect(Collectors.toList());
// }
// }
//
// public static byte[] download(String url) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// try (InputStream is = new URL(url).openStream()) {
// copy(is, result);
// }
// return result.toByteArray();
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// final int bufferSize = 8192;
// final byte[] buffer = new byte[bufferSize];
// int readed;
// while ((readed = is.read(buffer, 0, bufferSize)) != -1) {
// os.write(buffer, 0, readed);
// }
// }
// }
|
import com.noticeditorteam.noticeditor.io.IOUtil;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
|
private Set<String> getUsedLanguages(String content) {
Matcher matcher = PATTERN_CODE.matcher(content);
if (!matcher.find())
return null;
Set<String> languages = new HashSet<>();
do {
languages.add(matcher.group(1).toLowerCase());
} while (matcher.find());
return languages;
}
private final Runnable unpackHighlightJs = new Runnable() {
@Override
public void run() {
final File zipFile = new File(DIRECTORY, "highlightjs.zip");
try {
copyZipTo(zipFile);
extractZip(zipFile);
} catch (IOException ex) {
} finally {
zipFile.delete();
}
}
private void copyZipTo(File destFile) throws IOException {
try (InputStream is = getClass().getResourceAsStream("/resources/highlightjs.zip");
OutputStream os = new FileOutputStream(destFile)) {
|
// Path: src/com/noticeditorteam/noticeditor/io/IOUtil.java
// public final class IOUtil {
//
// private static final int FILENAME_LIMIT = 60;
//
// public static String readContent(File file) throws IOException {
// return stringFromStream(new FileInputStream(file));
// }
//
// public static void writeContent(File file, String content) throws IOException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// writer.write(content);
// }
// }
//
// public static void writeContent(File file, byte[] content) throws IOException {
// try (OutputStream os = new FileOutputStream(file)) {
// os.write(content);
// }
// }
//
// public static void writeJson(File file, JSONObject json) throws IOException, JSONException {
// try (OutputStream os = new FileOutputStream(file);
// Writer writer = new OutputStreamWriter(os, "UTF-8")) {
// json.write(writer);
// }
// }
//
// public static void removeDirectory(File directory) {
// if (directory.isFile() || !directory.exists())
// return;
// removeDirectoryHelper(directory);
// }
//
// private static void removeDirectoryHelper(File file) {
// if (file.isDirectory()) {
// for (File f : file.listFiles()) {
// removeDirectoryHelper(f);
// }
// }
// file.delete();
// }
//
// public static String sanitizeFilename(String name) {
// if (name == null || name.isEmpty())
// return "empty";
//
// String newName = name;
// // Quick transliteration
// newName = Junidecode.unidecode(newName);
// // Convert non-ascii chars to char code
// try {
// newName = URLEncoder.encode(newName, "UTF-8");
// } catch (UnsupportedEncodingException ex) {
// }
// // Allow only english chars, numbers and some specific symbols
// newName = newName.toLowerCase().replaceAll("[^a-z0-9._\\(\\)]", "_");
// // Limit filename length
// if (newName.length() > FILENAME_LIMIT) {
// newName = newName.substring(0, FILENAME_LIMIT);
// }
// return newName;
// }
//
// public static InputStream toStream(String content) throws IOException {
// return toStream(content, "UTF-8");
// }
//
// public static InputStream toStream(String content, String charset) throws IOException {
// return new ByteArrayInputStream(content.getBytes(charset));
// }
//
// public static String stringFromStream(InputStream stream) throws IOException {
// return stringFromStream(stream, "UTF-8");
// }
//
// public static String stringFromStream(InputStream stream, String charset) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// copy(stream, result);
// stream.close();
// return result.toString("UTF-8");
// }
//
// public static boolean isResourceExists(String resource) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return is != null;
// } catch (IOException ioe) {
// return false;
// }
// }
//
// public static List<String> linesFromResource(String resource) {
// return linesFromResource(resource, "UTF-8");
// }
//
// public static List<String> linesFromResource(String resource, String charset) {
// try (InputStream is = IOUtil.class.getResourceAsStream(resource)) {
// return linesFromStream(is, charset);
// } catch (IOException ioe) {
// return Collections.emptyList();
// }
// }
//
// public static List<String> linesFromStream(InputStream stream) throws IOException {
// return linesFromStream(stream, "UTF-8");
// }
//
// public static List<String> linesFromStream(InputStream stream, String charset) throws IOException {
// if (stream == null) return Collections.emptyList();
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset))) {
// return reader.lines().collect(Collectors.toList());
// }
// }
//
// public static byte[] download(String url) throws IOException {
// final ByteArrayOutputStream result = new ByteArrayOutputStream();
// try (InputStream is = new URL(url).openStream()) {
// copy(is, result);
// }
// return result.toByteArray();
// }
//
// public static void copy(InputStream is, OutputStream os) throws IOException {
// final int bufferSize = 8192;
// final byte[] buffer = new byte[bufferSize];
// int readed;
// while ((readed = is.read(buffer, 0, bufferSize)) != -1) {
// os.write(buffer, 0, readed);
// }
// }
// }
// Path: src/com/noticeditorteam/noticeditor/controller/SyntaxHighlighter.java
import com.noticeditorteam.noticeditor.io.IOUtil;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
private Set<String> getUsedLanguages(String content) {
Matcher matcher = PATTERN_CODE.matcher(content);
if (!matcher.find())
return null;
Set<String> languages = new HashSet<>();
do {
languages.add(matcher.group(1).toLowerCase());
} while (matcher.find());
return languages;
}
private final Runnable unpackHighlightJs = new Runnable() {
@Override
public void run() {
final File zipFile = new File(DIRECTORY, "highlightjs.zip");
try {
copyZipTo(zipFile);
extractZip(zipFile);
} catch (IOException ex) {
} finally {
zipFile.delete();
}
}
private void copyZipTo(File destFile) throws IOException {
try (InputStream is = getClass().getResourceAsStream("/resources/highlightjs.zip");
OutputStream os = new FileOutputStream(destFile)) {
|
IOUtil.copy(is, os);
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/SingleHtmlExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
|
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.*;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import javafx.scene.control.TreeItem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
|
package com.noticeditorteam.noticeditor.io;
public class SingleHtmlExportStrategy implements ExportStrategy {
private Parser mdParser;
private HtmlRenderer htmlRenderer;
public void setMarkdownParser(Parser parser) {
this.mdParser = parser;
}
public void setHtmlRenderer(HtmlRenderer renderer) {
this.htmlRenderer = renderer;
}
@Override
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/SingleHtmlExportStrategy.java
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.*;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import javafx.scene.control.TreeItem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
package com.noticeditorteam.noticeditor.io;
public class SingleHtmlExportStrategy implements ExportStrategy {
private Parser mdParser;
private HtmlRenderer htmlRenderer;
public void setMarkdownParser(Parser parser) {
this.mdParser = parser;
}
public void setHtmlRenderer(HtmlRenderer renderer) {
this.htmlRenderer = renderer;
}
@Override
|
public boolean export(File destDir, NoticeTree tree) throws ExportException {
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/controller/WebImportController.java
|
// Path: src/com/noticeditorteam/noticeditor/io/importers/HtmlImportMode.java
// public enum HtmlImportMode {
// RELAXED("relaxed", Whitelist.relaxed()),
// ONLY_TEXT("only_text", Whitelist.none()),
// ORIGINAL("original", null),
// BASIC("basic", Whitelist.basic()),
// BASIC_WITH_IMAGES("basic_with_img", Whitelist.basicWithImages()),
// SIMPLE_TEXT("simple_text", Whitelist.simpleText());
//
// private final String name;
// private final Whitelist whitelist;
//
// private HtmlImportMode(String name, Whitelist whitelist) {
// this.name = name;
// this.whitelist = whitelist;
// }
//
// public String getName() {
// return name;
// }
//
// public Whitelist getWhitelist() {
// return whitelist;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/ImportCallback.java
// @FunctionalInterface
// public interface ImportCallback<R, O> {
//
// public void call(R result, O optional);
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
// public class WebImporter extends HtmlImporter {
//
// private final Map<String, String> cache = new HashMap<>();
//
// @Override
// protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
// String html;
// if (cache.containsKey(url)) {
// html = cache.get(url);
// } else {
// html = IOUtil.stringFromStream(new URL(url).openStream());
// cache.put(url, html);
// }
// return super.cleanHtml(html, whitelist);
// }
// }
|
import com.noticeditorteam.noticeditor.io.importers.HtmlImportMode;
import com.noticeditorteam.noticeditor.io.importers.ImportCallback;
import com.noticeditorteam.noticeditor.io.importers.WebImporter;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
|
package com.noticeditorteam.noticeditor.controller;
/**
* @author aNNiMON
*/
public class WebImportController implements Initializable {
@FXML
private VBox modesBox;
@FXML
private WebView pagePreview;
@FXML
private TextField urlField;
|
// Path: src/com/noticeditorteam/noticeditor/io/importers/HtmlImportMode.java
// public enum HtmlImportMode {
// RELAXED("relaxed", Whitelist.relaxed()),
// ONLY_TEXT("only_text", Whitelist.none()),
// ORIGINAL("original", null),
// BASIC("basic", Whitelist.basic()),
// BASIC_WITH_IMAGES("basic_with_img", Whitelist.basicWithImages()),
// SIMPLE_TEXT("simple_text", Whitelist.simpleText());
//
// private final String name;
// private final Whitelist whitelist;
//
// private HtmlImportMode(String name, Whitelist whitelist) {
// this.name = name;
// this.whitelist = whitelist;
// }
//
// public String getName() {
// return name;
// }
//
// public Whitelist getWhitelist() {
// return whitelist;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/ImportCallback.java
// @FunctionalInterface
// public interface ImportCallback<R, O> {
//
// public void call(R result, O optional);
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
// public class WebImporter extends HtmlImporter {
//
// private final Map<String, String> cache = new HashMap<>();
//
// @Override
// protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
// String html;
// if (cache.containsKey(url)) {
// html = cache.get(url);
// } else {
// html = IOUtil.stringFromStream(new URL(url).openStream());
// cache.put(url, html);
// }
// return super.cleanHtml(html, whitelist);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/controller/WebImportController.java
import com.noticeditorteam.noticeditor.io.importers.HtmlImportMode;
import com.noticeditorteam.noticeditor.io.importers.ImportCallback;
import com.noticeditorteam.noticeditor.io.importers.WebImporter;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
package com.noticeditorteam.noticeditor.controller;
/**
* @author aNNiMON
*/
public class WebImportController implements Initializable {
@FXML
private VBox modesBox;
@FXML
private WebView pagePreview;
@FXML
private TextField urlField;
|
private WebImporter importer;
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/controller/WebImportController.java
|
// Path: src/com/noticeditorteam/noticeditor/io/importers/HtmlImportMode.java
// public enum HtmlImportMode {
// RELAXED("relaxed", Whitelist.relaxed()),
// ONLY_TEXT("only_text", Whitelist.none()),
// ORIGINAL("original", null),
// BASIC("basic", Whitelist.basic()),
// BASIC_WITH_IMAGES("basic_with_img", Whitelist.basicWithImages()),
// SIMPLE_TEXT("simple_text", Whitelist.simpleText());
//
// private final String name;
// private final Whitelist whitelist;
//
// private HtmlImportMode(String name, Whitelist whitelist) {
// this.name = name;
// this.whitelist = whitelist;
// }
//
// public String getName() {
// return name;
// }
//
// public Whitelist getWhitelist() {
// return whitelist;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/ImportCallback.java
// @FunctionalInterface
// public interface ImportCallback<R, O> {
//
// public void call(R result, O optional);
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
// public class WebImporter extends HtmlImporter {
//
// private final Map<String, String> cache = new HashMap<>();
//
// @Override
// protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
// String html;
// if (cache.containsKey(url)) {
// html = cache.get(url);
// } else {
// html = IOUtil.stringFromStream(new URL(url).openStream());
// cache.put(url, html);
// }
// return super.cleanHtml(html, whitelist);
// }
// }
|
import com.noticeditorteam.noticeditor.io.importers.HtmlImportMode;
import com.noticeditorteam.noticeditor.io.importers.ImportCallback;
import com.noticeditorteam.noticeditor.io.importers.WebImporter;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
|
package com.noticeditorteam.noticeditor.controller;
/**
* @author aNNiMON
*/
public class WebImportController implements Initializable {
@FXML
private VBox modesBox;
@FXML
private WebView pagePreview;
@FXML
private TextField urlField;
private WebImporter importer;
|
// Path: src/com/noticeditorteam/noticeditor/io/importers/HtmlImportMode.java
// public enum HtmlImportMode {
// RELAXED("relaxed", Whitelist.relaxed()),
// ONLY_TEXT("only_text", Whitelist.none()),
// ORIGINAL("original", null),
// BASIC("basic", Whitelist.basic()),
// BASIC_WITH_IMAGES("basic_with_img", Whitelist.basicWithImages()),
// SIMPLE_TEXT("simple_text", Whitelist.simpleText());
//
// private final String name;
// private final Whitelist whitelist;
//
// private HtmlImportMode(String name, Whitelist whitelist) {
// this.name = name;
// this.whitelist = whitelist;
// }
//
// public String getName() {
// return name;
// }
//
// public Whitelist getWhitelist() {
// return whitelist;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/ImportCallback.java
// @FunctionalInterface
// public interface ImportCallback<R, O> {
//
// public void call(R result, O optional);
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
// public class WebImporter extends HtmlImporter {
//
// private final Map<String, String> cache = new HashMap<>();
//
// @Override
// protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
// String html;
// if (cache.containsKey(url)) {
// html = cache.get(url);
// } else {
// html = IOUtil.stringFromStream(new URL(url).openStream());
// cache.put(url, html);
// }
// return super.cleanHtml(html, whitelist);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/controller/WebImportController.java
import com.noticeditorteam.noticeditor.io.importers.HtmlImportMode;
import com.noticeditorteam.noticeditor.io.importers.ImportCallback;
import com.noticeditorteam.noticeditor.io.importers.WebImporter;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
package com.noticeditorteam.noticeditor.controller;
/**
* @author aNNiMON
*/
public class WebImportController implements Initializable {
@FXML
private VBox modesBox;
@FXML
private WebView pagePreview;
@FXML
private TextField urlField;
private WebImporter importer;
|
private HtmlImportMode importMode;
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/controller/WebImportController.java
|
// Path: src/com/noticeditorteam/noticeditor/io/importers/HtmlImportMode.java
// public enum HtmlImportMode {
// RELAXED("relaxed", Whitelist.relaxed()),
// ONLY_TEXT("only_text", Whitelist.none()),
// ORIGINAL("original", null),
// BASIC("basic", Whitelist.basic()),
// BASIC_WITH_IMAGES("basic_with_img", Whitelist.basicWithImages()),
// SIMPLE_TEXT("simple_text", Whitelist.simpleText());
//
// private final String name;
// private final Whitelist whitelist;
//
// private HtmlImportMode(String name, Whitelist whitelist) {
// this.name = name;
// this.whitelist = whitelist;
// }
//
// public String getName() {
// return name;
// }
//
// public Whitelist getWhitelist() {
// return whitelist;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/ImportCallback.java
// @FunctionalInterface
// public interface ImportCallback<R, O> {
//
// public void call(R result, O optional);
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
// public class WebImporter extends HtmlImporter {
//
// private final Map<String, String> cache = new HashMap<>();
//
// @Override
// protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
// String html;
// if (cache.containsKey(url)) {
// html = cache.get(url);
// } else {
// html = IOUtil.stringFromStream(new URL(url).openStream());
// cache.put(url, html);
// }
// return super.cleanHtml(html, whitelist);
// }
// }
|
import com.noticeditorteam.noticeditor.io.importers.HtmlImportMode;
import com.noticeditorteam.noticeditor.io.importers.ImportCallback;
import com.noticeditorteam.noticeditor.io.importers.WebImporter;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
|
package com.noticeditorteam.noticeditor.controller;
/**
* @author aNNiMON
*/
public class WebImportController implements Initializable {
@FXML
private VBox modesBox;
@FXML
private WebView pagePreview;
@FXML
private TextField urlField;
private WebImporter importer;
private HtmlImportMode importMode;
|
// Path: src/com/noticeditorteam/noticeditor/io/importers/HtmlImportMode.java
// public enum HtmlImportMode {
// RELAXED("relaxed", Whitelist.relaxed()),
// ONLY_TEXT("only_text", Whitelist.none()),
// ORIGINAL("original", null),
// BASIC("basic", Whitelist.basic()),
// BASIC_WITH_IMAGES("basic_with_img", Whitelist.basicWithImages()),
// SIMPLE_TEXT("simple_text", Whitelist.simpleText());
//
// private final String name;
// private final Whitelist whitelist;
//
// private HtmlImportMode(String name, Whitelist whitelist) {
// this.name = name;
// this.whitelist = whitelist;
// }
//
// public String getName() {
// return name;
// }
//
// public Whitelist getWhitelist() {
// return whitelist;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/ImportCallback.java
// @FunctionalInterface
// public interface ImportCallback<R, O> {
//
// public void call(R result, O optional);
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/WebImporter.java
// public class WebImporter extends HtmlImporter {
//
// private final Map<String, String> cache = new HashMap<>();
//
// @Override
// protected String cleanHtml(String url, Whitelist whitelist) throws Exception {
// String html;
// if (cache.containsKey(url)) {
// html = cache.get(url);
// } else {
// html = IOUtil.stringFromStream(new URL(url).openStream());
// cache.put(url, html);
// }
// return super.cleanHtml(html, whitelist);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/controller/WebImportController.java
import com.noticeditorteam.noticeditor.io.importers.HtmlImportMode;
import com.noticeditorteam.noticeditor.io.importers.ImportCallback;
import com.noticeditorteam.noticeditor.io.importers.WebImporter;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
package com.noticeditorteam.noticeditor.controller;
/**
* @author aNNiMON
*/
public class WebImportController implements Initializable {
@FXML
private VBox modesBox;
@FXML
private WebView pagePreview;
@FXML
private TextField urlField;
private WebImporter importer;
private HtmlImportMode importMode;
|
private ImportCallback<String, Exception> importCallback;
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/HtmlExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
|
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.*;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import javafx.scene.control.TreeItem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export notices to html.
*
* @author aNNiMON
*/
public class HtmlExportStrategy implements ExportStrategy {
private Parser mdParser;
private HtmlRenderer htmlRenderer;
private Map<NoticeTreeItem, String> filenames;
public void setMarkdownParser(Parser parser) {
this.mdParser = parser;
}
public void setHtmlRenderer(HtmlRenderer renderer) {
this.htmlRenderer = renderer;
}
@Override
public boolean export(File destDir, NoticeTree notice) {
filenames = new HashMap<>();
try {
exportToHtmlPages(notice, destDir, "index");
return true;
} catch (IOException ioe) {
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/HtmlExportStrategy.java
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.*;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import javafx.scene.control.TreeItem;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
package com.noticeditorteam.noticeditor.io;
/**
* Export notices to html.
*
* @author aNNiMON
*/
public class HtmlExportStrategy implements ExportStrategy {
private Parser mdParser;
private HtmlRenderer htmlRenderer;
private Map<NoticeTreeItem, String> filenames;
public void setMarkdownParser(Parser parser) {
this.mdParser = parser;
}
public void setHtmlRenderer(HtmlRenderer renderer) {
this.htmlRenderer = renderer;
}
@Override
public boolean export(File destDir, NoticeTree notice) {
filenames = new HashMap<>();
try {
exportToHtmlPages(notice, destDir, "index");
return true;
} catch (IOException ioe) {
|
throw new ExportException(ioe);
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/DocumentFormat.java
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/FileImporter.java
// public final class FileImporter {
//
// private static Tree treeImporter;
// private static Content contentImporter;
//
// public static Tree tree() {
// if (treeImporter == null) {
// treeImporter = new Tree();
// }
// return treeImporter;
// }
//
// public static Content content() {
// if (contentImporter == null) {
// contentImporter = new Content();
// }
// return contentImporter;
// }
//
// public static class Tree implements Importer<File, Void, NoticeTree> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<NoticeTree, Exception> callback) {
// try {
// callback.call(importFrom(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
//
// public static NoticeTree importFrom(File file) throws IOException {
// final NoticeTreeItem root = new NoticeTreeItem("Root");
// final NoticeTree tree = new NoticeTree(root);
// tree.addItem(new NoticeTreeItem(file.getName(), IOUtil.readContent(file)), root);
// return tree;
// }
// }
//
// public static class Content implements Importer<File, Void, String> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<String, Exception> callback) {
// try {
// callback.call(IOUtil.readContent(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.io.importers.FileImporter;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Provides common operations with document.
*
* @author aNNiMON
*/
public final class DocumentFormat {
public static NoticeTree open(File file) throws IOException {
final boolean isZip = file.getName().toLowerCase().endsWith(".zip");
try {
if (isZip) {
return ZipWithIndexFormat.with(file).importDocument();
}
return JsonFormat.with(file).importDocument();
} catch (IOException | JSONException e) {
if (isZip) {
// Prevent to open binary files as text
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/FileImporter.java
// public final class FileImporter {
//
// private static Tree treeImporter;
// private static Content contentImporter;
//
// public static Tree tree() {
// if (treeImporter == null) {
// treeImporter = new Tree();
// }
// return treeImporter;
// }
//
// public static Content content() {
// if (contentImporter == null) {
// contentImporter = new Content();
// }
// return contentImporter;
// }
//
// public static class Tree implements Importer<File, Void, NoticeTree> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<NoticeTree, Exception> callback) {
// try {
// callback.call(importFrom(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
//
// public static NoticeTree importFrom(File file) throws IOException {
// final NoticeTreeItem root = new NoticeTreeItem("Root");
// final NoticeTree tree = new NoticeTree(root);
// tree.addItem(new NoticeTreeItem(file.getName(), IOUtil.readContent(file)), root);
// return tree;
// }
// }
//
// public static class Content implements Importer<File, Void, String> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<String, Exception> callback) {
// try {
// callback.call(IOUtil.readContent(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/DocumentFormat.java
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.io.importers.FileImporter;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Provides common operations with document.
*
* @author aNNiMON
*/
public final class DocumentFormat {
public static NoticeTree open(File file) throws IOException {
final boolean isZip = file.getName().toLowerCase().endsWith(".zip");
try {
if (isZip) {
return ZipWithIndexFormat.with(file).importDocument();
}
return JsonFormat.with(file).importDocument();
} catch (IOException | JSONException e) {
if (isZip) {
// Prevent to open binary files as text
|
PasswordManager.resetPassword();
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/DocumentFormat.java
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/FileImporter.java
// public final class FileImporter {
//
// private static Tree treeImporter;
// private static Content contentImporter;
//
// public static Tree tree() {
// if (treeImporter == null) {
// treeImporter = new Tree();
// }
// return treeImporter;
// }
//
// public static Content content() {
// if (contentImporter == null) {
// contentImporter = new Content();
// }
// return contentImporter;
// }
//
// public static class Tree implements Importer<File, Void, NoticeTree> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<NoticeTree, Exception> callback) {
// try {
// callback.call(importFrom(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
//
// public static NoticeTree importFrom(File file) throws IOException {
// final NoticeTreeItem root = new NoticeTreeItem("Root");
// final NoticeTree tree = new NoticeTree(root);
// tree.addItem(new NoticeTreeItem(file.getName(), IOUtil.readContent(file)), root);
// return tree;
// }
// }
//
// public static class Content implements Importer<File, Void, String> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<String, Exception> callback) {
// try {
// callback.call(IOUtil.readContent(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.io.importers.FileImporter;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Provides common operations with document.
*
* @author aNNiMON
*/
public final class DocumentFormat {
public static NoticeTree open(File file) throws IOException {
final boolean isZip = file.getName().toLowerCase().endsWith(".zip");
try {
if (isZip) {
return ZipWithIndexFormat.with(file).importDocument();
}
return JsonFormat.with(file).importDocument();
} catch (IOException | JSONException e) {
if (isZip) {
// Prevent to open binary files as text
PasswordManager.resetPassword();
throw new IOException(e);
}
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/io/importers/FileImporter.java
// public final class FileImporter {
//
// private static Tree treeImporter;
// private static Content contentImporter;
//
// public static Tree tree() {
// if (treeImporter == null) {
// treeImporter = new Tree();
// }
// return treeImporter;
// }
//
// public static Content content() {
// if (contentImporter == null) {
// contentImporter = new Content();
// }
// return contentImporter;
// }
//
// public static class Tree implements Importer<File, Void, NoticeTree> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<NoticeTree, Exception> callback) {
// try {
// callback.call(importFrom(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
//
// public static NoticeTree importFrom(File file) throws IOException {
// final NoticeTreeItem root = new NoticeTreeItem("Root");
// final NoticeTree tree = new NoticeTree(root);
// tree.addItem(new NoticeTreeItem(file.getName(), IOUtil.readContent(file)), root);
// return tree;
// }
// }
//
// public static class Content implements Importer<File, Void, String> {
//
// @Override
// public void importFrom(File file, Void options, ImportCallback<String, Exception> callback) {
// try {
// callback.call(IOUtil.readContent(file), null);
// } catch (IOException ex) {
// callback.call(null, ex);
// }
// }
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/DocumentFormat.java
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.io.importers.FileImporter;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Provides common operations with document.
*
* @author aNNiMON
*/
public final class DocumentFormat {
public static NoticeTree open(File file) throws IOException {
final boolean isZip = file.getName().toLowerCase().endsWith(".zip");
try {
if (isZip) {
return ZipWithIndexFormat.with(file).importDocument();
}
return JsonFormat.with(file).importDocument();
} catch (IOException | JSONException e) {
if (isZip) {
// Prevent to open binary files as text
PasswordManager.resetPassword();
throw new IOException(e);
}
|
return FileImporter.Tree.importFrom(file);
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/ZipExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export document to zip archive with index.json.
*
* @author aNNiMON
*/
public class ZipExportStrategy implements ExportStrategy {
@Override
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/ZipExportStrategy.java
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Export document to zip archive with index.json.
*
* @author aNNiMON
*/
public class ZipExportStrategy implements ExportStrategy {
@Override
|
public boolean export(File file, NoticeTree notice) {
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/ZipExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export document to zip archive with index.json.
*
* @author aNNiMON
*/
public class ZipExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree notice) {
try {
if (file.exists())
file.delete();
ZipWithIndexFormat.with(file).export(notice);
return true;
} catch (IOException | JSONException e) {
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/ZipExportStrategy.java
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Export document to zip archive with index.json.
*
* @author aNNiMON
*/
public class ZipExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree notice) {
try {
if (file.exists())
file.delete();
ZipWithIndexFormat.with(file).export(notice);
return true;
} catch (IOException | JSONException e) {
|
throw new ExportException(e);
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/EncZipExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export document to encrypted zip archive with index.json.
*
* @author aNNiMON
*/
public class EncZipExportStrategy implements ExportStrategy {
@Override
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/EncZipExportStrategy.java
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Export document to encrypted zip archive with index.json.
*
* @author aNNiMON
*/
public class EncZipExportStrategy implements ExportStrategy {
@Override
|
public boolean export(File file, NoticeTree notice) {
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/EncZipExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export document to encrypted zip archive with index.json.
*
* @author aNNiMON
*/
public class EncZipExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree notice) {
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/EncZipExportStrategy.java
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Export document to encrypted zip archive with index.json.
*
* @author aNNiMON
*/
public class EncZipExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree notice) {
|
final Optional<String> password = PasswordManager.askPassword(file.getAbsolutePath());
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/EncZipExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export document to encrypted zip archive with index.json.
*
* @author aNNiMON
*/
public class EncZipExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree notice) {
final Optional<String> password = PasswordManager.askPassword(file.getAbsolutePath());
if (!password.isPresent()) return false;
try {
if (file.exists())
file.delete();
ZipWithIndexFormat.with(file, password.get())
.encrypted()
.export(notice);
return true;
} catch (IOException | JSONException e) {
|
// Path: src/com/noticeditorteam/noticeditor/controller/PasswordManager.java
// public final class PasswordManager {
//
// private static Optional<String> lastPath = Optional.empty();
// private static Optional<String> lastPassword = Optional.empty();
//
// public static void resetPassword() {
// lastPassword = Optional.empty();
// lastPath = Optional.empty();
// }
//
// public static Optional<String> askPassword(String forFilePath) {
// if (lastPath.isPresent() && lastPath.get().equals(forFilePath)) {
// return lastPassword;
// }
// lastPassword = NoticeController.getController()
// .newPasswordDialog(lastPassword.orElse(""))
// .showAndWait();
// if (lastPassword.isPresent()) {
// lastPath = Optional.ofNullable(forFilePath);
// }
// return lastPassword;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/EncZipExportStrategy.java
import com.noticeditorteam.noticeditor.controller.PasswordManager;
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Export document to encrypted zip archive with index.json.
*
* @author aNNiMON
*/
public class EncZipExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree notice) {
final Optional<String> password = PasswordManager.askPassword(file.getAbsolutePath());
if (!password.isPresent()) return false;
try {
if (file.exists())
file.delete();
ZipWithIndexFormat.with(file, password.get())
.encrypted()
.export(notice);
return true;
} catch (IOException | JSONException e) {
|
throw new ExportException(e);
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/plugin/attachments/ClipboardImageImporter.java
|
// Path: src/com/noticeditorteam/noticeditor/model/Attachment.java
// public class Attachment {
//
// public static final Attachment EMPTY = new Attachment("", new byte[0]);
//
// public static final String PREFIX = "@att:";
// public static final Pattern PATTERN = Pattern.compile(PREFIX + "([a-zA-Z0-9._\\(\\)]+)");
//
// private final String name;
// private final byte[] data;
// private final boolean isImage;
// private final String base64data;
//
// public Attachment(String name, byte[] data) {
// this.name = name;
// this.data = data;
// final String nameLowerCase = name.toLowerCase(Locale.ENGLISH);
// isImage = Stream.of("jpg", "jpeg", "png", "gif")
// .anyMatch(ext -> nameLowerCase.endsWith("." + ext));
// base64data = isImage ? toBase64(data) : "";
// }
//
// public String getName() {
// return name;
// }
//
// public byte[] getData() {
// return data;
// }
//
// public String getDataAsBase64() {
// if (!base64data.isEmpty()) return base64data;
// return toBase64(data);
// }
//
// private static String toBase64(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
//
// public boolean isImage() {
// return isImage;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/Attachments.java
// public final class Attachments implements Iterable<Attachment> {
//
// private final Map<String, Attachment> attachments;
//
// public Attachments() {
// attachments = new HashMap<>();
// }
//
// public Attachments(Map<String, Attachment> map) {
// attachments = new HashMap<>(map);
// }
//
// public Attachments(List<Attachment> list) {
// attachments = new HashMap<>(list.size());
// for (Attachment attachment : list) {
// attachments.put(attachment.getName(), attachment);
// }
// }
//
// public Attachments(Attachments other) {
// this(other.attachments);
// }
//
// public int size() {
// return attachments.size();
// }
//
// public boolean isEmpty() {
// return attachments.isEmpty();
// }
//
// public void add(Attachment e) {
// attachments.put(e.getName(), e);
// }
//
// public void remove(Attachment att) {
// attachments.remove(att.getName());
// }
//
// public void clear() {
// attachments.clear();
// }
//
// public Attachment get(String name) {
// return attachments.get(name);
// }
//
// public Attachment getOrEmpty(String name) {
// return attachments.getOrDefault(name, Attachment.EMPTY);
// }
//
// public boolean contains(String key) {
// return attachments.containsKey(key);
// }
//
// @Override
// public Iterator<Attachment> iterator() {
// return attachments.values().iterator();
// }
// }
|
import com.noticeditorteam.noticeditor.model.Attachment;
import com.noticeditorteam.noticeditor.model.Attachments;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javax.imageio.ImageIO;
|
public ClipboardImageImporter(ResourceBundle resources) {
super(resources);
filenameField = new TextField(defaultFilename());
formatComboBox = new ComboBox<>();
formatComboBox.getItems().addAll(ImageFormat.values());
formatComboBox.getSelectionModel().selectFirst();
imageView = new ImageView();
imageView.setPreserveRatio(true);
imageView.setFocusTraversable(true);
propertiesBox = new HBox();
propertiesBox.getChildren().add(filenameField);
propertiesBox.getChildren().add(formatComboBox);
HBox.setHgrow(filenameField, Priority.ALWAYS);
mouseHandler = (event) -> {
container.requestFocus();
};
keyHandler = (event) -> {
if (event.isControlDown() && event.getCode() == KeyCode.V) {
onPaste();
}
};
clipboardHelper = new ClipboardImageHelper();
}
@Override
public String name() {
return resources.getString("import_image_from_clipboard");
}
@Override
|
// Path: src/com/noticeditorteam/noticeditor/model/Attachment.java
// public class Attachment {
//
// public static final Attachment EMPTY = new Attachment("", new byte[0]);
//
// public static final String PREFIX = "@att:";
// public static final Pattern PATTERN = Pattern.compile(PREFIX + "([a-zA-Z0-9._\\(\\)]+)");
//
// private final String name;
// private final byte[] data;
// private final boolean isImage;
// private final String base64data;
//
// public Attachment(String name, byte[] data) {
// this.name = name;
// this.data = data;
// final String nameLowerCase = name.toLowerCase(Locale.ENGLISH);
// isImage = Stream.of("jpg", "jpeg", "png", "gif")
// .anyMatch(ext -> nameLowerCase.endsWith("." + ext));
// base64data = isImage ? toBase64(data) : "";
// }
//
// public String getName() {
// return name;
// }
//
// public byte[] getData() {
// return data;
// }
//
// public String getDataAsBase64() {
// if (!base64data.isEmpty()) return base64data;
// return toBase64(data);
// }
//
// private static String toBase64(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
//
// public boolean isImage() {
// return isImage;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/Attachments.java
// public final class Attachments implements Iterable<Attachment> {
//
// private final Map<String, Attachment> attachments;
//
// public Attachments() {
// attachments = new HashMap<>();
// }
//
// public Attachments(Map<String, Attachment> map) {
// attachments = new HashMap<>(map);
// }
//
// public Attachments(List<Attachment> list) {
// attachments = new HashMap<>(list.size());
// for (Attachment attachment : list) {
// attachments.put(attachment.getName(), attachment);
// }
// }
//
// public Attachments(Attachments other) {
// this(other.attachments);
// }
//
// public int size() {
// return attachments.size();
// }
//
// public boolean isEmpty() {
// return attachments.isEmpty();
// }
//
// public void add(Attachment e) {
// attachments.put(e.getName(), e);
// }
//
// public void remove(Attachment att) {
// attachments.remove(att.getName());
// }
//
// public void clear() {
// attachments.clear();
// }
//
// public Attachment get(String name) {
// return attachments.get(name);
// }
//
// public Attachment getOrEmpty(String name) {
// return attachments.getOrDefault(name, Attachment.EMPTY);
// }
//
// public boolean contains(String key) {
// return attachments.containsKey(key);
// }
//
// @Override
// public Iterator<Attachment> iterator() {
// return attachments.values().iterator();
// }
// }
// Path: src/com/noticeditorteam/noticeditor/plugin/attachments/ClipboardImageImporter.java
import com.noticeditorteam.noticeditor.model.Attachment;
import com.noticeditorteam.noticeditor.model.Attachments;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javax.imageio.ImageIO;
public ClipboardImageImporter(ResourceBundle resources) {
super(resources);
filenameField = new TextField(defaultFilename());
formatComboBox = new ComboBox<>();
formatComboBox.getItems().addAll(ImageFormat.values());
formatComboBox.getSelectionModel().selectFirst();
imageView = new ImageView();
imageView.setPreserveRatio(true);
imageView.setFocusTraversable(true);
propertiesBox = new HBox();
propertiesBox.getChildren().add(filenameField);
propertiesBox.getChildren().add(formatComboBox);
HBox.setHgrow(filenameField, Priority.ALWAYS);
mouseHandler = (event) -> {
container.requestFocus();
};
keyHandler = (event) -> {
if (event.isControlDown() && event.getCode() == KeyCode.V) {
onPaste();
}
};
clipboardHelper = new ClipboardImageHelper();
}
@Override
public String name() {
return resources.getString("import_image_from_clipboard");
}
@Override
|
protected Task<Attachments> createTask() {
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/plugin/attachments/ClipboardImageImporter.java
|
// Path: src/com/noticeditorteam/noticeditor/model/Attachment.java
// public class Attachment {
//
// public static final Attachment EMPTY = new Attachment("", new byte[0]);
//
// public static final String PREFIX = "@att:";
// public static final Pattern PATTERN = Pattern.compile(PREFIX + "([a-zA-Z0-9._\\(\\)]+)");
//
// private final String name;
// private final byte[] data;
// private final boolean isImage;
// private final String base64data;
//
// public Attachment(String name, byte[] data) {
// this.name = name;
// this.data = data;
// final String nameLowerCase = name.toLowerCase(Locale.ENGLISH);
// isImage = Stream.of("jpg", "jpeg", "png", "gif")
// .anyMatch(ext -> nameLowerCase.endsWith("." + ext));
// base64data = isImage ? toBase64(data) : "";
// }
//
// public String getName() {
// return name;
// }
//
// public byte[] getData() {
// return data;
// }
//
// public String getDataAsBase64() {
// if (!base64data.isEmpty()) return base64data;
// return toBase64(data);
// }
//
// private static String toBase64(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
//
// public boolean isImage() {
// return isImage;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/Attachments.java
// public final class Attachments implements Iterable<Attachment> {
//
// private final Map<String, Attachment> attachments;
//
// public Attachments() {
// attachments = new HashMap<>();
// }
//
// public Attachments(Map<String, Attachment> map) {
// attachments = new HashMap<>(map);
// }
//
// public Attachments(List<Attachment> list) {
// attachments = new HashMap<>(list.size());
// for (Attachment attachment : list) {
// attachments.put(attachment.getName(), attachment);
// }
// }
//
// public Attachments(Attachments other) {
// this(other.attachments);
// }
//
// public int size() {
// return attachments.size();
// }
//
// public boolean isEmpty() {
// return attachments.isEmpty();
// }
//
// public void add(Attachment e) {
// attachments.put(e.getName(), e);
// }
//
// public void remove(Attachment att) {
// attachments.remove(att.getName());
// }
//
// public void clear() {
// attachments.clear();
// }
//
// public Attachment get(String name) {
// return attachments.get(name);
// }
//
// public Attachment getOrEmpty(String name) {
// return attachments.getOrDefault(name, Attachment.EMPTY);
// }
//
// public boolean contains(String key) {
// return attachments.containsKey(key);
// }
//
// @Override
// public Iterator<Attachment> iterator() {
// return attachments.values().iterator();
// }
// }
|
import com.noticeditorteam.noticeditor.model.Attachment;
import com.noticeditorteam.noticeditor.model.Attachments;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javax.imageio.ImageIO;
|
onPaste();
}
};
clipboardHelper = new ClipboardImageHelper();
}
@Override
public String name() {
return resources.getString("import_image_from_clipboard");
}
@Override
protected Task<Attachments> createTask() {
return new Task<Attachments>() {
@Override
protected Attachments call() throws Exception {
final Attachments result = new Attachments();
final Image image = imageView.getImage();
if (image == null) return result;
final BufferedImage swingImage = SwingFXUtils.fromFXImage(imageView.getImage(), null);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ImageFormat format = formatComboBox.getValue();
ImageIO.write(swingImage, format.format, baos);
baos.close();
imageView.setImage(null);
final String filename = Optional.ofNullable(filenameField.getText())
.orElse(defaultFilename()) + format.extension;
|
// Path: src/com/noticeditorteam/noticeditor/model/Attachment.java
// public class Attachment {
//
// public static final Attachment EMPTY = new Attachment("", new byte[0]);
//
// public static final String PREFIX = "@att:";
// public static final Pattern PATTERN = Pattern.compile(PREFIX + "([a-zA-Z0-9._\\(\\)]+)");
//
// private final String name;
// private final byte[] data;
// private final boolean isImage;
// private final String base64data;
//
// public Attachment(String name, byte[] data) {
// this.name = name;
// this.data = data;
// final String nameLowerCase = name.toLowerCase(Locale.ENGLISH);
// isImage = Stream.of("jpg", "jpeg", "png", "gif")
// .anyMatch(ext -> nameLowerCase.endsWith("." + ext));
// base64data = isImage ? toBase64(data) : "";
// }
//
// public String getName() {
// return name;
// }
//
// public byte[] getData() {
// return data;
// }
//
// public String getDataAsBase64() {
// if (!base64data.isEmpty()) return base64data;
// return toBase64(data);
// }
//
// private static String toBase64(byte[] data) {
// return Base64.getEncoder().encodeToString(data);
// }
//
// public boolean isImage() {
// return isImage;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/Attachments.java
// public final class Attachments implements Iterable<Attachment> {
//
// private final Map<String, Attachment> attachments;
//
// public Attachments() {
// attachments = new HashMap<>();
// }
//
// public Attachments(Map<String, Attachment> map) {
// attachments = new HashMap<>(map);
// }
//
// public Attachments(List<Attachment> list) {
// attachments = new HashMap<>(list.size());
// for (Attachment attachment : list) {
// attachments.put(attachment.getName(), attachment);
// }
// }
//
// public Attachments(Attachments other) {
// this(other.attachments);
// }
//
// public int size() {
// return attachments.size();
// }
//
// public boolean isEmpty() {
// return attachments.isEmpty();
// }
//
// public void add(Attachment e) {
// attachments.put(e.getName(), e);
// }
//
// public void remove(Attachment att) {
// attachments.remove(att.getName());
// }
//
// public void clear() {
// attachments.clear();
// }
//
// public Attachment get(String name) {
// return attachments.get(name);
// }
//
// public Attachment getOrEmpty(String name) {
// return attachments.getOrDefault(name, Attachment.EMPTY);
// }
//
// public boolean contains(String key) {
// return attachments.containsKey(key);
// }
//
// @Override
// public Iterator<Attachment> iterator() {
// return attachments.values().iterator();
// }
// }
// Path: src/com/noticeditorteam/noticeditor/plugin/attachments/ClipboardImageImporter.java
import com.noticeditorteam.noticeditor.model.Attachment;
import com.noticeditorteam.noticeditor.model.Attachments;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.concurrent.Task;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javax.imageio.ImageIO;
onPaste();
}
};
clipboardHelper = new ClipboardImageHelper();
}
@Override
public String name() {
return resources.getString("import_image_from_clipboard");
}
@Override
protected Task<Attachments> createTask() {
return new Task<Attachments>() {
@Override
protected Attachments call() throws Exception {
final Attachments result = new Attachments();
final Image image = imageView.getImage();
if (image == null) return result;
final BufferedImage swingImage = SwingFXUtils.fromFXImage(imageView.getImage(), null);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ImageFormat format = formatComboBox.getValue();
ImageIO.write(swingImage, format.format, baos);
baos.close();
imageView.setImage(null);
final String filename = Optional.ofNullable(filenameField.getText())
.orElse(defaultFilename()) + format.extension;
|
result.add(new Attachment(filename, baos.toByteArray()));
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/JsonExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export notices to json.
*
* @author aNNiMON
*/
public class JsonExportStrategy implements ExportStrategy {
@Override
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/JsonExportStrategy.java
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Export notices to json.
*
* @author aNNiMON
*/
public class JsonExportStrategy implements ExportStrategy {
@Override
|
public boolean export(File file, NoticeTree tree) {
|
NoticEditorTeam/NoticEditor
|
src/com/noticeditorteam/noticeditor/io/JsonExportStrategy.java
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
|
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
|
package com.noticeditorteam.noticeditor.io;
/**
* Export notices to json.
*
* @author aNNiMON
*/
public class JsonExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree tree) {
try {
JsonFormat.with(file).export(tree);
return true;
} catch (IOException | JSONException e) {
|
// Path: src/com/noticeditorteam/noticeditor/exceptions/ExportException.java
// public class ExportException extends RuntimeException {
//
// public ExportException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/com/noticeditorteam/noticeditor/model/NoticeTree.java
// public class NoticeTree {
//
// private final NoticeTreeItem root;
//
// public NoticeTree() {
// root = null;
// }
//
// /**
// * Create NoticeTree with set root
// *
// * @param root set root
// */
// public NoticeTree(NoticeTreeItem root) {
// this.root = root;
// }
//
// public NoticeTreeItem getRoot() {
// return root;
// }
//
// /**
// * @param item to add
// * @param parent if null, item will be added to root item.
// */
// public void addItem(NoticeTreeItem item, NoticeTreeItem parent) {
// if (parent == null) {
// parent = root;
// } else if (parent.isLeaf()) {
// parent = (NoticeTreeItem) parent.getParent();
// }
// parent.getInternalChildren().add(item);
// parent.setExpanded(true);
// }
//
// public void removeItem(NoticeTreeItem item) {
// if (item == null)
// return;
// NoticeTreeItem parent = (NoticeTreeItem) item.getParent();
// if (parent == null)
// return;
// parent.getInternalChildren().remove(item);
// }
// }
// Path: src/com/noticeditorteam/noticeditor/io/JsonExportStrategy.java
import com.noticeditorteam.noticeditor.exceptions.ExportException;
import com.noticeditorteam.noticeditor.model.NoticeTree;
import java.io.File;
import java.io.IOException;
import org.json.JSONException;
package com.noticeditorteam.noticeditor.io;
/**
* Export notices to json.
*
* @author aNNiMON
*/
public class JsonExportStrategy implements ExportStrategy {
@Override
public boolean export(File file, NoticeTree tree) {
try {
JsonFormat.with(file).export(tree);
return true;
} catch (IOException | JSONException e) {
|
throw new ExportException(e);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/eureka/EurekaServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
|
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.eureka;
/**
*
* @author Will Tran
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaServiceConnectorIntegrationTest.TestConfig.class)
public class EurekaServiceConnectorIntegrationTest {
private static final String ACCESS_TOKEN_URI = "https://p-spring-cloud-services.uaa.my-cf.com/oauth/token";
private static final String CLIENT_SECRET = "theClientSecret";
private static final String CLIENT_ID = "theClientId";
private static final String URI = "https://eureka-12345.mydomain.com";
@Autowired
private Environment environment;
@BeforeClass
public static void beforeClass() {
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/eureka/EurekaServiceConnectorIntegrationTest.java
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.eureka;
/**
*
* @author Will Tran
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaServiceConnectorIntegrationTest.TestConfig.class)
public class EurekaServiceConnectorIntegrationTest {
private static final String ACCESS_TOKEN_URI = "https://p-spring-cloud-services.uaa.my-cf.com/oauth/token";
private static final String CLIENT_SECRET = "theClientSecret";
private static final String CLIENT_ID = "theClientId";
private static final String URI = "https://eureka-12345.mydomain.com";
@Autowired
private Environment environment;
@BeforeClass
public static void beforeClass() {
|
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/eureka/EurekaServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
|
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.eureka;
/**
*
* @author Will Tran
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaServiceConnectorIntegrationTest.TestConfig.class)
public class EurekaServiceConnectorIntegrationTest {
private static final String ACCESS_TOKEN_URI = "https://p-spring-cloud-services.uaa.my-cf.com/oauth/token";
private static final String CLIENT_SECRET = "theClientSecret";
private static final String CLIENT_ID = "theClientId";
private static final String URI = "https://eureka-12345.mydomain.com";
@Autowired
private Environment environment;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/eureka/EurekaServiceConnectorIntegrationTest.java
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.eureka;
/**
*
* @author Will Tran
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaServiceConnectorIntegrationTest.TestConfig.class)
public class EurekaServiceConnectorIntegrationTest {
private static final String ACCESS_TOKEN_URI = "https://p-spring-cloud-services.uaa.my-cf.com/oauth/token";
private static final String CLIENT_SECRET = "theClientSecret";
private static final String CLIENT_ID = "theClientId";
private static final String URI = "https://eureka-12345.mydomain.com";
@Autowired
private Environment environment;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
|
new EurekaServiceInfo("eureka", URI, CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN_URI)));
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/eureka/EurekaServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
|
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.eureka;
/**
*
* @author Will Tran
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaServiceConnectorIntegrationTest.TestConfig.class)
public class EurekaServiceConnectorIntegrationTest {
private static final String ACCESS_TOKEN_URI = "https://p-spring-cloud-services.uaa.my-cf.com/oauth/token";
private static final String CLIENT_SECRET = "theClientSecret";
private static final String CLIENT_ID = "theClientId";
private static final String URI = "https://eureka-12345.mydomain.com";
@Autowired
private Environment environment;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
new EurekaServiceInfo("eureka", URI, CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN_URI)));
}
@AfterClass
public static void afterClass() {
MockCloudConnector.reset();
}
@TestPropertySource(properties = "spring.rabbitmq.host=some_rabbit_host")
public static class WithRabbitBinding extends EurekaServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsNull() {
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/eureka/EurekaServiceConnectorIntegrationTest.java
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.eureka;
/**
*
* @author Will Tran
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaServiceConnectorIntegrationTest.TestConfig.class)
public class EurekaServiceConnectorIntegrationTest {
private static final String ACCESS_TOKEN_URI = "https://p-spring-cloud-services.uaa.my-cf.com/oauth/token";
private static final String CLIENT_SECRET = "theClientSecret";
private static final String CLIENT_ID = "theClientId";
private static final String URI = "https://eureka-12345.mydomain.com";
@Autowired
private Environment environment;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
new EurekaServiceInfo("eureka", URI, CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN_URI)));
}
@AfterClass
public static void afterClass() {
MockCloudConnector.reset();
}
@TestPropertySource(properties = "spring.rabbitmq.host=some_rabbit_host")
public static class WithRabbitBinding extends EurekaServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsNull() {
|
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-cloudfoundry-connector/src/test/java/io/pivotal/spring/cloud/cloudfoundry/HystrixAmqpServiceInfoCreatorTest.java
|
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/HystrixAmqpServiceInfo.java
// public class HystrixAmqpServiceInfo extends BaseServiceInfo {
//
// private static final int AMQP_PORT = 5672;
//
// private static final int AMQPS_PORT = 5671;
//
// private AmqpServiceInfo delegate;
//
// private boolean sslEnabled;
//
// public HystrixAmqpServiceInfo(String id, String uri) throws CloudException {
// super(id);
// delegate = new AmqpServiceInfo(id, uri);
// }
//
// public HystrixAmqpServiceInfo(String id, String uri, List<String> uris,
// boolean sslEnabled) {
// super(id);
// delegate = new AmqpServiceInfo(id, uri, null, uris, null);
// this.sslEnabled = sslEnabled;
// }
//
// public AmqpServiceInfo getAmqpInfo() {
// return delegate;
// }
//
// public String getHost() {
// return delegate.getHost();
// }
//
// public int getPort() {
// return delegate.getPort();
// }
//
// public String getUserName() {
// return delegate.getUserName();
// }
//
// public String getPassword() {
// return delegate.getPassword();
// }
//
// public String getVirtualHost() {
// return delegate.getVirtualHost();
// }
//
// public boolean getSslEnabled() {
// return this.sslEnabled;
// }
//
// public String getAddresses() {
// if (this.delegate.getUris() != null && !this.delegate.getUris().isEmpty()) {
// return assembleAddresses(this.delegate.getUris());
// }
// else {
// return assembleAddresses(Arrays.asList(this.delegate.getUri()));
// }
// }
//
// private String assembleAddresses(List<String> uris) {
// List<String> addresses = new ArrayList<>();
// for (String uri : uris) {
// UriInfo uriInfo = new UriInfo(uri);
// int port = getSchemeBasedPort(uriInfo.getPort(), uriInfo.getScheme());
// addresses.add(uriInfo.getHost() + ":" + port);
// }
// return StringUtils.arrayToCommaDelimitedString(addresses.toArray());
// }
//
// private int getSchemeBasedPort(final int currentPort, String scheme) {
// int port = currentPort;
// if (currentPort == -1) {
// if (AmqpServiceInfo.AMQP_SCHEME.equals(scheme)) {
// port = AMQP_PORT;
// }
// else if (AmqpServiceInfo.AMQPS_SCHEME.equals(scheme)) {
// port = AMQPS_PORT;
// }
// }
// return port;
// }
//
// }
|
import java.util.List;
import io.pivotal.spring.cloud.service.common.HystrixAmqpServiceInfo;
import org.junit.Test;
import org.springframework.cloud.cloudfoundry.AbstractCloudFoundryConnectorTest;
import org.springframework.cloud.service.ServiceInfo;
import org.springframework.cloud.service.common.AmqpServiceInfo;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.cloudfoundry;
/**
* Connector tests for Hystrix AMQP services
*
* @author Scott Frederick
*/
public class HystrixAmqpServiceInfoCreatorTest extends AbstractCloudFoundryConnectorTest {
private static final String SERVICE_TAG_NAME = "myHystrixAmqpInstance";
private static final String VCAP_SERVICES_ENV_KEY = "VCAP_SERVICES";
private static final String PAYLOAD_FILE_NAME = "test-hystrix-amqp-info.json";
private static final String PAYLOAD_TEMPLATE_SERVICE_NAME = "$serviceName";
private static final String PAYLOAD_TEMPLATE_HOSTNAME = "$hostname";
private static final String PAYLOAD_TEMPLATE_PORT = "$port";
private static final String PAYLOAD_TEMPLATE_USER = "$user";
private static final String PAYLOAD_TEMPLATE_PASS = "$pass";
private static final String PAYLOAD_TEMPLATE_VHOST = "$vhost";
@Test
public void hystrixAmqpServiceCreation() {
when(mockEnvironment.getEnvValue(VCAP_SERVICES_ENV_KEY))
.thenReturn(getServicesPayload(getServicePayload(SERVICE_TAG_NAME, hostname, port, username, password, "vhost1")));
List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos();
|
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/HystrixAmqpServiceInfo.java
// public class HystrixAmqpServiceInfo extends BaseServiceInfo {
//
// private static final int AMQP_PORT = 5672;
//
// private static final int AMQPS_PORT = 5671;
//
// private AmqpServiceInfo delegate;
//
// private boolean sslEnabled;
//
// public HystrixAmqpServiceInfo(String id, String uri) throws CloudException {
// super(id);
// delegate = new AmqpServiceInfo(id, uri);
// }
//
// public HystrixAmqpServiceInfo(String id, String uri, List<String> uris,
// boolean sslEnabled) {
// super(id);
// delegate = new AmqpServiceInfo(id, uri, null, uris, null);
// this.sslEnabled = sslEnabled;
// }
//
// public AmqpServiceInfo getAmqpInfo() {
// return delegate;
// }
//
// public String getHost() {
// return delegate.getHost();
// }
//
// public int getPort() {
// return delegate.getPort();
// }
//
// public String getUserName() {
// return delegate.getUserName();
// }
//
// public String getPassword() {
// return delegate.getPassword();
// }
//
// public String getVirtualHost() {
// return delegate.getVirtualHost();
// }
//
// public boolean getSslEnabled() {
// return this.sslEnabled;
// }
//
// public String getAddresses() {
// if (this.delegate.getUris() != null && !this.delegate.getUris().isEmpty()) {
// return assembleAddresses(this.delegate.getUris());
// }
// else {
// return assembleAddresses(Arrays.asList(this.delegate.getUri()));
// }
// }
//
// private String assembleAddresses(List<String> uris) {
// List<String> addresses = new ArrayList<>();
// for (String uri : uris) {
// UriInfo uriInfo = new UriInfo(uri);
// int port = getSchemeBasedPort(uriInfo.getPort(), uriInfo.getScheme());
// addresses.add(uriInfo.getHost() + ":" + port);
// }
// return StringUtils.arrayToCommaDelimitedString(addresses.toArray());
// }
//
// private int getSchemeBasedPort(final int currentPort, String scheme) {
// int port = currentPort;
// if (currentPort == -1) {
// if (AmqpServiceInfo.AMQP_SCHEME.equals(scheme)) {
// port = AMQP_PORT;
// }
// else if (AmqpServiceInfo.AMQPS_SCHEME.equals(scheme)) {
// port = AMQPS_PORT;
// }
// }
// return port;
// }
//
// }
// Path: spring-cloud-services-cloudfoundry-connector/src/test/java/io/pivotal/spring/cloud/cloudfoundry/HystrixAmqpServiceInfoCreatorTest.java
import java.util.List;
import io.pivotal.spring.cloud.service.common.HystrixAmqpServiceInfo;
import org.junit.Test;
import org.springframework.cloud.cloudfoundry.AbstractCloudFoundryConnectorTest;
import org.springframework.cloud.service.ServiceInfo;
import org.springframework.cloud.service.common.AmqpServiceInfo;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.cloudfoundry;
/**
* Connector tests for Hystrix AMQP services
*
* @author Scott Frederick
*/
public class HystrixAmqpServiceInfoCreatorTest extends AbstractCloudFoundryConnectorTest {
private static final String SERVICE_TAG_NAME = "myHystrixAmqpInstance";
private static final String VCAP_SERVICES_ENV_KEY = "VCAP_SERVICES";
private static final String PAYLOAD_FILE_NAME = "test-hystrix-amqp-info.json";
private static final String PAYLOAD_TEMPLATE_SERVICE_NAME = "$serviceName";
private static final String PAYLOAD_TEMPLATE_HOSTNAME = "$hostname";
private static final String PAYLOAD_TEMPLATE_PORT = "$port";
private static final String PAYLOAD_TEMPLATE_USER = "$user";
private static final String PAYLOAD_TEMPLATE_PASS = "$pass";
private static final String PAYLOAD_TEMPLATE_VHOST = "$vhost";
@Test
public void hystrixAmqpServiceCreation() {
when(mockEnvironment.getEnvValue(VCAP_SERVICES_ENV_KEY))
.thenReturn(getServicesPayload(getServicePayload(SERVICE_TAG_NAME, hostname, port, username, password, "vhost1")));
List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos();
|
assertServiceFoundOfType(serviceInfos, SERVICE_TAG_NAME, HystrixAmqpServiceInfo.class);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-cloudfoundry-connector/src/test/java/io/pivotal/spring/cloud/cloudfoundry/EurekaServiceInfoCreatorTest.java
|
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
|
import java.util.List;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.cloud.cloudfoundry.AbstractCloudFoundryConnectorTest;
import org.springframework.cloud.service.ServiceInfo;
import static org.mockito.Mockito.when;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.cloudfoundry;
/**
* Connector tests for Eureka services
*
* @author Chris Schaefer
*/
public class EurekaServiceInfoCreatorTest extends AbstractCloudFoundryConnectorTest {
private static final String EUREKA_SERVICE_TAG_NAME = "myEurekaInstance";
private static final String VCAP_SERVICES_ENV_KEY = "VCAP_SERVICES";
private static final String PAYLOAD_FILE_NAME = "test-eureka-info.json";
private static final String PAYLOAD_TEMPLATE_SERVICE_NAME = "$serviceName";
private static final String PAYLOAD_TEMPLATE_HOSTNAME = "$hostname";
private static final String PAYLOAD_TEMPLATE_PORT = "$port";
private static final String PAYLOAD_TEMPLATE_USER = "$user";
private static final String PAYLOAD_TEMPLATE_PASS = "$pass";
@Test
public void eurekaServiceCreationWithTags() {
when(mockEnvironment.getEnvValue(VCAP_SERVICES_ENV_KEY))
.thenReturn(getServicesPayload(getEurekaServicePayload(EUREKA_SERVICE_TAG_NAME, hostname, port, username, password)));
List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos();
|
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/EurekaServiceInfo.java
// @ServiceInfo.ServiceLabel("eureka")
// public class EurekaServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public EurekaServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
//
// }
// Path: spring-cloud-services-cloudfoundry-connector/src/test/java/io/pivotal/spring/cloud/cloudfoundry/EurekaServiceInfoCreatorTest.java
import java.util.List;
import io.pivotal.spring.cloud.service.common.EurekaServiceInfo;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.cloud.cloudfoundry.AbstractCloudFoundryConnectorTest;
import org.springframework.cloud.service.ServiceInfo;
import static org.mockito.Mockito.when;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.cloudfoundry;
/**
* Connector tests for Eureka services
*
* @author Chris Schaefer
*/
public class EurekaServiceInfoCreatorTest extends AbstractCloudFoundryConnectorTest {
private static final String EUREKA_SERVICE_TAG_NAME = "myEurekaInstance";
private static final String VCAP_SERVICES_ENV_KEY = "VCAP_SERVICES";
private static final String PAYLOAD_FILE_NAME = "test-eureka-info.json";
private static final String PAYLOAD_TEMPLATE_SERVICE_NAME = "$serviceName";
private static final String PAYLOAD_TEMPLATE_HOSTNAME = "$hostname";
private static final String PAYLOAD_TEMPLATE_PORT = "$port";
private static final String PAYLOAD_TEMPLATE_USER = "$user";
private static final String PAYLOAD_TEMPLATE_PASS = "$pass";
@Test
public void eurekaServiceCreationWithTags() {
when(mockEnvironment.getEnvValue(VCAP_SERVICES_ENV_KEY))
.thenReturn(getServicesPayload(getEurekaServicePayload(EUREKA_SERVICE_TAG_NAME, hostname, port, username, password)));
List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos();
|
assertServiceFoundOfType(serviceInfos, EUREKA_SERVICE_TAG_NAME, EurekaServiceInfo.class);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-cloudfoundry-connector/src/test/java/io/pivotal/spring/cloud/cloudfoundry/ConfigServerServiceInfoCreatorTest.java
|
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
|
import org.junit.Assert;
import org.junit.Test;
import org.springframework.cloud.cloudfoundry.AbstractCloudFoundryConnectorTest;
import org.springframework.cloud.service.ServiceInfo;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import java.util.List;
import static org.mockito.Mockito.when;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.cloudfoundry;
/**
* Connector tests for Config Server services
*
* @author Chris Schaefer
*/
public class ConfigServerServiceInfoCreatorTest extends AbstractCloudFoundryConnectorTest {
private static final String CONFIG_SERVER_SERVICE_TAG_NAME = "myConfigServerService";
private static final String VCAP_SERVICES_ENV_KEY = "VCAP_SERVICES";
private static final String PAYLOAD_FILE_NAME = "test-config-server-info.json";
private static final String PAYLOAD_TEMPLATE_SERVICE_NAME = "$serviceName";
private static final String PAYLOAD_TEMPLATE_HOSTNAME = "$hostname";
private static final String PAYLOAD_TEMPLATE_PORT = "$port";
private static final String PAYLOAD_TEMPLATE_USER = "$user";
private static final String PAYLOAD_TEMPLATE_PASS = "$pass";
@Test
public void configServerServiceCreationWithTags() {
when(mockEnvironment.getEnvValue(VCAP_SERVICES_ENV_KEY))
.thenReturn(getServicesPayload(getConfigServerServicePayload(CONFIG_SERVER_SERVICE_TAG_NAME,
hostname, port, username, password)));
List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos();
|
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
// Path: spring-cloud-services-cloudfoundry-connector/src/test/java/io/pivotal/spring/cloud/cloudfoundry/ConfigServerServiceInfoCreatorTest.java
import org.junit.Assert;
import org.junit.Test;
import org.springframework.cloud.cloudfoundry.AbstractCloudFoundryConnectorTest;
import org.springframework.cloud.service.ServiceInfo;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import java.util.List;
import static org.mockito.Mockito.when;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.cloudfoundry;
/**
* Connector tests for Config Server services
*
* @author Chris Schaefer
*/
public class ConfigServerServiceInfoCreatorTest extends AbstractCloudFoundryConnectorTest {
private static final String CONFIG_SERVER_SERVICE_TAG_NAME = "myConfigServerService";
private static final String VCAP_SERVICES_ENV_KEY = "VCAP_SERVICES";
private static final String PAYLOAD_FILE_NAME = "test-config-server-info.json";
private static final String PAYLOAD_TEMPLATE_SERVICE_NAME = "$serviceName";
private static final String PAYLOAD_TEMPLATE_HOSTNAME = "$hostname";
private static final String PAYLOAD_TEMPLATE_PORT = "$port";
private static final String PAYLOAD_TEMPLATE_USER = "$user";
private static final String PAYLOAD_TEMPLATE_PASS = "$pass";
@Test
public void configServerServiceCreationWithTags() {
when(mockEnvironment.getEnvValue(VCAP_SERVICES_ENV_KEY))
.thenReturn(getServicesPayload(getConfigServerServicePayload(CONFIG_SERVER_SERVICE_TAG_NAME,
hostname, port, username, password)));
List<ServiceInfo> serviceInfos = testCloudConnector.getServiceInfos();
|
assertServiceFoundOfType(serviceInfos, CONFIG_SERVER_SERVICE_TAG_NAME, ConfigServerServiceInfo.class);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
|
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.config;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(
classes = {
ConfigServerServiceConnectorIntegrationTest.TestConfig.class
},
properties = "spring.cloud.config.enabled=true")
public class ConfigServerServiceConnectorIntegrationTest {
private static final String CLIENT_ID = "client-id";
private static final String CLIENT_SECRET = "secret";
private static final String ACCESS_TOKEN_URI = "https://your-identity-zone.uaa.my-cf.com/oauth/token";
private static final String URI = "https://username:[email protected]";
@Autowired
private Environment environment;
@Autowired
private ApplicationContext context;
@BeforeClass
public static void beforeClass() {
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.config;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(
classes = {
ConfigServerServiceConnectorIntegrationTest.TestConfig.class
},
properties = "spring.cloud.config.enabled=true")
public class ConfigServerServiceConnectorIntegrationTest {
private static final String CLIENT_ID = "client-id";
private static final String CLIENT_SECRET = "secret";
private static final String ACCESS_TOKEN_URI = "https://your-identity-zone.uaa.my-cf.com/oauth/token";
private static final String URI = "https://username:[email protected]";
@Autowired
private Environment environment;
@Autowired
private ApplicationContext context;
@BeforeClass
public static void beforeClass() {
|
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
|
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
|
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.config;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(
classes = {
ConfigServerServiceConnectorIntegrationTest.TestConfig.class
},
properties = "spring.cloud.config.enabled=true")
public class ConfigServerServiceConnectorIntegrationTest {
private static final String CLIENT_ID = "client-id";
private static final String CLIENT_SECRET = "secret";
private static final String ACCESS_TOKEN_URI = "https://your-identity-zone.uaa.my-cf.com/oauth/token";
private static final String URI = "https://username:[email protected]";
@Autowired
private Environment environment;
@Autowired
private ApplicationContext context;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
/*
* Copyright 2015 the original author or authors.
*
* 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
*
* https://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 io.pivotal.spring.cloud.service.config;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(
classes = {
ConfigServerServiceConnectorIntegrationTest.TestConfig.class
},
properties = "spring.cloud.config.enabled=true")
public class ConfigServerServiceConnectorIntegrationTest {
private static final String CLIENT_ID = "client-id";
private static final String CLIENT_SECRET = "secret";
private static final String ACCESS_TOKEN_URI = "https://your-identity-zone.uaa.my-cf.com/oauth/token";
private static final String URI = "https://username:[email protected]";
@Autowired
private Environment environment;
@Autowired
private ApplicationContext context;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
|
new ConfigServerServiceInfo("config-server",
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
|
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
|
private static final String URI = "https://username:[email protected]";
@Autowired
private Environment environment;
@Autowired
private ApplicationContext context;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
new ConfigServerServiceInfo("config-server",
URI,
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN_URI)));
}
@AfterClass
public static void afterClass() {
MockCloudConnector.reset();
}
@TestPropertySource(properties = "spring.rabbitmq.host=some_rabbit_host")
public static class WithRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsNull() {
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
private static final String URI = "https://username:[email protected]";
@Autowired
private Environment environment;
@Autowired
private ApplicationContext context;
@BeforeClass
public static void beforeClass() {
Mockito.when(MockCloudConnector.instance.isInMatchingCloud()).thenReturn(true);
Mockito.when(MockCloudConnector.instance.getServiceInfos()).thenReturn(Collections.singletonList(
new ConfigServerServiceInfo("config-server",
URI,
CLIENT_ID,
CLIENT_SECRET,
ACCESS_TOKEN_URI)));
}
@AfterClass
public static void afterClass() {
MockCloudConnector.reset();
}
@TestPropertySource(properties = "spring.rabbitmq.host=some_rabbit_host")
public static class WithRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsNull() {
|
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
|
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
|
@Test
public void springAutoConfigureExcludeIsNull() {
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
@Test
public void springAutoConfigureExcludeIsNull() {
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
|
assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
|
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
|
@Test
public void springAutoConfigureExcludeIsNull() {
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI);
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
@Test
public void springAutoConfigureExcludeIsNull() {
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI);
|
assertPropertyEquals(CLIENT_ID, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
|
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
|
public void springAutoConfigureExcludeIsNull() {
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI);
assertPropertyEquals(CLIENT_ID, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID);
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
public void springAutoConfigureExcludeIsNull() {
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI);
assertPropertyEquals(CLIENT_ID, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID);
|
assertPropertyEquals(CLIENT_SECRET, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET);
|
pivotal-cf/spring-cloud-services-connector
|
spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
|
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
|
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI);
assertPropertyEquals(CLIENT_ID, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID);
assertPropertyEquals(CLIENT_SECRET, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET);
|
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/MockCloudConnector.java
// public class MockCloudConnector implements CloudConnector {
//
// public static final CloudConnector instance = Mockito.mock(CloudConnector.class);
//
// public static void reset() {
// Mockito.reset(instance);
// }
//
// public boolean isInMatchingCloud() {
// return instance.isInMatchingCloud();
// }
//
// public ApplicationInstanceInfo getApplicationInstanceInfo() {
// return instance.getApplicationInstanceInfo();
// }
//
// public List<ServiceInfo> getServiceInfos() {
// return instance.getServiceInfos();
// }
// }
//
// Path: spring-cloud-services-connector-core/src/main/java/io/pivotal/spring/cloud/service/common/ConfigServerServiceInfo.java
// public class ConfigServerServiceInfo extends UriBasedServiceInfo {
// private String clientId;
// private String clientSecret;
// private String accessTokenUri;
//
// public ConfigServerServiceInfo(String id, String uriString, String clientId, String clientSecret, String accessTokenUri) {
// super(id, uriString);
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// this.accessTokenUri = accessTokenUri;
// }
//
// public String getClientId() {
// return clientId;
// }
//
// public String getClientSecret() {
// return clientSecret;
// }
//
// public String getAccessTokenUri() {
// return accessTokenUri;
// }
// }
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/config/java/ServiceInfoPropertySourceAdapter.java
// public static final String SPRING_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI = "spring.cloud.config.client.oauth2.accessTokenUri";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID = "spring.cloud.config.client.oauth2.clientId";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET = "spring.cloud.config.client.oauth2.clientSecret";
//
// Path: spring-cloud-services-spring-connector/src/main/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnector.java
// public static final String SPRING_CLOUD_CONFIG_URI = "spring.cloud.config.uri";
// Path: spring-cloud-services-spring-connector/src/test/java/io/pivotal/spring/cloud/service/config/ConfigServerServiceConnectorIntegrationTest.java
import java.util.Collections;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import io.pivotal.spring.cloud.MockCloudConnector;
import io.pivotal.spring.cloud.service.common.ConfigServerServiceInfo;
import static io.pivotal.spring.cloud.config.java.ServiceInfoPropertySourceAdapter.SPRING_AUTOCONFIGURE_EXCLUDE;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET;
import static io.pivotal.spring.cloud.service.config.ConfigServerServiceConnector.SPRING_CLOUD_CONFIG_URI;
import static org.junit.Assert.assertEquals;
assertPropertyEquals(null, SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
public static class WithoutRabbitBinding extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludeIsOnlyRabbitAutoConfig() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration",
SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@TestPropertySource(properties = "spring.autoconfigure.exclude=com.foo.Bar")
public static class WithoutRabbitBindingButWithExistingAutoConfigExcludes extends ConfigServerServiceConnectorIntegrationTest {
@Test
public void springAutoConfigureExcludePreservesExistingExcludes() {
assertPropertyEquals("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,com.foo.Bar", SPRING_AUTOCONFIGURE_EXCLUDE);
}
}
@Test
public void propertySourceIsAdded() {
assertPropertyEquals(URI, SPRING_CLOUD_CONFIG_URI);
assertPropertyEquals(CLIENT_ID, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_ID);
assertPropertyEquals(CLIENT_SECRET, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_CLIENT_SECRET);
|
assertPropertyEquals(ACCESS_TOKEN_URI, SPRING_CLOUD_CONFIG_OAUTH2_CLIENT_ACCESS_TOKEN_URI);
|
ehsane/rainbownlp
|
src/main/java/rainbownlp/machinelearning/LearnerCommon.java
|
// Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
//
// Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
|
import java.sql.SQLException;
import rainbownlp.util.ConfigurationUtil;
import rainbownlp.util.ConfigurationUtil.OperationMode;
|
package rainbownlp.machinelearning;
public class LearnerCommon {
public static void includeExamples(String updateTo) throws SQLException {
// if(Setting.Mode==OperationMode.EDGE)
// {
// RelationExampleTable.setTestAsTrain();
// RelationExampleTable.include(updateTo);
// }
// if(Setting.Mode==OperationMode.TRIGGER)
// {
// ArtifactExampleTable.setTestAsTrain();
// ArtifactExampleTable.include(updateTo);
// }
}
public static String[] getClassTitles() {
String[] class_titles = new String[1];
|
// Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public class ConfigurationUtil {
// public static final String RuleSureCorpus = "RuleSure";
// public static boolean SaveInGetInstance = true;
// static Properties configFile = new Properties();
// static boolean loadedRNLPConfig = false;
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// public static OperationMode Mode = OperationMode.TRIGGER;
// public static boolean TrainingMode = true;
// // This switch between using Development set or Test set for evaluation, set to true if you want to generate test submission files
// public static boolean ReleaseMode = false;
// public static int NotTriggerNumericValue = 10;
// public static int NotEdgeNumericValue = 9;
// public static int MinInstancePerLeaf;
// public static Double SVMCostParameter;
// public static Double SVMPolyCParameter;
// public static enum SVMKernels {
// Linear, //0: linear (default)
// Polynomial, //1: polynomial (s a*b+c)^d
// Radial, //2: radial basis function exp(-gamma ||a-b||^2)
// SigmoidTanh //3: sigmoid tanh(s a*b + c)
// };
// public static SVMKernels SVMKernel;
//
// public static boolean batchMode = false;
// public static int crossValidationFold;
// public static int crossFoldCurrent = 0;
//
// public static String[] getArrayValues(String key)
// {
// if(getValue(key)==null)
// return null;
// String[] arrayValues = getValue(key).split("\\|");
// return arrayValues;
// }
// public static void init()
// {
// if(!loadedRNLPConfig){
// Properties rnlpConfigFile = new Properties();
// try {
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream("configuration.conf");//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// rnlpConfigFile.load(config_file);
//
// configFile.putAll(rnlpConfigFile);
//
// MinInstancePerLeaf = Integer.parseInt(configFile.getProperty("MinInstancePerLeaf"));
// SVMCostParameter = Double.parseDouble(configFile.getProperty("SVMCostParameter"));
// SVMPolyCParameter = Double.parseDouble(configFile.getProperty("SVMPolyCParameter"));
// ReleaseMode = Boolean.parseBoolean(configFile.getProperty("ReleaseMode"));
// SVMKernel = SVMKernels.values()[Integer.parseInt(configFile.getProperty("SVMKernel"))];
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// }
//
// public static void init(String configurationFileName) throws IOException
// {
// init();
// configFile = new Properties();
// InputStream config_file =
// ConfigurationUtil.class.getClassLoader().
// getResourceAsStream(configurationFileName);//
// //Configuration.class.getClassLoader().getResourceAsStream("/configuration.properties");
// configFile.load(config_file);
// }
// public static void init(String configurationFileName, String hibernateConfigFile) throws IOException
// {
// init(configurationFileName);
// HibernateUtil.initialize("hibernate-oss.cfg.xml");
// }
// public static String getValue(String key){
// init();
// return configFile.getProperty(key);
// }
//
// public static int getValueInteger(String key) {
// String val = getValue(key);
// if(val==null) return 0;
// int result = Integer.parseInt(val);
// return result;
// }
//
// public static String getResourcePath(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResource(resourceName).getPath();
// }
//
// public static InputStream getResourceStream(String resourceName) {
// return ConfigurationUtil.class.getClassLoader().getResourceAsStream(resourceName);
// }
//
//
//
//
// }
//
// Path: src/main/java/rainbownlp/util/ConfigurationUtil.java
// public enum OperationMode
// {
// TRIGGER,
// EDGE,
// ARTIFACT
// }
// Path: src/main/java/rainbownlp/machinelearning/LearnerCommon.java
import java.sql.SQLException;
import rainbownlp.util.ConfigurationUtil;
import rainbownlp.util.ConfigurationUtil.OperationMode;
package rainbownlp.machinelearning;
public class LearnerCommon {
public static void includeExamples(String updateTo) throws SQLException {
// if(Setting.Mode==OperationMode.EDGE)
// {
// RelationExampleTable.setTestAsTrain();
// RelationExampleTable.include(updateTo);
// }
// if(Setting.Mode==OperationMode.TRIGGER)
// {
// ArtifactExampleTable.setTestAsTrain();
// ArtifactExampleTable.include(updateTo);
// }
}
public static String[] getClassTitles() {
String[] class_titles = new String[1];
|
if (ConfigurationUtil.getValue("RelationMode").equals("BioNLP")) {
|
ehsane/rainbownlp
|
src/main/java/rainbownlp/analyzer/sentenceclause/SentenceObject.java
|
// Path: src/main/java/rainbownlp/parser/DependencyLine.java
// public class DependencyLine {
// public String relationName;
// public String firstPart;
// public String secondPart;
// public int firstOffset;
// public int secondOffset;
// public boolean hasWord(String word) {
// if(firstPart.equals(word) ||
// secondPart.equals(word))
// return true;
// return false;
// }
// }
|
import java.util.ArrayList;
import rainbownlp.parser.DependencyLine;
|
package rainbownlp.analyzer.sentenceclause;
public class SentenceObject {
public String content;
public Clause clause;
public ArrayList<String> modifiers;
|
// Path: src/main/java/rainbownlp/parser/DependencyLine.java
// public class DependencyLine {
// public String relationName;
// public String firstPart;
// public String secondPart;
// public int firstOffset;
// public int secondOffset;
// public boolean hasWord(String word) {
// if(firstPart.equals(word) ||
// secondPart.equals(word))
// return true;
// return false;
// }
// }
// Path: src/main/java/rainbownlp/analyzer/sentenceclause/SentenceObject.java
import java.util.ArrayList;
import rainbownlp.parser.DependencyLine;
package rainbownlp.analyzer.sentenceclause;
public class SentenceObject {
public String content;
public Clause clause;
public ArrayList<String> modifiers;
|
public DependencyLine dependencyLine;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.