code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
private void processResponse(Response response) {
// at this point a server response should contain a secure JSON with challenges
JSONObject jsonResponse = Utils.extractSecureJson(response);
JSONObject jsonChallenges = (jsonResponse == null) ? null : jsonResponse.optJSONObject(CHALLENGES_VALUE_NAME);
if (jsonChallenges != null) {
startHandleChallenges(jsonChallenges, response);
} else {
listener.onSuccess(response);
}
} | Process a response from the server.
@param response Server response. |
private void startHandleChallenges(JSONObject jsonChallenges, Response response) {
ArrayList<String> challenges = getRealmsFromJson(jsonChallenges);
MCAAuthorizationManager authManager = (MCAAuthorizationManager) BMSClient.getInstance().getAuthorizationManager();
if (isAuthorizationRequired(response)) {
setExpectedAnswers(challenges);
}
for (String realm : challenges) {
ChallengeHandler handler = authManager.getChallengeHandler(realm);
if (handler != null) {
JSONObject challenge = jsonChallenges.optJSONObject(realm);
handler.handleChallenge(this, challenge, context);
} else {
throw new RuntimeException("Challenge handler for realm is not found: " + realm);
}
}
} | Handles authentication challenges.
@param jsonChallenges Collection of challenges.
@param response Server response. |
private boolean isAuthorizationRequired(Response response) {
if (response != null && response.getStatus() == 401) {
ResponseImpl responseImpl = (ResponseImpl)response;
String challengesHeader = responseImpl.getFirstHeader(AUTHENTICATE_HEADER_NAME);
if (AUTHENTICATE_HEADER_VALUE.equalsIgnoreCase(challengesHeader)) {
return true;
}
}
return false;
} | Checks server response for MFP 401 error. This kind of response should contain MFP authentication challenges.
@param response Server response.
@return <code>true</code> if the server response contains 401 status code along with MFP challenges. |
private void processFailures(JSONObject jsonFailures) {
if (jsonFailures == null) {
return;
}
MCAAuthorizationManager authManager = (MCAAuthorizationManager) BMSClient.getInstance().getAuthorizationManager();
ArrayList<String> challenges = getRealmsFromJson(jsonFailures);
for (String realm : challenges) {
ChallengeHandler handler = authManager.getChallengeHandler(realm);
if (handler != null) {
JSONObject challenge = jsonFailures.optJSONObject(realm);
handler.handleFailure(context, challenge);
} else {
logger.error("Challenge handler for realm is not found: " + realm);
}
}
} | Processes authentication failures.
@param jsonFailures Collection of authentication failures. |
private void processSuccesses(JSONObject jsonSuccesses) {
if (jsonSuccesses == null) {
return;
}
MCAAuthorizationManager authManager = (MCAAuthorizationManager) BMSClient.getInstance().getAuthorizationManager();
ArrayList<String> challenges = getRealmsFromJson(jsonSuccesses);
for (String realm : challenges) {
ChallengeHandler handler = authManager.getChallengeHandler(realm);
if (handler != null) {
JSONObject challenge = jsonSuccesses.optJSONObject(realm);
handler.handleSuccess(context, challenge);
} else {
logger.error("Challenge handler for realm is not found: " + realm);
}
}
} | Processes authentication successes.
@param jsonSuccesses Collection of authentication successes. |
public void requestFailed(JSONObject info) {
logger.error("BaseRequest failed with info: " + (info == null ? "info is null" : info.toString()));
listener.onFailure(null, null, info);
} | Called when a request to authorization server failed.
@param info Extended information about the failure. |
private ArrayList<String> getRealmsFromJson(JSONObject jsonChallenges) {
Iterator<String> challengesIterator = jsonChallenges.keys();
ArrayList<String> challenges = new ArrayList<>();
while (challengesIterator.hasNext()) {
challenges.add(challengesIterator.next());
}
return challenges;
} | Iterates a JSON object containing authorization challenges and builds a list of reals.
@param jsonChallenges Collection of challenges.
@return Array with realms. |
@Override
public void onFailure(Response response, Throwable t, JSONObject extendedInfo) {
if (isAuthorizationRequired(response)) {
processResponseWrapper(response, true);
} else {
listener.onFailure(response, t, extendedInfo);
}
} | Called when request fails.
@param response Contains detail regarding why the request failed
@param t Exception that could have caused the request to fail. Null if no Exception thrown. |
private void processResponseWrapper(Response response, boolean isFailure) {
try {
ResponseImpl responseImpl = (ResponseImpl)response;
if (isFailure || !responseImpl.isRedirect()) {
processResponse(response);
} else {
processRedirectResponse(response);
}
} catch (Throwable t) {
logger.error("processResponseWrapper caught exception: " + t.getLocalizedMessage());
listener.onFailure(response, t, null);
}
} | Called from onSuccess and onFailure. Handles all possible exceptions and notifies the listener
if an exception occurs.
@param response server response
@param isFailure specifies whether this method is called from onSuccess (false) or onFailure (true). |
public T execute(HyperionClient client)
{
EntityList<T> response = client.create(build());
List<T> entries = response.getEntries();
return entries.size() == 0 ? null : entries.get(0);
} | Execute the request using the supplied client
@param client the client
@return The request |
public static void assertNotNull(final Object object, final StatusType status) {
RESTAssert.assertTrue(object != null, status);
} | assert that object is not null
@param object the object to check
@param status the status code to throw
@throws WebApplicationException with given status code |
public static void assertNotEmpty(final String string, final StatusType status) {
RESTAssert.assertNotNull(string, status);
RESTAssert.assertFalse(string.isEmpty(), status);
} | assert that string is not null nor empty
@param string the string to check
@param status the status code to throw
@throws WebApplicationException with given status code |
public static void assertNotEmpty(final Collection<?> collection, final StatusType status) {
RESTAssert.assertNotNull(collection, status);
RESTAssert.assertFalse(collection.isEmpty(), status);
} | assert that collection is not empty
@param collection the collection to check
@param status the status code to throw
@throws WebApplicationException with given status code |
public static void assertSingleElement(final Collection<?> collection, final StatusType status) {
RESTAssert.assertNotNull(collection, status);
RESTAssert.assertTrue(collection.size() == 1, status);
} | assert that collection has one element
@param collection the collection to check
@param status the status code to throw
@throws WebApplicationException with given status code |
public static void assertEquals(final Object one, final Object two) {
RESTAssert.assertEquals(one, two, RESTAssert.DEFAULT_STATUS_CODE);
} | assert that objects are equal.<br>
This means they are both <i>null</i> or <code>one.equals(two)</code> returns <i>true</i>
@param one the first object
@param two the second object
@throws WebApplicationException with status code 422 (Unprocessable Entity) |
@SuppressWarnings("null")
public static void assertEquals(final Object one, final Object two, final StatusType status) {
if ((one == null) && (two == null)) {
return;
}
RESTAssert.assertNotNull(one, status);
RESTAssert.assertTrue(one.equals(two), status);
} | assert that objects are equal.<br>
This means they are both <i>null</i> or <code>one.equals(two)</code> returns <i>true</i>
@param one the first object
@param two the second object
@param status the status code to throw
@throws WebApplicationException with given status code |
public static void assertInt(final String string, final StatusType status) {
RESTAssert.assertNotEmpty(string);
RESTAssert.assertPattern(string, "[+-]?[0-9]*", status);
} | assert that string matches [+-]?[0-9]*
@param string the string to check
@param status the status code to throw
@throws WebApplicationException with given status code |
public static void assertPattern(String string, String pattern) {
RESTAssert.assertPattern(string, pattern, RESTAssert.DEFAULT_STATUS_CODE);
} | assert that string matches the given pattern
@param string the string to check
@param pattern the pattern to check
@throws WebApplicationException with status code 422 (Unprocessable Entity) |
public static void assertPattern(String string, String pattern, final StatusType status) {
RESTAssert.assertNotNull(string);
RESTAssert.assertNotNull(pattern);
RESTAssert.assertTrue(string.matches(pattern), status);
} | assert that string matches the given pattern
@param string the string to check
@param status the status code to throw
@throws WebApplicationException with given status code |
public static Class<?> getClass(String classname) {
Class<?> clazz = null;
try {
clazz = Class.forName(classname);
} catch (Exception e) {
// Try the second approach
}
if (null == clazz) {
Exception classNotFoundEx = null;
try {
clazz = Class.forName(classname, true, new ClassLoaderResourceUtils().getClass().getClassLoader());
} catch (Exception e) {
// Try the third approach
classNotFoundEx = e;
}
if (null == clazz) {
ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
if (null != threadClassLoader) {
try {
clazz = Class.forName(classname, true, threadClassLoader);
} catch (Exception e) {
throw new BundlingProcessException(e.getMessage() + " [The custom class " + classname
+ " could not be instantiated, check wether it is available on the classpath and"
+ " verify that it has a zero-arg constructor].\n" + " The specific error message is: "
+ e.getClass().getName() + ":" + e.getMessage(), e);
}
} else {
throw new BundlingProcessException(classNotFoundEx.getMessage() + " [The custom class " + classname
+ " could not be instantiated, check wether it is available on the classpath and"
+ " verify that it has a zero-arg constructor].\n" + " The specific error message is: "
+ classNotFoundEx.getClass().getName() + ":" + classNotFoundEx.getMessage(),
classNotFoundEx);
}
}
}
return clazz;
} | Returns the class associated to the class name given in parameter
@param classname
the class name
@return the class |
public static Object buildObjectInstance(String classname, Object[] params) {
Object rets = null;
Class<?>[] paramTypes = new Class[params.length];
for (int x = 0; x < params.length; x++) {
paramTypes[x] = params[x].getClass();
}
try {
Class<?> clazz = getClass(classname);
rets = clazz.getConstructor(paramTypes).newInstance(params);
} catch (Exception e) {
throw new BundlingProcessException(e.getMessage() + " [The custom class " + classname
+ " could not be instantiated, check wether it is available on the classpath and"
+ " verify that it has a zero-arg constructor].\n" + " The specific error message is: "
+ e.getClass().getName() + ":" + e.getMessage(), e);
}
return rets;
} | Builds a class instance using reflection, by using its classname. The
class must have a zero-arg constructor.
@param classname
the class to build an instance of.
@param params
the parameters
@return the class instance |
public TaskResult add(String key, String value) {
mBundle.putString(key, value);
return this;
} | Inserts a String value into the mapping of this Bundle, replacing any existing value for the
given key. Either key or value may be null.
@param key a String, or null
@param value a String, or null |
public TaskResult add(String key, CharSequence value) {
mBundle.putCharSequence(key, value);
return this;
} | Inserts a CharSequence value into the mapping of this Bundle, replacing any existing value for
the given key. Either key or value may be null.
@param key a String, or null
@param value a CharSequence, or null |
public TaskResult add(String key, Parcelable value) {
mBundle.putParcelable(key, value);
return this;
} | Inserts a Parcelable value into the mapping of this Bundle, replacing any existing value for
the given key. Either key or value may be null.
@param key a String, or null
@param value a Parcelable object, or null |
public TaskResult add(String key, Parcelable[] value) {
mBundle.putParcelableArray(key, value);
return this;
} | Inserts an array of Parcelable values into the mapping of this Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value an array of Parcelable objects, or null |
public TaskResult addParcelableArrayList(String key, ArrayList<? extends Parcelable> value) {
mBundle.putParcelableArrayList(key, value);
return this;
} | Inserts a List of Parcelable values into the mapping of this Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value an ArrayList of Parcelable objects, or null |
public TaskResult add(String key, SparseArray<? extends Parcelable> value) {
mBundle.putSparseParcelableArray(key, value);
return this;
} | Inserts a SparseArray of Parcelable values into the mapping of this Bundle, replacing any
existing value for the given key. Either key or value may be null.
@param key a String, or null
@param value a SparseArray of Parcelable objects, or null |
public TaskResult addIntegerArrayList(String key, ArrayList<Integer> value) {
mBundle.putIntegerArrayList(key, value);
return this;
} | Inserts an ArrayList<Integer> value into the mapping of this Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value an ArrayList<Integer> object, or null |
public TaskResult addStringArrayList(String key, ArrayList<String> value) {
mBundle.putStringArrayList(key, value);
return this;
} | Inserts an ArrayList<String> value into the mapping of this Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value an ArrayList<String> object, or null |
public TaskResult add(String key, ArrayList<CharSequence> value) {
mBundle.putCharSequenceArrayList(key, value);
return this;
} | Inserts an ArrayList<CharSequence> value into the mapping of this Bundle, replacing any
existing value for the given key. Either key or value may be null.
@param key a String, or null
@param value an ArrayList<CharSequence> object, or null |
public TaskResult add(String key, Serializable value) {
mBundle.putSerializable(key, value);
return this;
} | Inserts a Serializable value into the mapping of this Bundle, replacing any existing value for
the given key. Either key or value may be null.
@param key a String, or null
@param value a Serializable object, or null |
public TaskResult add(String key, String[] value) {
mBundle.putStringArray(key, value);
return this;
} | Inserts a String array value into the mapping of this Bundle, replacing any existing value for
the given key. Either key or value may be null.
@param key a String, or null
@param value a String array object, or null |
public TaskResult add(String key, CharSequence[] value) {
mBundle.putCharSequenceArray(key, value);
return this;
} | Inserts a CharSequence array value into the mapping of this Bundle, replacing any existing
value for the given key. Either key or value may be null.
@param key a String, or null
@param value a CharSequence array object, or null |
public TaskResult add(String key, Bundle value) {
mBundle.putBundle(key, value);
return this;
} | Inserts a Bundle value into the mapping of this Bundle, replacing any existing value for the
given key. Either key or value may be null.
@param key a String, or null
@param value a Bundle object, or null
@return itself |
private void tryExpire(boolean force, LongSupplier time) {
long now = time.getAsLong();
if (force || now >= nextPruning) {
nextPruning = now + pruningDelay;
histogram.expire(now);
}
} | Expire the histogram if it is time to expire it, or if force is true AND it is dirty |
public static boolean isOnline(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
NetworkInfo info = cm.getActiveNetworkInfo();
return info != null && info.isConnectedOrConnecting();
} | Checks whether there's a network connection.
@param context Context to use
@return true if there's an active network connection, false otherwise |
public static boolean isCurrentConnectionWifi(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
NetworkInfo info = cm.getActiveNetworkInfo();
return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
} | Check if current connection is Wi-Fi.
@param context Context to use
@return true if current connection is Wi-Fi false otherwise |
public static void keepCpuAwake(Context context, boolean awake) {
if (cpuWakeLock == null) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm != null) {
cpuWakeLock =
pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
cpuWakeLock.setReferenceCounted(true);
}
}
if (cpuWakeLock != null) { //May be null if pm is null
if (awake) {
cpuWakeLock.acquire();
L.d(TAG, "Adquired CPU lock");
} else if (cpuWakeLock.isHeld()) {
cpuWakeLock.release();
L.d(TAG, "Released CPU lock");
}
}
} | Register a wake lock to power management in the device.
@param context Context to use
@param awake if true the device cpu will keep awake until false is called back. if true is
passed several times only the first time after a false call will take effect,
also if false is passed and previously the cpu was not turned on (true call)
does nothing. |
public static void keepWiFiOn(Context context, boolean on) {
if (wifiLock == null) {
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wm != null) {
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
wifiLock.setReferenceCounted(true);
}
}
if (wifiLock != null) { // May be null if wm is null
if (on) {
wifiLock.acquire();
L.d(TAG, "Adquired WiFi lock");
} else if (wifiLock.isHeld()) {
wifiLock.release();
L.d(TAG, "Released WiFi lock");
}
}
} | Register a WiFi lock to WiFi management in the device.
@param context Context to use
@param on if true the device WiFi radio will keep awake until false is called back. if
true is passed several times only the first time after a false call will take
effect, also if false is passed and previously the WiFi radio was not turned on
(true call) does nothing. |
private void run(String[] arguments) throws Exception {
if(isHelpRequested(arguments)) {
usage();
}
validateArguments(arguments);
checkTemporaryDirectory(arguments);
addShutdownHook();
File war = getWarLocation();
File tempDirectory = createTempDirectory(war.getName(), getPort(arguments));
cl = createClassLoader(war, tempDirectory);
Thread.currentThread().setContextClassLoader(cl);
startJettyConsole(cl, arguments, tempDirectory);
} | Extract jar files, set up a class loader and execute {@link org.simplericity.jettyconsole.JettyConsoleStarter}'s main method.
@param arguments
@throws Exception |
private void startJettyConsole(ClassLoader cl, String[] arguments, File tempDirectory) {
try {
Class starterClass = cl.loadClass("org.simplericity.jettyconsole.JettyConsoleStarter");
starterClass.getField("jettyWorkDirectory").set(null, tempDirectory);
Method main = starterClass.getMethod("main", arguments.getClass());
main.invoke(null, new Object[] {arguments});
} catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
} | Load {@link org.simplericity.jettyconsole.JettyConsoleStarter} and execute its main method.
@param cl The class loader to use for loading {@link JettyConsoleStarter}
@param arguments the arguments to pass to the main method |
private ClassLoader createClassLoader(File warFile, File tempDirectory) {
try {
File condiLibDirectory = new File(tempDirectory, "condi");
condiLibDirectory.mkdirs();
File jettyWebappDirectory = new File(tempDirectory, "webapp");
jettyWebappDirectory.mkdirs();
List<URL> urls = new ArrayList<>();
JarInputStream in = new JarInputStream(new FileInputStream(warFile));
while(true) {
JarEntry entry = in.getNextJarEntry();
if(entry == null) {
break;
}
String name = entry.getName();
String prefix = "META-INF/jettyconsole/lib/";
if(!entry.isDirectory()) {
if( name.startsWith(prefix) ) {
String simpleName = name.substring(name.lastIndexOf("/")+1);
File file = new File(condiLibDirectory, simpleName);
unpackFile(in, file);
urls.add(file.toURI().toURL());
} else if(!name.startsWith("META-INF/jettyconsole")
&& !name.contains("JettyConsoleBootstrapMainClass")) {
File file = new File(jettyWebappDirectory, name);
file.getParentFile().mkdirs();
unpackFile(in, file);
}
}
}
in.close();
return new URLClassLoader(urls.toArray(new URL[urls.size()]), JettyConsoleBootstrapMainClass.class.getClassLoader());
} catch (IOException e) {
throw new RuntimeException(e);
}
} | Create a URL class loader containing all jar files in the given directory
@param warFile the war file to look for libs dirs in
@return |
private static File getWarLocation() {
URL resource = JettyConsoleBootstrapMainClass.class.getResource("/META-INF/jettyconsole/jettyconsole.properties");
String file = resource.getFile();
file = file.substring("file:".length(), file.indexOf("!"));
try {
file = URLDecoder.decode(file, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return new File(file);
} | Return a File pointing to the location of the Jar file this Main method is executed from. |
private static void unpackFile(InputStream in, File file) {
byte[] buffer = new byte[4096];
try {
OutputStream out = new FileOutputStream(file);
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} | Write the contents of an InputStream to a file
@param in the input stream to read
@param file the File to write to |
public static ContextElement extract(Object from) {
Map<String, AttributeGetter<Object>> attributes = new HashMap<>();
attributes.putAll(extractInstanceAttribute(from));
attributes.putAll(extractMethodAttributes(from));
attributes.putAll(extractFieldAttributes(from));
return new LazyContextElement(from.getClass(), attributes);
} | Returns a {@code ContextElement} instance for the supplied object.
<p>
The supplied object's class type is parsed for {@link ContextAttribute}
annotations and the associated attributes are extracted and returned in the
form of a {@code ContextElement}.
@param from object to extract context for
@return a {@code ContextElement} |
@OnSuccess(AnimalTask.class)
public void onSuccess(@Param("sound") String sound,
@Param(Groundy.TASK_IMPLEMENTATION) Class<?> impl) {
if (impl == DogTask.class) findViewById(R.id.send_random_task).setEnabled(true);
Toast.makeText(InheritanceExample.this, sound, Toast.LENGTH_SHORT).show();
} | we are using AnimalTask (super class of CatTask and DogTask) |
public final boolean matches(Object object) {
return boundType.isAssignableFrom(object.getClass()) && matchesSafely(boundType.cast(object));
} | Returns true if this object matches successfully.
<p>
This method checks for a type match against the erased type of this matcher
and then defers to the {@link #matchesSafely(Object)} of this matcher with the
type-checked and cast object.
@param object object to be checked
@return {@code true} if the object matches |
public static Element getFirstChildElement(Node node) {
if(node instanceof NestableNode) {
return ((NestableNode) node).getFirstElementChild();
}
return null;
} | Get the first child node that is an element node.
@param node The node whose children should be iterated.
@return The first child element or {@code null}. |
public static final Element getNextSiblingElement(Node node) {
List<Node> siblings = node.getParent().getChildren();
Node n = null;
int index = siblings.indexOf(node) + 1;
if(index>0 && index<siblings.size()) {
n = siblings.get(index);
while(!(n instanceof Element) && ++index < siblings.size()) {
n = siblings.get(index);
}
if(index==siblings.size()) {
n = null;
}
}
return (Element) n;
} | Get the next sibling element.
@param node The start node.
@return The next sibling element or {@code null}. |
public <T extends Serializable> Optional<Statistic<T>> queryStatistic(String fullStatisticName) {
return queryStatistic(fullStatisticName, 0);
} | Query a statistic based on the full statistic name. Returns null if not found. |
@SuppressWarnings("unchecked")
public <T extends Serializable> Optional<Statistic<T>> queryStatistic(String fullStatisticName, long sinceMillis) {
ValueStatistic<T> valueStatistic = (ValueStatistic<T>) statistics.get(fullStatisticName);
if (valueStatistic == null) {
return Optional.empty();
}
return Optional.of(Statistic.extract(valueStatistic, sinceMillis, timeSource.getAsLong()));
} | Query a statistic based on the full statistic name. Returns null if not found. |
public void registerTable(String fullStatName, Supplier<Table> accessor) {
registerStatistic(fullStatName, table(accessor));
} | Directly register a TABLE stat with its accessors |
public void registerGauge(String fullStatName, Supplier<Number> accessor) {
registerStatistic(fullStatName, gauge(accessor));
} | Directly register a GAUGE stat with its accessor |
public void registerCounter(String fullStatName, Supplier<Number> accessor) {
registerStatistic(fullStatName, counter(accessor));
} | Directly register a COUNTER stat with its accessor |
private void writePathDescriptor(File consoleDir, Set<String> paths) {
try (PrintWriter writer = new PrintWriter(new FileOutputStream(new File(consoleDir, "jettyconsolepaths.txt")))){
for (String path : paths) {
writer.println(path);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} | Write a txt file with one line for each unpacked class or resource
from dependencies. |
@Override
public Set<Node> check(Set<Node> nodes, Node root) throws NodeSelectorException {
Assert.notNull(nodes, "nodes is null!");
this.nodes = nodes;
//Document doc = (root instanceof Document) ? (Document) root : DOMHelper.getOwnerDocument(root);
caseSensitive = false; //!doc.createElement("a").isEqualNode(doc.createElement("A"));
result = new LinkedHashSet<Node>();
switch (selector.getCombinator()) {
case DESCENDANT:
addDescendantElements();
break;
case CHILD:
addChildElements();
break;
case ADJACENT_SIBLING:
addAdjacentSiblingElements();
break;
case GENERAL_SIBLING:
addGeneralSiblingElements();
break;
}
return result;
} | {@inheritDoc} |
private void addDescendantElements() throws NodeSelectorException {
for (Node node : nodes) {
List<Node> nl;
if (node instanceof Document || node instanceof Element) {
nl = DOMHelper.getElementsByTagName(node, selector.getTagName());
} else {
throw new NodeSelectorException("Only document and element nodes allowed!");
}
result.addAll(nl);
}
} | Add descendant elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#descendant-combinators">Descendant combinator</a>
@throws NodeSelectorException If one of the nodes have an illegal type. |
private void addChildElements() {
for (Node node : nodes) {
if(node instanceof NestableNode) {
List<Node> nl = ((NestableNode) node).getChildren();
for (Node n : nl) {
if (!(n instanceof Element)) {
continue;
}
String tag = selector.getTagName();
if (tagEquals(tag, ((Element)n).getNormalizedName()) || tag.equals(Selector.UNIVERSAL_TAG)) {
result.add(n);
}
}
}
}
} | Add child elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#child-combinators">Child combinators</a> |
private void addAdjacentSiblingElements() {
for (Node node : nodes) {
Node n = DOMHelper.getNextSiblingElement(node);
if (n != null) {
String tag = selector.getTagName();
if (tagEquals(tag, DOMHelper.getNodeName(n)) || tag.equals(Selector.UNIVERSAL_TAG)) {
result.add(n);
}
}
}
} | Add adjacent sibling elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#adjacent-sibling-combinators">Adjacent sibling combinator</a> |
private boolean tagEquals(String tag1, String tag2) {
if (caseSensitive) {
return tag1.equals(tag2);
}
return tag1.equalsIgnoreCase(tag2);
} | Determine if the two specified tag names are equal.
@param tag1 A tag name.
@param tag2 A tag name.
@return <code>true</code> if the tag names are equal, <code>false</code> otherwise. |
private void onHandleIntent(GroundyTask groundyTask) {
if (groundyTask == null) {
return;
}
boolean requiresWifi = groundyTask.keepWifiOn();
if (requiresWifi) {
mWakeLockHelper.acquire();
}
L.d(TAG, "Executing value: " + groundyTask);
TaskResult taskResult;
try {
taskResult = groundyTask.doInBackground();
} catch (Exception e) {
e.printStackTrace();
taskResult = new Failed();
taskResult.add(Groundy.CRASH_MESSAGE, String.valueOf(e.getMessage()));
}
if (taskResult == null) {
throw new NullPointerException(
"Task " + groundyTask + " returned null from the doInBackground method");
}
if (requiresWifi) {
mWakeLockHelper.release();
}
//Lets try to send back the response
Bundle resultData = taskResult.getResultData();
resultData.putBundle(Groundy.ORIGINAL_PARAMS, groundyTask.getArgs());
resultData.putSerializable(Groundy.TASK_IMPLEMENTATION, groundyTask.getClass());
switch (taskResult.getType()) {
case SUCCESS:
groundyTask.send(OnSuccess.class, resultData);
break;
case FAIL:
groundyTask.send(OnFailure.class, resultData);
break;
case CANCEL:
resultData.putInt(Groundy.CANCEL_REASON, groundyTask.getQuittingReason());
groundyTask.send(OnCancel.class, resultData);
break;
}
} | This method is invoked on the worker thread with a request to process. Only one Intent is
processed at a time, but the processing happens on a worker thread that runs independently
from other application logic. So, if this code takes a long time, it will hold up other
requests to the same IntentService, but it will not hold up anything else.
@param groundyTask task to execute |
@Override
public Set<Node> check(Set<Node> nodes, Node root) throws NodeSelectorException {
Assert.notNull(nodes, "nodes is null!");
this.nodes = nodes;
result = new LinkedHashSet<Node>();
String value = specifier.getValue();
if ("nth-child".equals(value)) {
addNthChild();
} else if ("nth-last-child".equals(value)) {
addNthLastChild();
} else if ("nth-of-type".equals(value)) {
addNthOfType();
} else if ("nth-last-of-type".equals(value)) {
addNthLastOfType();
} else {
throw new NodeSelectorException("Unknown pseudo nth class: " + value);
}
return result;
} | {@inheritDoc} |
private void addNthChild() {
for (Node node : nodes) {
int count = 1;
Node n = DOMHelper.getPreviousSiblingElement(node);
while (n != null) {
count++;
n = DOMHelper.getPreviousSiblingElement(n);
}
if (specifier.isMatch(count)) {
result.add(node);
}
}
} | Add the {@code :nth-child} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#nth-child-pseudo"><code>:nth-child</code> pseudo-class</a> |
private void addNthLastChild() {
for (Node node : nodes) {
int count = 1;
Node n = DOMHelper.getNextSiblingElement(node);
while (n != null) {
count++;
n = DOMHelper.getNextSiblingElement(n);
}
if (specifier.isMatch(count)) {
result.add(node);
}
}
} | Add {@code :nth-last-child} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#nth-last-child-pseudo"><code>:nth-last-child</code> pseudo-class</a> |
private void addNthOfType() {
for (Node node : nodes) {
int count = 1;
Node n = DOMHelper.getPreviousSiblingElement(node);
while (n != null) {
if (DOMHelper.getNodeName(n).equals(DOMHelper.getNodeName(node))) {
count++;
}
n = DOMHelper.getPreviousSiblingElement(n);
}
if (specifier.isMatch(count)) {
result.add(node);
}
}
} | Add {@code :nth-of-type} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#nth-of-type-pseudo"><code>:nth-of-type</code> pseudo-class</a> |
private void addNthLastOfType() {
for (Node node : nodes) {
int count = 1;
Node n = DOMHelper.getNextSiblingElement(node);
while (n != null) {
if (DOMHelper.getNodeName(n).equals(DOMHelper.getNodeName(node))) {
count++;
}
n = DOMHelper.getNextSiblingElement(n);
}
if (specifier.isMatch(count)) {
result.add(node);
}
}
} | Add {@code nth-last-of-type} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#nth-last-of-type-pseudo"><code>:nth-last-of-type</code> pseudo-class</a> |
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(pl.setblack.airomem.direct.banksample.rest.BankResource.class);
} | Do not modify addRestResourceClasses() method. It is automatically
populated with all resources defined in the project. If required, comment
out calling this method in getClasses(). |
public void event(double value, long time) {
int barIndex = getBarIndex(value);
Bar bar = bars.get(barIndex);
long before = bar.count();
bar.insert(value, time);
long after = bar.count();
size += (after - before);
if (after > maxBarSize(barIndex)) {
split(bar, barIndex);
}
} | Record an event of the given {@code value} occuring at he given {@code time}
@param value event value
@param time event time |
public void expire(long time) {
long calculatedSize = 0;
Iterator<Bar> it = bars.iterator();
while (it.hasNext()) {
long barSize = it.next().expire(time);
if (barSize == 0) {
it.remove();
}
calculatedSize += barSize;
}
this.size = calculatedSize;
if (bars.isEmpty()) {
bars.add(new Bar(barEpsilon, window));
}
} | Expire old events from all buckets.
@param time current timestamp |
public static <T extends Serializable> ValueStatistic<T> memoize(long delay, TimeUnit unit, ValueStatistic<T> valueStatistic) {
return new MemoizingValueStatistic<>(delay, unit, valueStatistic);
} | Returns a {@link ValueStatistic} that caches the value of a statistic for at least a specific amount of time.
<p>
This method does not block.
<p>
When the delay expires, if several threads are coming at the same time to read the expired value, then only one will
do the update and set a new expiring delay and read the new value.
The other threads can continue to read the current expired value for their next call until it gets updated.
<p>
If the caching delay is smaller than the time it takes for a statistic value to be computed, then it is possible that
a new thread starts asking for a new value before the previous update is completed. In this case, there is no guarantee
that the cached value will be updated in order because it depends on the time took to get the new value.
@param delay The delay
@param unit The unit of time
@param valueStatistic The delegate statistic that will provide the value
@param <T> The statistic type
@return the memoizing statistic |
public static void cancelAll(Context context,
Class<? extends GroundyService> groundyServiceClass) {
new GroundyServiceConnection(context, groundyServiceClass) {
@Override
protected void onGroundyServiceBound(GroundyService.GroundyServiceBinder binder) {
binder.cancelAllTasks();
}
}.start();
} | Cancel all tasks: the ones running and parallel and future tasks.
@param context used to interact with the service
@param groundyServiceClass custom groundy service implementation |
public static void cancelTasksByGroup(Context context, int groupId,
CancelListener cancelListener) {
cancelTasksByGroup(context, groupId, GroundyTask.CANCEL_BY_GROUP, cancelListener);
} | Cancels all tasks of the specified group. The tasks get cancelled with the {@link
GroundyTask#CANCEL_BY_GROUP} reason.
@param context used to interact with the service
@param groupId the group id to cancel
@param cancelListener callback for cancel result |
public static void cancelTasksByGroup(Context context, int groupId, int reason,
CancelListener cancelListener) {
cancelTasks(context, GroundyService.class, groupId, reason, cancelListener);
} | Cancels all tasks of the specified group w/ the specified reason.
@param context used to interact with the service
@param groupId the group id to cancel
@param cancelListener callback for cancel result |
public static void cancelTaskById(Context context, final long id, final int reason,
final SingleCancelListener cancelListener,
Class<? extends GroundyService> groundyServiceClass) {
if (id <= 0) {
throw new IllegalStateException("id must be greater than zero");
}
new GroundyServiceConnection(context, groundyServiceClass) {
@Override
protected void onGroundyServiceBound(GroundyService.GroundyServiceBinder binder) {
int result = binder.cancelTaskById(id, reason);
if (cancelListener != null) {
cancelListener.onCancelResult(id, result);
}
}
}.start();
} | Cancels all tasks of the specified group w/ the specified reason.
@param context used to interact with the service
@param id the value to cancel
@param cancelListener callback for cancel result |
public static void cancelTasks(final Context context,
Class<? extends GroundyService> groundyServiceClass, final int groupId, final int reason,
final CancelListener cancelListener) {
if (groupId <= 0) {
throw new IllegalStateException("Group id must be greater than zero");
}
new GroundyServiceConnection(context, groundyServiceClass) {
@Override
protected void onGroundyServiceBound(GroundyService.GroundyServiceBinder binder) {
GroundyService.CancelGroupResponse cancelGroupResponse =
binder.cancelTasks(groupId, reason);
if (cancelListener != null) {
cancelListener.onCancelResult(groupId, cancelGroupResponse);
}
}
}.start();
} | Cancels all tasks of the specified group w/ the specified reason.
@param context used to interact with the service
@param groupId the group id to cancel
@param cancelListener callback for cancel result |
@SuppressWarnings("rawtypes")
public boolean useReferences(Class type) {
return !Util.isWrapperClass(type) && !type.equals(String.class) && !type.equals(Date.class) && !type.equals(BigDecimal.class) && !type.equals(BigInteger.class);
} | Returns false for all primitive wrappers. |
public void close() {
Politician.beatAroundTheBush(() -> {
if (this.prevayler != null) {
this.optionalSnapshot();
this.prevayler.close();
this.prevayler = null;
}
});
} | Close system.
<p>
This couses snapshot of system to be done. After this operation
Controller should be no more usable. |
public <RESULT> RESULT query(Query<ROOT, RESULT> query) {
return query.evaluate(getImmutable());
} | Query system (immutable view of it).
<p>
Few things to remember: 1. if operations done on system (using query) do
make some changes they will not be preserved (for long) 2. it is possible
to return any object from domain (including IMMUTABLE root) and perform
operations later on (but the more You do inside Query the safer).
@param <RESULT> result of query
@param query lambda (or query implementation) with operations
@return calculated result |
public <R> R executeAndQuery(ContextCommand<ROOT, R> cmd) {
return Politician.beatAroundTheBush(() -> this.prevayler.execute(new InternalTransaction<>(cmd)));
} | Perform command on system.
<p>
Inside command can be any code doing any changes. Such changes are
guaranteed to be preserved (if only command ended without exception).
@param cmd |
@Override
public <R> R executeAndQuery(Command<ROOT, R> cmd) {
return this.executeAndQuery((ContextCommand<ROOT, R>) cmd);
} | Perform command on system.
<p>
Inside command can be any code doing any changes. Such changes are
guaranteed to be preserved (if only command ended without exception).
@param cmd |
@Override
public Set<Node> check(Set<Node> nodes, Node root) throws NodeSelectorException {
Assert.notNull(nodes, "nodes is null!");
Set<Node> result = new LinkedHashSet<Node>();
for (Node node : nodes) {
if(node instanceof NestableAttributeHolderNode) {
Map<String,Attribute> map = ((NestableAttributeHolderNode) node).getAttributeMap();
if (map == null || map.isEmpty()) {
continue;
}
Attribute attr = map.get(specifier.getName());
if (attr == null) {
continue;
}
// It just have to be present.
if (specifier.getValue() == null) {
result.add(node);
continue;
}
String value = attr.getValue().trim();
if (value.length() != 0) {
String val = specifier.getValue();
switch (specifier.getMatch()) {
case EXACT:
if (value.equals(val)) {
result.add(node);
}
break;
case HYPHEN:
if (value.equals(val) || value.startsWith(val + '-')) {
result.add(node);
}
break;
case PREFIX:
if (value.startsWith(val)) {
result.add(node);
}
break;
case SUFFIX:
if (value.endsWith(val)) {
result.add(node);
}
break;
case CONTAINS:
if (value.contains(val)) {
result.add(node);
}
break;
case LIST:
for (String v : value.split("\\s+")) {
if (v.equals(val)) {
result.add(node);
}
}
break;
}
}
}
}
return result;
} | {@inheritDoc} |
@Nonnull
public static <T> EbInterfaceWriter <T> create (@Nonnull final Class <T> aClass)
{
return new EbInterfaceWriter <> (aClass);
} | Create a new writer builder.
@param aClass
The UBL class to be written. May not be <code>null</code>.
@return The new writer builder. Never <code>null</code>.
@param <T>
The ebInterface document implementation type |
@Nonnull
public static EbInterfaceWriter <Ebi30InvoiceType> ebInterface30 ()
{
final EbInterfaceWriter <Ebi30InvoiceType> ret = EbInterfaceWriter.create (Ebi30InvoiceType.class);
ret.setNamespaceContext (EbInterface30NamespaceContext.getInstance ());
return ret;
} | Create a writer builder for Ebi30InvoiceType.
@return The builder and never <code>null</code> |
@Nonnull
public static EbInterfaceWriter <Ebi302InvoiceType> ebInterface302 ()
{
final EbInterfaceWriter <Ebi302InvoiceType> ret = EbInterfaceWriter.create (Ebi302InvoiceType.class);
ret.setNamespaceContext (EbInterface302NamespaceContext.getInstance ());
return ret;
} | Create a writer builder for Ebi302InvoiceType.
@return The builder and never <code>null</code> |
@Nonnull
public static EbInterfaceWriter <Ebi40InvoiceType> ebInterface40 ()
{
final EbInterfaceWriter <Ebi40InvoiceType> ret = EbInterfaceWriter.create (Ebi40InvoiceType.class);
ret.setNamespaceContext (EbInterface40NamespaceContext.getInstance ());
return ret;
} | Create a writer builder for Ebi40InvoiceType.
@return The builder and never <code>null</code> |
@Nonnull
public static EbInterfaceWriter <Ebi41InvoiceType> ebInterface41 ()
{
final EbInterfaceWriter <Ebi41InvoiceType> ret = EbInterfaceWriter.create (Ebi41InvoiceType.class);
ret.setNamespaceContext (EbInterface41NamespaceContext.getInstance ());
return ret;
} | Create a writer builder for Ebi41InvoiceType.
@return The builder and never <code>null</code> |
@Nonnull
public static EbInterfaceWriter <Ebi42InvoiceType> ebInterface42 ()
{
final EbInterfaceWriter <Ebi42InvoiceType> ret = EbInterfaceWriter.create (Ebi42InvoiceType.class);
ret.setNamespaceContext (EbInterface42NamespaceContext.getInstance ());
return ret;
} | Create a writer builder for Ebi42InvoiceType.
@return The builder and never <code>null</code> |
@Nonnull
public static EbInterfaceWriter <Ebi43InvoiceType> ebInterface43 ()
{
final EbInterfaceWriter <Ebi43InvoiceType> ret = EbInterfaceWriter.create (Ebi43InvoiceType.class);
ret.setNamespaceContext (EbInterface43NamespaceContext.getInstance ());
return ret;
} | Create a writer builder for Ebi43InvoiceType.
@return The builder and never <code>null</code> |
@Nonnull
public static EbInterfaceWriter <Ebi50InvoiceType> ebInterface50 ()
{
final EbInterfaceWriter <Ebi50InvoiceType> ret = EbInterfaceWriter.create (Ebi50InvoiceType.class);
ret.setNamespaceContext (EbInterface50NamespaceContext.getInstance ());
return ret;
} | Create a writer builder for Ebi50InvoiceType.
@return The builder and never <code>null</code> |
public static CallbacksManager init(Bundle bundle, Object... callbackHandlers) {
if (bundle == null) {
return new CallbacksManager();
}
CallbacksManager callbacksManager = new CallbacksManager();
ArrayList<TaskHandler> taskProxies = bundle.getParcelableArrayList(TASK_PROXY_LIST);
if (taskProxies != null) {
callbacksManager.proxyTasks.addAll(taskProxies);
}
if (callbackHandlers != null) {
for (TaskHandler proxyTask : new ArrayList<TaskHandler>(callbacksManager.proxyTasks)) {
proxyTask.clearCallbacks();
proxyTask.appendCallbacks(callbackHandlers);
}
}
return callbacksManager;
} | Call from within your activity or fragment onCreate method.
@param bundle the onSaveInstance bundle
@param callbackHandlers an array of callback handlers to mange
@return an instance of {@link CallbacksManager} |
public void linkCallbacks(Object... callbackHandlers) {
if (callbackHandlers != null) {
for (TaskHandler proxyTask : new ArrayList<TaskHandler>(proxyTasks)) {
proxyTask.clearCallbacks();
proxyTask.appendCallbacks(callbackHandlers);
}
}
} | Links the specified callback handlers to their respective tasks.
@param callbackHandlers an array of callback handlers |
public void onSaveInstanceState(Bundle bundle) {
bundle.putParcelableArrayList(TASK_PROXY_LIST, proxyTasks);
for (TaskHandler proxyTask : proxyTasks) {
bundle.putParcelable(GROUNDY_PROXY_KEY_PREFIX + proxyTask.getTaskId(), proxyTask);
}
} | Saves the current callback handlers information in order to restore them after the
configuration change.
@param bundle the same bundle you receive from within your activity or fragment
onSaveInstanceState method |
@Nonnull
public static <T> EbInterfaceValidator <T> create (@Nonnull final Class <T> aClass)
{
return new EbInterfaceValidator <> (aClass);
} | Create a new validation builder.
@param aClass
The UBL class to be validated. May not be <code>null</code>.
@return The new validation builder. Never <code>null</code>.
@param <T>
The ebInterface document implementation type |
public static <T extends Enum<T>> OperationStatisticBuilder<T> operation(Class<T> type) {
return new OperationStatisticBuilder<>(type);
} | Operation.
@param <T> the generic type
@param type the type
@return the operation statistic builder |
public void addFields(List<ModelFieldBean> modelFields) {
Assert.notNull(modelFields, "modelFields must not be null");
for (ModelFieldBean bean : modelFields) {
this.fields.put(bean.getName(), bean);
}
} | Add all provided fields to the collection of fields
@param modelFields collection of {@link ModelFieldBean} |
public void addField(ModelFieldBean bean) {
Assert.notNull(bean, "ModelFieldBean must not be null");
this.fields.put(bean.getName(), bean);
} | Adds one instance of {@link ModelFieldBean} to the internal collection of fields
@param bean instance of {@link ModelFieldBean} |
public static void d(String tag, String msg) {
if (logEnabled) {
Log.d(tag, msg);
}
} | Sends a debug message to the log.
@param tag Tag to use
@param msg Message to send |
public static void e(String tag, String msg) {
if (logEnabled) {
Log.e(tag, msg);
}
} | Send an error message to the log.
@param tag Tag to use
@param msg Message to send |
public static void e(String tag, String msg, Throwable tr) {
if (logEnabled) {
Log.e(tag, msg, tr);
}
} | Send an error message to the log.
@param tag Tag to use
@param msg Message to send
@param tr Throwable to dump |
public static Groundy create(Class<? extends GroundyTask> groundyTask) {
if (groundyTask == null) {
throw new IllegalStateException("GroundyTask no provided");
}
return new Groundy(groundyTask);
} | Creates a new Groundy instance ready to be queued or executed. You can configure it by adding
arguments ({@link #args(android.os.Bundle)}), setting a group id ({@link #group(int)}) or
providing a callback ({@link #callback(Object...)}).
<p/>
You must configure the value <b>before</b> queueing or executing it.
@param groundyTask reference of the groundy value implementation
@return new Groundy instance (does not execute anything) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.