code
stringlengths 25
201k
| docstring
stringlengths 19
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
51
| path
stringlengths 11
314
| url
stringlengths 62
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
public JDBCStateRepository build() {
return new JDBCStateRepository(this);
}
|
Creates a {@link JDBCStateRepository} from the current configuration
|
build
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/repository/jdbc/JDBCStateRepository.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/repository/jdbc/JDBCStateRepository.java
|
Apache-2.0
|
private boolean columnExists(String column) throws SQLException {
return isSuccessful("SELECT " + column + " FROM %TABLE%");
}
|
Returns <code>true</code> if the given column exists in the features table.
@throws SQLException
|
columnExists
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/repository/jdbc/SchemaUpdater.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/repository/jdbc/SchemaUpdater.java
|
Apache-2.0
|
private boolean isSuccessful(String sql) throws SQLException {
Statement statement = connection.createStatement();
try {
statement.execute(substitute(sql));
} catch (SQLException e) {
return false;
} finally {
DbUtils.closeQuietly(statement);
}
return true;
}
|
Returns <code>true</code> if the supplied statement returned without any error
|
isSuccessful
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/repository/jdbc/SchemaUpdater.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/repository/jdbc/SchemaUpdater.java
|
Apache-2.0
|
private String substitute(String s) {
return s.replace("%TABLE%", tableName);
}
|
Replaces <code>%TABLE%</code> with the table name configured.
|
substitute
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/repository/jdbc/SchemaUpdater.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/repository/jdbc/SchemaUpdater.java
|
Apache-2.0
|
@Override
public FeatureUser getCurrentUser() {
return null;
}
|
This implementation of {@link UserProvider} can be used if user-dependent feature toggling isn't used at all.
@author Christian Kaltepoth
|
getCurrentUser
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/user/NoOpUserProvider.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/user/NoOpUserProvider.java
|
Apache-2.0
|
public SimpleFeatureUser setAttribute(String name, Object value) {
if (value != null) {
attributes.put(name, value);
} else {
attributes.remove(name);
}
return this;
}
|
This method can be used to set attributes of the user.
@param name The name of the attribute
@param value The value of the attribute
@return <code>this</code> for fluent object creation
|
setAttribute
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/user/SimpleFeatureUser.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/user/SimpleFeatureUser.java
|
Apache-2.0
|
@Override
public FeatureUser getCurrentUser() {
return user;
}
|
A very simple implementation of {@link UserProvider} which always returns the supplied user.
|
getCurrentUser
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/user/SingleUserProvider.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/user/SingleUserProvider.java
|
Apache-2.0
|
@Override
public FeatureUser getCurrentUser() {
AccessControlContext acc = AccessController.getContext();
if (acc != null) {
Subject subject = Subject.getSubject(acc);
if (subject != null) {
Iterator<Principal> iter = subject.getPrincipals().iterator();
if (iter.hasNext()) {
Principal principal = iter.next();
return new SimpleFeatureUser(principal.getName(), isFeatureAdmin(principal));
}
}
}
return null;
}
|
This implementation supports looking up the current user the JAAS AccessControlContext. The class currently doesn't support
determining whether a user is a feature admin and therefore always sets it to false. Overriding
{@link #isFeatureAdmin(String)} allows to change the default behavior.
@author Christian Kaltepoth
|
getCurrentUser
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/user/jaas/JAASUserProvider.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/user/jaas/JAASUserProvider.java
|
Apache-2.0
|
protected boolean isFeatureAdmin(Principal principal) {
return false;
}
|
Checks if the supplied user is a feature admin. The default implementation always returns <code>false</code>. Users can
overwrite this method to implement a different behavior.
@param principal The principal
@return <code>true</code> for feature admins, <code>false</code> otherwise
|
isFeatureAdmin
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/user/jaas/JAASUserProvider.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/user/jaas/JAASUserProvider.java
|
Apache-2.0
|
public static void bind(FeatureUser featureUser) {
if (featureUser != null && threadLocal.get() != null) {
throw new IllegalStateException("setFeatureUser() called for a "
+ "thread that already has one associated with it. It's likely that the FeatureUser "
+ "is not correctly removed from the thread before it is put back into the thread pool.");
}
threadLocal.set(featureUser);
}
|
Store the supplied FeatureUser in the thread context. After calling this method all calls of {@link #getCurrentUser()}
from the active thread will return this feature user. Please don't forget to call {@link #release()} before the thread is
put back to a thread pool to prevent memory leaks.
@param featureUser The feature user to store
|
bind
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/user/thread/ThreadLocalUserProvider.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/user/thread/ThreadLocalUserProvider.java
|
Apache-2.0
|
@Override
public FeatureUser getCurrentUser() {
return threadLocal.get();
}
|
Removes the user associated with the current thread from the thread's context. It's required to always call this method
before a thread is put back to a thread pool.
|
getCurrentUser
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/user/thread/ThreadLocalUserProvider.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/user/thread/ThreadLocalUserProvider.java
|
Apache-2.0
|
private static int hash(int h) {
// Spread bits to regularize both segment and index locations,
// using variant of single-word Wang/Jenkins hash.
h += (h << 15) ^ 0xffffcd7d;
h ^= (h >>> 10);
h += (h << 3);
h ^= (h >>> 6);
h += (h << 2) + (h << 14);
return h ^ (h >>> 16);
}
|
Applies a supplemental hash function to a given hashCode, which
defends against poor quality hash functions. This is critical
because ConcurrentReferenceHashMap uses power-of-two length hash tables,
that otherwise encounter collisions for hashCodes that do not
differ in lower or upper bits.
|
hash
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
void setTable(HashEntry<K,V>[] newTable) {
threshold = (int)(newTable.length * loadFactor);
table = newTable;
refQueue = new ReferenceQueue<Object>();
}
|
Sets table to new HashEntry array.
Call only while holding lock or in constructor.
|
setTable
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public boolean isEmpty() {
final Segment<K,V>[] segments = this.segments;
/*
* We keep track of per-segment modCounts to avoid ABA
* problems in which an element in one segment was added and
* in another removed during traversal, in which case the
* table was never actually empty at any point. Note the
* similar use of modCounts in the size() and containsValue()
* methods, which are the only other methods also susceptible
* to ABA problems.
*/
int[] mc = new int[segments.length];
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0)
return false;
else
mcsum += mc[i] = segments[i].modCount;
}
// If mcsum happens to be zero, then we know we got a snapshot
// before any modifications at all were made. This is
// probably common enough to bother tracking.
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
if (segments[i].count != 0 ||
mc[i] != segments[i].modCount)
return false;
}
}
return true;
}
|
Returns <tt>true</tt> if this map contains no key-value mappings.
@return <tt>true</tt> if this map contains no key-value mappings
|
isEmpty
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public int size() {
final Segment<K,V>[] segments = this.segments;
long sum = 0;
long check = 0;
int[] mc = new int[segments.length];
// Try a few times to get accurate count. On failure due to
// continuous async changes in table, resort to locking.
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
check = 0;
sum = 0;
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
sum += segments[i].count;
mcsum += mc[i] = segments[i].modCount;
}
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
check += segments[i].count;
if (mc[i] != segments[i].modCount) {
check = -1; // force retry
break;
}
}
}
if (check == sum)
break;
}
if (check != sum) { // Resort to locking all segments
sum = 0;
for (int i = 0; i < segments.length; ++i)
segments[i].lock();
for (int i = 0; i < segments.length; ++i)
sum += segments[i].count;
for (int i = 0; i < segments.length; ++i)
segments[i].unlock();
}
if (sum > Integer.MAX_VALUE)
return Integer.MAX_VALUE;
else
return (int)sum;
}
|
Returns the number of key-value mappings in this map. If the
map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
<tt>Integer.MAX_VALUE</tt>.
@return the number of key-value mappings in this map
|
size
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public V get(Object key) {
int hash = hashOf(key);
return segmentFor(hash).get(key, hash);
}
|
Returns the value to which the specified key is mapped,
or {@code null} if this map contains no mapping for the key.
<p>More formally, if this map contains a mapping from a key
{@code k} to a value {@code v} such that {@code key.equals(k)},
then this method returns {@code v}; otherwise it returns
{@code null}. (There can be at most one such mapping.)
@throws NullPointerException if the specified key is null
|
get
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public boolean containsKey(Object key) {
int hash = hashOf(key);
return segmentFor(hash).containsKey(key, hash);
}
|
Tests if the specified object is a key in this table.
@param key possible key
@return <tt>true</tt> if and only if the specified object
is a key in this table, as determined by the
<tt>equals</tt> method; <tt>false</tt> otherwise.
@throws NullPointerException if the specified key is null
|
containsKey
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public boolean containsValue(Object value) {
if (value == null)
throw new NullPointerException();
// See explanation of modCount use above
final Segment<K,V>[] segments = this.segments;
int[] mc = new int[segments.length];
// Try a few times without locking
for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
int sum = 0;
int mcsum = 0;
for (int i = 0; i < segments.length; ++i) {
int c = segments[i].count;
mcsum += mc[i] = segments[i].modCount;
if (segments[i].containsValue(value))
return true;
}
boolean cleanSweep = true;
if (mcsum != 0) {
for (int i = 0; i < segments.length; ++i) {
int c = segments[i].count;
if (mc[i] != segments[i].modCount) {
cleanSweep = false;
break;
}
}
}
if (cleanSweep)
return false;
}
// Resort to locking all segments
for (int i = 0; i < segments.length; ++i)
segments[i].lock();
boolean found = false;
try {
for (int i = 0; i < segments.length; ++i) {
if (segments[i].containsValue(value)) {
found = true;
break;
}
}
} finally {
for (int i = 0; i < segments.length; ++i)
segments[i].unlock();
}
return found;
}
|
Returns <tt>true</tt> if this map maps one or more keys to the
specified value. Note: This method requires a full internal
traversal of the hash table, and so is much slower than
method <tt>containsKey</tt>.
@param value value whose presence in this map is to be tested
@return <tt>true</tt> if this map maps one or more keys to the
specified value
@throws NullPointerException if the specified value is null
|
containsValue
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public boolean contains(Object value) {
return containsValue(value);
}
|
Legacy method testing if some key maps into the specified value
in this table. This method is identical in functionality to
{@link #containsValue}, and exists solely to ensure
full compatibility with class {@link java.util.Hashtable},
which supported this method prior to introduction of the
Java Collections framework.
@param value a value to search for
@return <tt>true</tt> if and only if some key maps to the
<tt>value</tt> argument in this table as
determined by the <tt>equals</tt> method;
<tt>false</tt> otherwise
@throws NullPointerException if the specified value is null
|
contains
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
|
Copies all of the mappings from the specified map to this one.
These mappings replace any mappings that this map had for any of the
keys currently in the specified map.
@param m mappings to be stored in this map
|
putAll
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public V remove(Object key) {
int hash = hashOf(key);
return segmentFor(hash).remove(key, hash, null, false);
}
|
Removes the key (and its corresponding value) from this map.
This method does nothing if the key is not in the map.
@param key the key that needs to be removed
@return the previous value associated with <tt>key</tt>, or
<tt>null</tt> if there was no mapping for <tt>key</tt>
@throws NullPointerException if the specified key is null
|
remove
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public boolean remove(Object key, Object value) {
int hash = hashOf(key);
if (value == null)
return false;
return segmentFor(hash).remove(key, hash, value, false) != null;
}
|
{@inheritDoc}
@throws NullPointerException if the specified key is null
|
remove
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public boolean replace(K key, V oldValue, V newValue) {
if (oldValue == null || newValue == null)
throw new NullPointerException();
int hash = hashOf(key);
return segmentFor(hash).replace(key, hash, oldValue, newValue);
}
|
{@inheritDoc}
@throws NullPointerException if any of the arguments are null
|
replace
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public void clear() {
for (int i = 0; i < segments.length; ++i)
segments[i].clear();
}
|
Removes all of the mappings from this map.
|
clear
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public void purgeStaleEntries() {
for (int i = 0; i < segments.length; ++i)
segments[i].removeStale();
}
|
Removes any stale entries whose keys have been finalized. Use of this
method is normally not necessary since stale entries are automatically
removed lazily, when blocking operations are required. However, there
are some cases where this operation should be performed eagerly, such
as cleaning up old references to a ClassLoader in a multi-classloader
environment.
Note: this method will acquire locks, one at a time, across all segments
of this table, so if it is to be used, it should be used sparingly.
|
purgeStaleEntries
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null) ? ks : (keySet = new KeySet());
}
|
Returns a {@link Set} view of the keys contained in this map.
The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. The set supports element
removal, which removes the corresponding mapping from this map,
via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
<tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
operations. It does not support the <tt>add</tt> or
<tt>addAll</tt> operations.
<p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
that will never throw {@link ConcurrentModificationException},
and guarantees to traverse elements as they existed upon
construction of the iterator, and may (but is not guaranteed to)
reflect any modifications subsequent to construction.
|
keySet
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null) ? vs : (values = new Values());
}
|
Returns a {@link Collection} view of the values contained in this map.
The collection is backed by the map, so changes to the map are
reflected in the collection, and vice-versa. The collection
supports element removal, which removes the corresponding
mapping from this map, via the <tt>Iterator.remove</tt>,
<tt>Collection.remove</tt>, <tt>removeAll</tt>,
<tt>retainAll</tt>, and <tt>clear</tt> operations. It does not
support the <tt>add</tt> or <tt>addAll</tt> operations.
<p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
that will never throw {@link ConcurrentModificationException},
and guarantees to traverse elements as they existed upon
construction of the iterator, and may (but is not guaranteed to)
reflect any modifications subsequent to construction.
|
values
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es = entrySet;
return (es != null) ? es : (entrySet = new EntrySet());
}
|
Returns a {@link Set} view of the mappings contained in this map.
The set is backed by the map, so changes to the map are
reflected in the set, and vice-versa. The set supports element
removal, which removes the corresponding mapping from the map,
via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
<tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
operations. It does not support the <tt>add</tt> or
<tt>addAll</tt> operations.
<p>The view's <tt>iterator</tt> is a "weakly consistent" iterator
that will never throw {@link ConcurrentModificationException},
and guarantees to traverse elements as they existed upon
construction of the iterator, and may (but is not guaranteed to)
reflect any modifications subsequent to construction.
|
entrySet
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public Enumeration<K> keys() {
return new KeyIterator();
}
|
Returns an enumeration of the keys in this table.
@return an enumeration of the keys in this table
@see #keySet()
|
keys
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
s.defaultReadObject();
// Initialize each segment to be minimally sized, and let grow.
for (int i = 0; i < segments.length; ++i) {
segments[i].setTable(new HashEntry[1]);
}
// Read the keys and values, and put the mappings in the table
for (;;) {
K key = (K) s.readObject();
V value = (V) s.readObject();
if (key == null)
break;
put(key, value);
}
}
|
Reconstitute the <tt>ConcurrentReferenceHashMap</tt> instance from a
stream (i.e., deserialize it).
@param s the stream
|
readObject
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/ConcurrentReferenceHashMap.java
|
Apache-2.0
|
public static String[] getFeatureAttribute(Annotation annotation) {
try {
// only annotations which are annotated with @FeatureAttribute are interesting
FeatureAttribute details = annotation.annotationType().getAnnotation(FeatureAttribute.class);
if (details != null) {
// this is the name of the feature attribute
String attributeName = details.value();
// find the method to invoke on the annotation to read the value of the feature attribute
Method method = annotation.getClass().getMethod(details.annotationAttribute());
if (method != null) {
String attributeValue = method.invoke(annotation).toString();
return new String[]{attributeName, attributeValue};
}
}
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
return null;
}
|
Checks whether the supplied annotation specifies a feature attribute. If so, it returns an String array containing the
name of the attribute at the first and the value at the second position. Returns <code>null</code> if no attribute was
found.
|
getFeatureAttribute
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/FeatureAnnotations.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/FeatureAnnotations.java
|
Apache-2.0
|
public static void close(InputStream s) {
if (s != null) {
try {
s.close();
} catch (IOException e) {
// ignore
}
}
}
|
Provides utility methods for working with I/O streams.
Based on com.google.common.io.* from com.google.guava:17.0
@author Chris Nokleberg
@author Colin Decker
@author Bin Zhu
|
close
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/IOUtils.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/IOUtils.java
|
Apache-2.0
|
public static long copy(InputStream from, OutputStream to) throws IOException {
checkNotNull(from);
checkNotNull(to);
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
|
Copies all bytes from the input stream to the output stream.
Does not close or flush either stream.
@param from the input stream to read from
@param to the output stream to write to
@return the number of bytes copied
@throws IOException if an I/O error occurs
|
copy
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/IOUtils.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/IOUtils.java
|
Apache-2.0
|
public static String toString(Readable r) throws IOException {
StringBuilder sb = new StringBuilder();
copy(r, sb);
return sb.toString();
}
|
Reads all characters from a {@link Readable} object into a {@link String}.
Does not close the {@code Readable}.
@param r the object to read from
@return a string containing all the characters
@throws IOException if an I/O error occurs
|
toString
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/IOUtils.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/IOUtils.java
|
Apache-2.0
|
public static long copy(Readable from, Appendable to) throws IOException {
checkNotNull(from);
checkNotNull(to);
CharBuffer buf = CharBuffer.allocate(BUF_SIZE);
long total = 0;
while (from.read(buf) != -1) {
buf.flip();
to.append(buf);
total += buf.remaining();
buf.clear();
}
return total;
}
|
Copies all characters between the {@link Readable} and {@link Appendable}
objects. Does not close or flush either object.
@param from the object to read from
@param to the object to write to
@return the number of characters copied
@throws IOException if an I/O error occurs
|
copy
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/IOUtils.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/IOUtils.java
|
Apache-2.0
|
private static String simpleName(Class<?> clazz) {
String name = clazz.getName();
// the nth anonymous class has a class name ending in "Outer$n"
// and local inner classes have names ending in "Outer.$1Inner"
name = name.replaceAll("\\$[0-9]+", "\\$");
// we want the name of the inner class all by its lonesome
int start = name.lastIndexOf('$');
// if this isn't an inner class, just find the start of the
// top level class name.
if (start == -1) {
start = name.lastIndexOf('.');
}
return name.substring(start + 1);
}
|
{@link Class#getSimpleName()} is not GWT compatible yet, so we
provide our own implementation.
|
simpleName
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/MoreObjects.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/MoreObjects.java
|
Apache-2.0
|
public static <T> T firstNonNull(T first, T second) {
return first != null ? first : checkNotNull(second);
}
|
Returns the first of two given parameters that is not {@code null}, if
either is, or otherwise throws a {@link NullPointerException}.
@return {@code first} if {@code first} is not {@code null}, or
{@code second} if {@code first} is {@code null} and {@code second} is
not {@code null}
@throws NullPointerException if both {@code first} and {@code second} were
{@code null}
@since 3.0
|
firstNonNull
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/MoreObjects.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/MoreObjects.java
|
Apache-2.0
|
public ToStringHelper add(String name, Object value) {
return addHolder(name, value);
}
|
Adds a name/value pair to the formatted output in {@code name=value}
format. If {@code value} is {@code null}, the string {@code "null"}
is used in which case this
name/value pair will not be added.
|
add
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/MoreObjects.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/MoreObjects.java
|
Apache-2.0
|
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
|
Ensures the truth of an expression involving one or more parameters to the calling method.
@param expression a boolean expression
@throws IllegalArgumentException if {@code expression} is false
|
checkArgument
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
|
Ensures the truth of an expression involving one or more parameters to the calling method.
@param expression a boolean expression
@param errorMessage the exception message to use if the check fails; will be converted to a
string using {@link String#valueOf(Object)}
@throws IllegalArgumentException if {@code expression} is false
|
checkArgument
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
public static void checkArgument(boolean expression,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
|
Ensures the truth of an expression involving one or more parameters to the calling method.
@param expression a boolean expression
@param errorMessageTemplate a template for the exception message should the check fail. The
message is formed by replacing each {@code %s} placeholder in the template with an
argument. These are matched by position - the first {@code %s} gets {@code
errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
in square braces. Unmatched placeholders will be left as-is.
@param errorMessageArgs the arguments to be substituted into the message template. Arguments
are converted to strings using {@link String#valueOf(Object)}.
@throws IllegalArgumentException if {@code expression} is false
@throws NullPointerException if the check fails and either {@code errorMessageTemplate} or
{@code errorMessageArgs} is null (don't let this happen)
|
checkArgument
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
|
Ensures the truth of an expression involving the state of the calling instance, but not
involving any parameters to the calling method.
@param expression a boolean expression
@throws IllegalStateException if {@code expression} is false
|
checkState
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
|
Ensures that an object reference passed as a parameter to the calling method is not null.
@param reference an object reference
@return the non-null reference that was validated
@throws NullPointerException if {@code reference} is null
|
checkNotNull
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
|
Ensures that an object reference passed as a parameter to the calling method is not null.
@param reference an object reference
@param errorMessage the exception message to use if the check fails; will be converted to a
string using {@link String#valueOf(Object)}
@return the non-null reference that was validated
@throws NullPointerException if {@code reference} is null
|
checkNotNull
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
public static <T> T checkNotNull(T reference,
String errorMessageTemplate,
Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
|
Ensures that an object reference passed as a parameter to the calling method is not null.
@param reference an object reference
@param errorMessageTemplate a template for the exception message should the check fail. The
message is formed by replacing each {@code %s} placeholder in the template with an
argument. These are matched by position - the first {@code %s} gets {@code
errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message
in square braces. Unmatched placeholders will be left as-is.
@param errorMessageArgs the arguments to be substituted into the message template. Arguments
are converted to strings using {@link String#valueOf(Object)}.
@return the non-null reference that was validated
@throws NullPointerException if {@code reference} is null
|
checkNotNull
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template, templateStart, placeholderStart);
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
|
Substitutes each {@code %s} in {@code template} with an argument. These are matched by
position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than
placeholders, the unmatched arguments will be appended to the end of the formatted message in
square braces.
@param template a non-null string containing 0 or more {@code %s} placeholders.
@param args the arguments to be substituted into the message template. Arguments are converted
to strings using {@link String#valueOf(Object)}. Arguments can be null.
|
format
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Preconditions.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Preconditions.java
|
Apache-2.0
|
public static <E> Collection<E> get(Class<? extends E> service) {
Iterator<? extends E> implementations = ServiceLoader.load(service).iterator();
Collection<E> result = new ArrayList<E>();
while (implementations.hasNext()) {
result.add(implementations.next());
}
return result;
}
|
Lookup implementations of the supplied SPI. Please note that the order in which the implementations will occur in the
collection is not specified.
|
get
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Services.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Services.java
|
Apache-2.0
|
public static <E extends Weighted> List<E> getSorted(Class<? extends E> service) {
List<E> result = new ArrayList<E>(get(service));
result.sort(WEIGHTED_COMPARATOR);
return result;
}
|
Lookup implementations of the supplied SPI. This method requires the SPI to extends {@link Weighted} and therefore is
able to return a sorted list of implementations.
|
getSorted
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Services.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Services.java
|
Apache-2.0
|
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
|
<p>
Returns whether the specified string is empty while remaining null-safe.
</p>
@param s
the string to be checked (may be {@literal null})
@return {@literal true} if {@code s} is either {@literal null} or contains no characters.
|
isEmpty
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Strings.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Strings.java
|
Apache-2.0
|
public static String trim(String s) {
return s != null ? s.trim() : null;
}
|
<p>
Trims the specified string while remaining null-safe.
</p>
@param s
the string to be trimmed (may be {@literal null})
@return The trimmed {@code s} or {@literal null} if {@code s} is {@literal null}.
|
trim
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Strings.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Strings.java
|
Apache-2.0
|
public static Boolean toBoolean(String s) {
String value = trimToNull(s);
if (value == null) {
return null;
}
value = value.toLowerCase();
if (trueValues.contains(value)) {
return Boolean.TRUE;
}
if (falseValues.contains(value)) {
return Boolean.FALSE;
}
throw new IllegalArgumentException("Invalid boolean value '" + s + "'");
}
|
<p>
Attempts to return the best boolean representation for the specified string while remaining null-safe and
ignoring any leading/trailing whitespace as well as case.
</p>
<p>
This method simply uses a set of predefined values that it compares {@code s} to in order to determine the best
{@code Boolean} representation. If {@code s} does not fall into either category, it is considered invalid and
will result in an {@code IllegalArgumentException} being thrown.
</p>
@param s
the string to be converted into a {@code Boolean}
@return The {@code Boolean} representation of {@code s} or {@literal null} if {@code s} is {@literal null}.
@throws IllegalArgumentException
If {@code s} is non-{@literal null} <b>and</b> does not match any of the predefined values.
|
toBoolean
|
java
|
togglz/togglz
|
core/src/main/java/org/togglz/core/util/Strings.java
|
https://github.com/togglz/togglz/blob/master/core/src/main/java/org/togglz/core/util/Strings.java
|
Apache-2.0
|
private String getMachineIP() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
Enumeration<InetAddress> addresses = interfaces.nextElement().getInetAddresses();
while (addresses.hasMoreElements()) {
String hostAddress = addresses.nextElement().getHostAddress();
if (hostAddress != null) {
return hostAddress.trim();
}
}
}
}
return null;
} catch (SocketException e) {
return "<no-ip>";
}
}
|
Returns the first IP of the current machine
|
getMachineIP
|
java
|
togglz/togglz
|
core/src/test/java/org/togglz/core/activation/IPActivationStrategyTest.java
|
https://github.com/togglz/togglz/blob/master/core/src/test/java/org/togglz/core/activation/IPActivationStrategyTest.java
|
Apache-2.0
|
@BeforeEach
void before() {
FeatureManager featureManager = new FeatureManagerBuilder()
.featureEnum(MyFeature.class)
.stateRepository(new InMemoryStateRepository())
.userProvider(new NoOpUserProvider())
.build();
ThreadLocalFeatureManagerProvider.bind(featureManager);
}
|
Binds a FeatureManager to the thread before starting each test
|
before
|
java
|
togglz/togglz
|
core/src/test/java/org/togglz/core/context/ThreadLocalFeatureManagerProviderTest.java
|
https://github.com/togglz/togglz/blob/master/core/src/test/java/org/togglz/core/context/ThreadLocalFeatureManagerProviderTest.java
|
Apache-2.0
|
public static Builder newBuilder() {
return new Builder();
}
|
Creates a new builder for creating a {@link HazelcastStateRepository}.
|
newBuilder
|
java
|
togglz/togglz
|
hazelcast/src/main/java/org/togglz/hazelcast/HazelcastStateRepository.java
|
https://github.com/togglz/togglz/blob/master/hazelcast/src/main/java/org/togglz/hazelcast/HazelcastStateRepository.java
|
Apache-2.0
|
public static Builder newBuilder(String mapName) {
return new Builder(mapName);
}
|
Creates a new builder for creating a {@link HazelcastStateRepository}.
@param mapName
the Hazelcast map name
|
newBuilder
|
java
|
togglz/togglz
|
hazelcast/src/main/java/org/togglz/hazelcast/HazelcastStateRepository.java
|
https://github.com/togglz/togglz/blob/master/hazelcast/src/main/java/org/togglz/hazelcast/HazelcastStateRepository.java
|
Apache-2.0
|
public Builder mapName(String mapName) {
this.mapName = mapName;
return this;
}
|
Sets the Hazelcast map name to use.
@param mapName
the Hazelcast map name to use for feature state store
|
mapName
|
java
|
togglz/togglz
|
hazelcast/src/main/java/org/togglz/hazelcast/HazelcastStateRepository.java
|
https://github.com/togglz/togglz/blob/master/hazelcast/src/main/java/org/togglz/hazelcast/HazelcastStateRepository.java
|
Apache-2.0
|
public static Builder newBuilder(MongoClient client, String dbname) {
return new Builder(client, dbname);
}
|
Creates a new builder for creating a {@link MongoStateRepository}.
@param client the client instance to use for connecting to MongoDB
@param dbname the database name used for storing features state.
|
newBuilder
|
java
|
togglz/togglz
|
mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
https://github.com/togglz/togglz/blob/master/mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
Apache-2.0
|
public Builder collection(String collection) {
this.collection = collection;
return this;
}
|
The name of the collection used by the repository to store the feature state. The default is <code>togglz</code>.
@param collection The name of the collection to use
|
collection
|
java
|
togglz/togglz
|
mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
https://github.com/togglz/togglz/blob/master/mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
Apache-2.0
|
public Builder writeConcern(WriteConcern writeConcern) {
this.writeConcern = writeConcern;
return this;
}
|
The {@link WriteConcern} used when accessing the database. By default <code>ACKNOWLEDGED</code> will be used.
@param writeConcern The {@link WriteConcern} to use
|
writeConcern
|
java
|
togglz/togglz
|
mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
https://github.com/togglz/togglz/blob/master/mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
Apache-2.0
|
public MongoStateRepository build() {
return new MongoStateRepository(this);
}
|
Creates a new {@link MongoStateRepository} using the current settings.
|
build
|
java
|
togglz/togglz
|
mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
https://github.com/togglz/togglz/blob/master/mongodb/src/main/java/org/togglz/mongodb/MongoStateRepository.java
|
Apache-2.0
|
public Builder lettucePool(final GenericObjectPool<StatefulConnection<String, String>> lettucePool) {
this.lettucePool = lettucePool;
return this;
}
|
Sets the Lettuce Pool.
@param lettucePool the Lettuce Pool {@link GenericObjectPool}
|
lettucePool
|
java
|
togglz/togglz
|
redis/src/main/java/org/togglz/redis/RedisLettuceStateRepository.java
|
https://github.com/togglz/togglz/blob/master/redis/src/main/java/org/togglz/redis/RedisLettuceStateRepository.java
|
Apache-2.0
|
public RedisLettuceStateRepository build() {
return new RedisLettuceStateRepository(this);
}
|
Creates a new {@link RedisLettuceStateRepository} using the current settings.
|
build
|
java
|
togglz/togglz
|
redis/src/main/java/org/togglz/redis/RedisLettuceStateRepository.java
|
https://github.com/togglz/togglz/blob/master/redis/src/main/java/org/togglz/redis/RedisLettuceStateRepository.java
|
Apache-2.0
|
public Builder jedisPool(final Pool<Jedis> jedisPool) {
this.jedisPool = jedisPool;
return this;
}
|
Sets the Jedis Pool.
@param jedisPool the Jedis Pool {@link JedisPool}
|
jedisPool
|
java
|
togglz/togglz
|
redis/src/main/java/org/togglz/redis/RedisStateRepository.java
|
https://github.com/togglz/togglz/blob/master/redis/src/main/java/org/togglz/redis/RedisStateRepository.java
|
Apache-2.0
|
public RedisStateRepository build() {
return new RedisStateRepository(this);
}
|
Creates a new {@link RedisStateRepository} using the current settings.
|
build
|
java
|
togglz/togglz
|
redis/src/main/java/org/togglz/redis/RedisStateRepository.java
|
https://github.com/togglz/togglz/blob/master/redis/src/main/java/org/togglz/redis/RedisStateRepository.java
|
Apache-2.0
|
@Override
public FeatureUser getCurrentUser() {
HttpServletRequest request = HttpServletRequestHolder.get();
if (request == null) {
throw new IllegalStateException(
"Could not get request from HttpServletRequestHolder. Did you configure the TogglzFilter correctly?");
}
Principal principal = request.getUserPrincipal();
if (principal == null) {
return null;
}
boolean featureAdmin = request.isUserInRole(featureAdminRole);
return new SimpleFeatureUser(principal.getName(), featureAdmin);
}
|
This constructor requires you to supply the name of the role that identifies users to be feature admins.
@param featureAdminRole the feature admin role name
|
getCurrentUser
|
java
|
togglz/togglz
|
servlet/src/main/java/org/togglz/servlet/user/ServletUserProvider.java
|
https://github.com/togglz/togglz/blob/master/servlet/src/main/java/org/togglz/servlet/user/ServletUserProvider.java
|
Apache-2.0
|
public static void bind(HttpServletRequest request) {
if (request != null && threadLocal.get() != null) {
throw new IllegalStateException("HttpServletRequestHolder.bind() called for a "
+ "thread that already has a request associated with it. It's likely that the request "
+ "was not correctly removed from the thread before it is put back into the thread pool.");
}
threadLocal.set(request);
}
|
Associate the request with the current thread.
|
bind
|
java
|
togglz/togglz
|
servlet/src/main/java/org/togglz/servlet/util/HttpServletRequestHolder.java
|
https://github.com/togglz/togglz/blob/master/servlet/src/main/java/org/togglz/servlet/util/HttpServletRequestHolder.java
|
Apache-2.0
|
public static HttpServletRequest get() {
return threadLocal.get();
}
|
Remove the request that is currently associated with the current thread.
|
get
|
java
|
togglz/togglz
|
servlet/src/main/java/org/togglz/servlet/util/HttpServletRequestHolder.java
|
https://github.com/togglz/togglz/blob/master/servlet/src/main/java/org/togglz/servlet/util/HttpServletRequestHolder.java
|
Apache-2.0
|
@Override
public FeatureUser getCurrentUser() {
// will always return a result
Subject subject = SecurityUtils.getSubject();
// only allow authenticated user
if (subject.isAuthenticated()) {
return new SimpleFeatureUser(subject.getPrincipal().toString(), subject.hasRole(featureAdminRole));
}
// user is not authenticated
return null;
}
|
Constructor for the provider.
@param featureAdminRole The role identifier to check whether the users are feature admins.
|
getCurrentUser
|
java
|
togglz/togglz
|
shiro/src/main/java/org/togglz/shiro/ShiroUserProvider.java
|
https://github.com/togglz/togglz/blob/master/shiro/src/main/java/org/togglz/shiro/ShiroUserProvider.java
|
Apache-2.0
|
public NotificationConfigurationBuilder withMessageFormat(String messageFormat) {
this.messageFormat = messageFormat;
return this;
}
|
@param messageFormat custom replacement for default org.togglz.slack.notification.NotificationComposer.DEFAULT_MESSAGE_FORMAT
|
withMessageFormat
|
java
|
togglz/togglz
|
slack/src/main/java/org/togglz/slack/config/NotificationConfigurationBuilder.java
|
https://github.com/togglz/togglz/blob/master/slack/src/main/java/org/togglz/slack/config/NotificationConfigurationBuilder.java
|
Apache-2.0
|
public NotificationConfigurationBuilder withStatesIcons(String enabled, String disabled) {
this.statesIcons = Arrays.asList(enabled, disabled);
return this;
}
|
@param enabled icon name, eg. green_apple
@param disabled icon name, eg. apple
|
withStatesIcons
|
java
|
togglz/togglz
|
slack/src/main/java/org/togglz/slack/config/NotificationConfigurationBuilder.java
|
https://github.com/togglz/togglz/blob/master/slack/src/main/java/org/togglz/slack/config/NotificationConfigurationBuilder.java
|
Apache-2.0
|
public String format(String text) {
return Strings.isBlank(text) ? "" : concat(tag, text, tag);
}
|
https://api.slack.com/docs/message-formatting#message_formatting
|
format
|
java
|
togglz/togglz
|
slack/src/main/java/org/togglz/slack/notification/Markdown.java
|
https://github.com/togglz/togglz/blob/master/slack/src/main/java/org/togglz/slack/notification/Markdown.java
|
Apache-2.0
|
public static String link(String url, String name) {
String urlText = Strings.isNotBlank(url) ? url.trim() : "";
if (!urlText.isEmpty()) {
String nameText = Strings.isNotBlank(name) ? name : urlText;
return concat("<", urlText, "|", nameText, ">");
} else {
return name;
}
}
|
https://api.slack.com/docs/message-formatting#linking_to_urls
|
link
|
java
|
togglz/togglz
|
slack/src/main/java/org/togglz/slack/notification/Markdown.java
|
https://github.com/togglz/togglz/blob/master/slack/src/main/java/org/togglz/slack/notification/Markdown.java
|
Apache-2.0
|
@WriteOperation
public TogglzFeature setFeatureState(@Selector String name, @Nullable Boolean enabled,
@Nullable String strategy, @Nullable String parameters) {
final Feature feature = findFeature(name);
if (feature == null) {
throw new IllegalArgumentException("Could not find feature with name " + name);
}
Map<String, String> parametersMap = parseParameterMap(parameters);
FeatureState featureState = changeFeatureStatus(feature, enabled, strategy, parametersMap);
FeatureMetaData metaData = this.featureManager.getMetaData(feature);
return new TogglzFeature(feature, featureState, new TogglzFeatureMetaData(metaData));
}
|
Allows to change the state of toggles via http post.
@param name the name of the toggle/feature
@param enabled the name of the field containing the toggle/feature status
@param strategy the ID of the activation strategy to use
@param parameters activation strategy parameters as comma separated list of key=value pairs
|
setFeatureState
|
java
|
togglz/togglz
|
spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/TogglzEndpoint.java
|
https://github.com/togglz/togglz/blob/master/spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/TogglzEndpoint.java
|
Apache-2.0
|
@WriteOperation
public WebEndpointResponse<TogglzFeature> setFeatureState(@Selector String name, @Nullable Boolean enabled,
@Nullable String strategy, @Nullable String parameters) {
Feature feature = findFeature(name);
if (feature == null) {
return new WebEndpointResponse<>(WebEndpointResponse.STATUS_NOT_FOUND);
}
try {
Map<String, String> parametersMap = parseParameterMap(parameters);
FeatureState featureState = changeFeatureStatus(feature, enabled, strategy, parametersMap);
FeatureMetaData metaData = this.featureManager.getMetaData(feature);
return new WebEndpointResponse<>(new TogglzFeature(feature, featureState, new TogglzFeatureMetaData(metaData)));
} catch (IllegalArgumentException exception) {
log.debug("Illegal params format in togglz endpoint.", exception);
return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST);
}
}
|
Extension to the Togglz endpoint for HTTP so the status coddes for write operations are correct.
|
setFeatureState
|
java
|
togglz/togglz
|
spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/TogglzEndpointWebExtension.java
|
https://github.com/togglz/togglz/blob/master/spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/TogglzEndpointWebExtension.java
|
Apache-2.0
|
public Properties getFeatureProperties() {
Properties properties = new Properties();
for (String name : features.keySet()) {
properties.setProperty(name, features.get(name).spec());
}
return properties;
}
|
The configured features in a format that can be consumed by a
PropertyFeatureProvider.
@return features in the right format.
|
getFeatureProperties
|
java
|
togglz/togglz
|
spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/autoconfigure/TogglzProperties.java
|
https://github.com/togglz/togglz/blob/master/spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/autoconfigure/TogglzProperties.java
|
Apache-2.0
|
@Override
public Set<IProcessor> getProcessors(final String dialectPrefix) {
final Set<IProcessor> processors = new LinkedHashSet<IProcessor>();
processors.add(new FeatureActiveAttrProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new FeatureInactiveAttrProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix));
return processors;
}
|
Dialect for Thymeleaf that allows to show/hide DOM containers based on features state. In Order to use it, add an
instance of the dialect to your via {@link TemplateEngine}. The dialect uses the default prefix <code>togglz</code>.
@author Hendrik Heneke
@since 1.0.0
@see FeatureActiveAttrProcessor
@see FeatureInactiveAttrProcessor
|
getProcessors
|
java
|
togglz/togglz
|
spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/thymeleaf/TogglzDialect.java
|
https://github.com/togglz/togglz/blob/master/spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/thymeleaf/TogglzDialect.java
|
Apache-2.0
|
@Override
protected boolean isVisible(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) {
return determineFeatureState(context, attributeValue, false);
}
|
Processor for the <code>active</code> attribute in {@link TogglzDialect}. It shows or hides the given DOM container
based on feature state: <br>
<br>
<pre>
<span togglz:active="FEATURE">
Only visible when FEATURE is active.
</span>
</pre>
Features may also be specified dynamically by using expressions:<br>
<br>
<pre>
<span togglz:active="${feature}">
Only visible when feature resolved by evaluating ${feature} is active.
</span>
</pre>
When using Thymeleaf 2.0.x, literal feature names have to be quoted with single quotes. Thymeleaf from 2.1 onward
supports unquoted string literals.
@author Hendrik Heneke
@since 1.0.0
|
isVisible
|
java
|
togglz/togglz
|
spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/thymeleaf/processor/FeatureActiveAttrProcessor.java
|
https://github.com/togglz/togglz/blob/master/spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/thymeleaf/processor/FeatureActiveAttrProcessor.java
|
Apache-2.0
|
@Override
protected boolean isVisible(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue) {
return !determineFeatureState(context, attributeValue, true);
}
|
Processor for the <code>inactive</code> attribute in {@link TogglzDialect}. It shows or hides the given DOM container
based on feature state: <br>
<br>
<pre>
<span togglz:inactive="FEATURE">
Only visible when FEATURE is inactive.
</span>
</pre>
Features may also be specified dynamically by using expressions:<br>
<br>
<pre>
<span togglz:inactive="${feature}">
Only visible when feature resolved by evaluating ${feature} is inactive.
</span>
</pre>
When using Thymeleaf 2.0.x, literal feature names have to be quoted with single quotes. Thymeleaf from 2.1 onward
supports unquoted string literals.
@author Hendrik Heneke
@since 1.0.1
|
isVisible
|
java
|
togglz/togglz
|
spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/thymeleaf/processor/FeatureInactiveAttrProcessor.java
|
https://github.com/togglz/togglz/blob/master/spring-boot/autoconfigure/src/main/java/org/togglz/spring/boot/actuate/thymeleaf/processor/FeatureInactiveAttrProcessor.java
|
Apache-2.0
|
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent && filter.test((ContextRefreshedEvent) event)) {
if (ContextClassLoaderApplicationContextHolder.get() != null) {
log.warn("ApplicationContext already bound to current context class loader, releasing it first");
ContextClassLoaderApplicationContextHolder.release();
}
ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
ContextClassLoaderApplicationContextHolder.bind(applicationContext);
} else if (event instanceof ContextClosedEvent) {
ContextClassLoaderApplicationContextHolder.release();
}
}
|
{@link ApplicationListener} that binds the {@link ApplicationContext}
to the Togglz {@link ContextClassLoaderApplicationContextHolder}.
@author Marcel Overdijk
|
onApplicationEvent
|
java
|
togglz/togglz
|
spring-core/src/main/java/org/togglz/spring/listener/TogglzApplicationContextBinderApplicationListener.java
|
https://github.com/togglz/togglz/blob/master/spring-core/src/main/java/org/togglz/spring/listener/TogglzApplicationContextBinderApplicationListener.java
|
Apache-2.0
|
@Override
protected ApplicationContext getApplicationContext(Object context) {
return ContextClassLoaderApplicationContextHolder.get();
}
|
Simple implementation of {@link org.togglz.core.spi.BeanFinder} which uses
{@link ContextClassLoaderApplicationContextHolder}.
|
getApplicationContext
|
java
|
togglz/togglz
|
spring-core/src/main/java/org/togglz/spring/spi/SpringCoreBeanFinder.java
|
https://github.com/togglz/togglz/blob/master/spring-core/src/main/java/org/togglz/spring/spi/SpringCoreBeanFinder.java
|
Apache-2.0
|
public static ApplicationContext get() {
ClassLoader classLoader = getContextClassLoader();
while (classLoader != null) {
ApplicationContext applicationContext = contextMap.get(classLoader);
if (applicationContext != null) {
return applicationContext;
}
classLoader = classLoader.getParent();
}
return null;
}
|
Returns the {@link ApplicationContext} bound to the current context class loader or any of
its parent class loaders. Walking up the class loader hierarchy is required to support
special class loader scenarios like Spring Boot's reloading mechanism.
|
get
|
java
|
togglz/togglz
|
spring-core/src/main/java/org/togglz/spring/util/ContextClassLoaderApplicationContextHolder.java
|
https://github.com/togglz/togglz/blob/master/spring-core/src/main/java/org/togglz/spring/util/ContextClassLoaderApplicationContextHolder.java
|
Apache-2.0
|
public static void bind(ApplicationContext context) {
Object old = contextMap.putIfAbsent(getContextClassLoader(), context);
if (old != null) {
throw new IllegalStateException(
"There is already a ApplicationContext associated with the context ClassLoader of the current thread!");
}
}
|
Binds the {@link ApplicationContext} to the current context class loader .
|
bind
|
java
|
togglz/togglz
|
spring-core/src/main/java/org/togglz/spring/util/ContextClassLoaderApplicationContextHolder.java
|
https://github.com/togglz/togglz/blob/master/spring-core/src/main/java/org/togglz/spring/util/ContextClassLoaderApplicationContextHolder.java
|
Apache-2.0
|
@Override
public CSRFToken getToken(HttpServletRequest request) {
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
if (token != null) {
return new CSRFToken(token.getParameterName(), token.getToken());
}
return null;
}
|
Implementation of CSRFTokenProvider for Spring Security.
@see org.togglz.servlet.spi.CSRFTokenProvider
|
getToken
|
java
|
togglz/togglz
|
spring-security/src/main/java/org/togglz/spring/security/SpringSecurityTokenProvider.java
|
https://github.com/togglz/togglz/blob/master/spring-security/src/main/java/org/togglz/spring/security/SpringSecurityTokenProvider.java
|
Apache-2.0
|
public static <F extends Feature> VariationSetBuilder<F> create(Class<F> featureClass) {
return new VariationSetBuilder<>(featureClass);
}
|
Default implementation of {@link VariationSet} that allows to build the set dynamically.
@param <F> The feature class
@author Christian Kaltepoth
|
create
|
java
|
togglz/togglz
|
testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
https://github.com/togglz/togglz/blob/master/testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
Apache-2.0
|
public VariationSetBuilder<F> vary(F f) {
featuresToVary.add(f);
featuresToEnable.remove(f);
featuresToDisable.remove(f);
return this;
}
|
Vary this feature in the variation set.
|
vary
|
java
|
togglz/togglz
|
testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
https://github.com/togglz/togglz/blob/master/testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
Apache-2.0
|
public VariationSetBuilder<F> enable(F f) {
featuresToVary.remove(f);
featuresToEnable.add(f);
featuresToDisable.remove(f);
return this;
}
|
Enable this feature in the variation set.
|
enable
|
java
|
togglz/togglz
|
testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
https://github.com/togglz/togglz/blob/master/testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
Apache-2.0
|
public VariationSetBuilder<F> disable(F f) {
featuresToVary.remove(f);
featuresToEnable.remove(f);
featuresToDisable.add(f);
return this;
}
|
Disable this feature in the variation set.
|
disable
|
java
|
togglz/togglz
|
testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
https://github.com/togglz/togglz/blob/master/testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
Apache-2.0
|
public VariationSetBuilder<F> enableAll() {
for (F f : featureClass.getEnumConstants()) {
enable(f);
}
return this;
}
|
Enable all features in the variation set.
|
enableAll
|
java
|
togglz/togglz
|
testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
https://github.com/togglz/togglz/blob/master/testing/src/main/java/org/togglz/testing/vary/VariationSetBuilder.java
|
Apache-2.0
|
public void resetPolicy() {
mPreferences.putString(PREF_LAST_RESPONSE, Integer.toString(Policy.RETRY));
setRetryUntil(DEFAULT_RETRY_UNTIL);
setMaxRetries(DEFAULT_MAX_RETRIES);
setRetryCount(Long.parseLong(DEFAULT_RETRY_COUNT));
setValidityTimestamp(DEFAULT_VALIDITY_TIMESTAMP);
mPreferences.commit();
}
|
We call this to guarantee that we fetch a fresh policy from the server. This is to be used if
the URL is invalid.
|
resetPolicy
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/APKExpansionPolicy.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/APKExpansionPolicy.java
|
Apache-2.0
|
private static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
// This won't happen in an Android-compatible environment.
throw new RuntimeException(e);
} catch (Base64DecoderException e) {
Log.e(TAG, "Could not decode from Base64.");
throw new IllegalArgumentException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
}
}
|
Generates a PublicKey instance from a string containing the Base64-encoded public key.
@param encodedPublicKey
Base64-encoded public key
@throws IllegalArgumentException
if encodedPublicKey is invalid
|
generatePublicKey
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
Apache-2.0
|
private static String getVersionCode(Context context, String packageName) {
try {
return String.valueOf(
context.getPackageManager().getPackageInfo(packageName, 0).versionCode);
} catch (NameNotFoundException e) {
Log.e(TAG, "Package not found. could not get version code.");
return "";
}
}
|
Get version code for the application package name.
@param packageName
application package name
@return the version code or empty string if package not found
|
getVersionCode
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
Apache-2.0
|
private synchronized void handleServiceConnectionError(LibraryValidator validator) {
mPolicy.processServerResponse(Policy.RETRY, null);
if (mPolicy.allowAccess()) {
validator.getCallback().allow(Policy.RETRY);
} else {
validator.getCallback().dontAllow(Policy.RETRY);
}
}
|
Generates policy response for service connection errors, as a result of disconnections or
timeouts.
|
handleServiceConnectionError
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
Apache-2.0
|
private void cleanupService() {
if (mService != null) {
try {
mContext.unbindService(this);
} catch (IllegalArgumentException e) {
// Somehow we've already been unbound. This is a non-fatal error.
Log.e(TAG, "Unable to unbind from licensing service (already unbound)");
}
mService = null;
}
}
|
Unbinds service if necessary and removes reference to it.
|
cleanupService
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/LibraryChecker.java
|
Apache-2.0
|
public void check(PublicKey publicKey, int responseCode, String signedData, Calendar calendar,
String signature) {
String userId = null;
// Skip signature check for unsuccessful requests
ResponseData data = null;
if (calendar == null) {
handleInvalidResponse();
} else if (responseCode == LICENSED || responseCode == NOT_LICENSED ||
responseCode == LICENSED_OLD_KEY) {
// Verify signature.
try {
if (TextUtils.isEmpty(signedData)) {
Log.e(TAG, "Signature verification failed: signedData is empty. " +
"(Device not signed-in to any Google accounts?)");
handleInvalidResponse();
return;
}
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(Base64.decode(signature))) {
Log.e(TAG, "Signature verification failed.");
handleInvalidResponse();
return;
}
} catch (NoSuchAlgorithmException | SignatureException e) {
// This can't happen on an Android compatible device.
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
handleApplicationError(LibraryCheckerCallback.ERROR_INVALID_PUBLIC_KEY);
return;
} catch (Base64DecoderException e) {
Log.e(TAG, "Could not Base64-decode signature.");
handleInvalidResponse();
return;
}
// Parse and validate response.
try {
data = ResponseData.parse(signedData);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Could not parse response.");
handleInvalidResponse();
return;
}
if (data.responseCode != responseCode) {
Log.e(TAG, "Response codes don't match.");
handleInvalidResponse();
return;
}
if (data.nonce != mNonce) {
Log.e(TAG, "Nonce doesn't match.");
handleInvalidResponse();
return;
}
if (!data.packageName.equals(mPackageName)) {
Log.e(TAG, "Package name doesn't match.");
handleInvalidResponse();
return;
}
if (!data.versionCode.equals(mVersionCode)) {
Log.e(TAG, "Version codes don't match.");
handleInvalidResponse();
return;
}
// Application-specific user identifier.
userId = data.userId;
if (TextUtils.isEmpty(userId)) {
Log.e(TAG, "User identifier is empty.");
handleInvalidResponse();
return;
}
}
switch (responseCode) {
case LICENSED:
case LICENSED_OLD_KEY:
int limiterResponse = mDeviceLimiter.isDeviceAllowed(userId);
handleResponse(limiterResponse, data);
break;
case NOT_LICENSED:
handleResponse(Policy.NOT_LICENSED, data);
break;
case ERROR_CONTACTING_SERVER:
Log.w(TAG, "Error contacting licensing server.");
handleResponse(Policy.RETRY, data);
break;
case ERROR_SERVER_FAILURE:
Log.w(TAG, "An error has occurred on the licensing server.");
handleResponse(Policy.RETRY, data);
break;
case ERROR_OVER_QUOTA:
Log.w(TAG, "Licensing server is refusing to talk to this device, over quota.");
handleResponse(Policy.RETRY, data);
break;
case ERROR_INVALID_PACKAGE_NAME:
handleApplicationError(LibraryCheckerCallback.ERROR_INVALID_PACKAGE_NAME);
break;
case ERROR_NON_MATCHING_UID:
handleApplicationError(LibraryCheckerCallback.ERROR_NON_MATCHING_UID);
break;
case ERROR_NOT_MARKET_MANAGED:
handleApplicationError(LibraryCheckerCallback.ERROR_NOT_MARKET_MANAGED);
break;
default:
Log.e(TAG, "Unknown response code for license check.");
handleInvalidResponse();
}
}
|
Verifies the response from server and calls appropriate callback method.
@param publicKey
public key associated with the developer account
@param responseCode
server response code
@param signedData
signed data from server
@param signature
server signature
|
check
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/LibraryValidator.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/LibraryValidator.java
|
Apache-2.0
|
private void handleResponse(int response, ResponseData rawData) {
// Update policy data and increment retry counter (if needed)
mPolicy.processServerResponse(response, rawData);
// Given everything we know, including cached data, ask the policy if we should grant
// access.
if (mPolicy.allowAccess()) {
mCallback.allow(response);
} else {
mCallback.dontAllow(response);
}
}
|
Confers with policy and calls appropriate callback method.
|
handleResponse
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/LibraryValidator.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/LibraryValidator.java
|
Apache-2.0
|
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset, byte[]
alphabet) {
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index alphabet
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff =
(numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = alphabet[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
}
|
Encodes up to three bytes of the array <var>source</var> and writes the resulting four Base64
bytes to <var>destination</var>. The source and destination arrays can be manipulated
anywhere along their length by specifying <var>srcOffset</var> and <var>destOffset</var>.
This method does not check to make sure your arrays are large enough to accommodate
<var>srcOffset</var> + 3 for the <var>source</var> array or <var>destOffset</var> + 4 for the
<var>destination</var> array. The actual number of significant bytes in your array is given
by <var>numSigBytes</var>.
@param source
the array to convert
@param srcOffset
the index where conversion begins
@param numSigBytes
the number of significant bytes in your array
@param destination
the array to hold the conversion
@param destOffset
the index where output will be put
@param alphabet
is the encoding alphabet
@return the <var>destination</var> array
@since 1.3
|
encode3to4
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
Apache-2.0
|
public static String encode(byte[] source) {
return encode(source, 0, source.length, ALPHABET, true);
}
|
Encodes a byte array into Base64 notation. Equivalent to calling {@code encodeBytes(source,
0, source.length)}
@param source
The data to convert
@since 1.4
|
encode
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
Apache-2.0
|
public static String encodeWebSafe(byte[] source, boolean doPadding) {
return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding);
}
|
Encodes a byte array into web safe Base64 notation.
@param source
The data to convert
@param doPadding
is {@code true} to pad result with '=' chars if it does not fall on 3 byte
boundaries
|
encodeWebSafe
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
Apache-2.0
|
public static String encode(byte[] source, int off, int len, byte[] alphabet,
boolean doPadding) {
byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE);
int outLen = outBuff.length;
// If doPadding is false, set length to truncate '='
// padding characters
while ((!doPadding) && outLen > 0) {
if (outBuff[outLen - 1] != '=') {
break;
}
outLen -= 1;
}
return new String(outBuff, 0, outLen);
}
|
Encodes a byte array into Base64 notation.
@param source
The data to convert
@param off
Offset in array where conversion should begin
@param len
Length of data to convert
@param alphabet
is the encoding alphabet
@param doPadding
is {@code true} to pad result with '=' chars if it does not fall on 3 byte
boundaries
@since 1.4
|
encode
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
Apache-2.0
|
@SuppressLint("Assert")
public static byte[] encode(byte[] source, int off, int len, byte[] alphabet,
int maxLineLength) {
int lenDiv3 = (len + 2) / 3; // ceil(len / 3)
int len43 = lenDiv3 * 4;
byte[] outBuff = new byte[len43 // Main 4:3
+ (len43 / maxLineLength)]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
// The following block of code is the same as
// encode3to4( source, d + off, 3, outBuff, e, alphabet );
// but inlined for faster encoding (~20% improvement)
int inBuff =
((source[d + off] << 24) >>> 8)
| ((source[d + 1 + off] << 24) >>> 16)
| ((source[d + 2 + off] << 24) >>> 24);
outBuff[e] = alphabet[(inBuff >>> 18)];
outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f];
outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f];
outBuff[e + 3] = alphabet[(inBuff) & 0x3f];
lineLength += 4;
if (lineLength == maxLineLength) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // end for: each piece of array
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e, alphabet);
lineLength += 4;
if (lineLength == maxLineLength) {
// Add a last newline
outBuff[e + 4] = NEW_LINE;
e++;
}
e += 4;
}
assert (e == outBuff.length);
return outBuff;
}
|
Encodes a byte array into Base64 notation.
@param source
The data to convert
@param off
Offset in array where conversion should begin
@param len
Length of data to convert
@param alphabet
is the encoding alphabet
@param maxLineLength
maximum length of one line.
@return the BASE64-encoded byte array
|
encode
|
java
|
javiersantos/PiracyChecker
|
library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
https://github.com/javiersantos/PiracyChecker/blob/master/library/src/main/java/com/github/javiersantos/licensing/util/Base64.java
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.