code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public Groundy service(Class<? extends GroundyService> groundyClass) {
if (groundyClass == GroundyService.class) {
throw new IllegalStateException(
"This method is meant to set a different GroundyService implementation. "
+ "You cannot use GroundyService.class, http://i.imgur.com/IR23PAe.png");
}
checkAlreadyProcessed();
mGroundyClass = groundyClass;
return this;
} | This allows you to use a different GroundyService implementation.
@param groundyClass a different Groundy service implementation
@return itself |
public Groundy arg(String key, String value) {
mArgs.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 Groundy arg(String key, CharSequence value) {
mArgs.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 Groundy arg(String key, Parcelable value) {
mArgs.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 Groundy arg(String key, Parcelable[] value) {
mArgs.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 Groundy addIntegerArrayList(String key, ArrayList<Integer> value) {
mArgs.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 Groundy addStringArrayList(String key, ArrayList<String> value) {
mArgs.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 Groundy arg(String key, ArrayList<CharSequence> value) {
mArgs.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 Groundy arg(String key, Serializable value) {
mArgs.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 Groundy arg(String key, String[] value) {
mArgs.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 Groundy arg(String key, CharSequence[] value) {
mArgs.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 Groundy arg(String key, Bundle value) {
mArgs.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 |
public static Association associate(final Object object) {
return new Association() {
@Override
public Association withChild(Object child) {
associate(child, object);
return this;
}
@Override
public Association withParent(Object parent) {
associate(object, parent);
return this;
}
};
} | Create an {@code Association} instance for the supplied object.
@param object the object to be associated
@return an association instance |
public static Dissociation dissociate(final Object object) {
return new Dissociation() {
@Override
public Dissociation fromChild(Object child) {
dissociate(child, object);
return this;
}
@Override
public Dissociation fromParent(Object parent) {
dissociate(object, parent);
return this;
}
};
} | Create a {@code Dissociation} instance for the supplied object.
@param object the object to be dissociated
@return a dissociation instance |
public static TreeNode nodeFor(Object object) {
TreeNode node = getTreeNode(object);
return node == null ? null : new ContextAwareTreeNode(node, object);
} | Return the {@code TreeNode} associated with this object.
<p>
Returns {@code null} if the supplied object has no associated context node.
@param object object to lookup node for
@return {@code TreeNode} associated with this object |
public Set<TreeNode> query(Query query) {
return query.execute(Collections.singleton(root));
} | Run the supplied {@code Query} against this {@code ContextManager}'s
root context.
<p>
The initial node in the queries traversal will be the node whose children
form the root set of this {@code ContextManager}. That is, the following
code will select the root set of this instance.<br>
<pre>
public static Set<TreeNode> roots(ContextManager manager) {
return manager.query(QueryBuilder.queryBuilder().children().build());
}
</pre>
@param query the query to execute
@return the set of nodes selected by the query |
public TreeNode queryForSingleton(Query query) throws IllegalStateException {
return query(queryBuilder().chain(query).ensureUnique().build()).iterator().next();
} | Return the unique node selected by running this query against this
{@code ContextManager}'s root context.
<p>
If this query does not return a single unique result then an
{@code IllegalStateException} will be thrown. More details on the query
execution context can be found in {@link #query(Query)}.
@param query the query to execute
@return the node selected by the query
@throws IllegalStateException if the query does not select a unique node
@see #query(Query)
@see QueryBuilder#ensureUnique() |
static GroundyTask get(Class<? extends GroundyTask> taskClass, Context context) {
if (CACHE.containsKey(taskClass)) {
return CACHE.get(taskClass);
}
GroundyTask groundyTask = null;
try {
L.d(TAG, "Instantiating " + taskClass);
Constructor ctc = taskClass.getConstructor();
groundyTask = (GroundyTask) ctc.newInstance();
if (groundyTask.canBeCached()) {
CACHE.put(taskClass, groundyTask);
} else if (CACHE.containsKey(taskClass)) {
CACHE.remove(taskClass);
}
groundyTask.setContext(context);
groundyTask.onCreate();
return groundyTask;
} catch (Exception e) {
L.e(TAG, "Unable to create value for call " + taskClass, e);
}
return groundyTask;
} | Builds a GroundyTask based on call.
@param taskClass groundy value implementation class
@param context used to instantiate the value
@return An instance of a GroundyTask if a given call is valid null otherwise |
public Node querySelector(String selectors) throws NodeSelectorException {
Set<Node> result = querySelectorAll(selectors);
if (result.isEmpty()) {
return null;
}
return result.iterator().next();
} | {@inheritDoc} |
public Set<Node> querySelectorAll(String selectors) throws NodeSelectorException {
Assert.notNull(selectors, "selectors is null!");
List<List<Selector>> groups;
try {
Scanner scanner = new Scanner(selectors);
groups = scanner.scan();
} catch (ScannerException e) {
throw new NodeSelectorException(e);
}
Set<Node> results = new LinkedHashSet<Node>();
for (List<Selector> parts : groups) {
Set<Node> result = check(parts);
if (!result.isEmpty()) {
results.addAll(result);
}
}
return results;
} | {@inheritDoc} |
private Set<Node> check(List<Selector> parts) throws NodeSelectorException {
Set<Node> result = new LinkedHashSet<Node>();
result.add(root);
for (Selector selector : parts) {
NodeTraversalChecker checker = new TagChecker(selector);
result = checker.check(result, root);
if (selector.hasSpecifiers()) {
for (Specifier specifier : selector.getSpecifiers()) {
switch (specifier.getType()) {
case ATTRIBUTE:
checker = new AttributeSpecifierChecker((AttributeSpecifier) specifier);
break;
case PSEUDO:
if (specifier instanceof PseudoClassSpecifier) {
checker = new PseudoClassSpecifierChecker((PseudoClassSpecifier) specifier);
} else if (specifier instanceof PseudoNthSpecifier) {
checker = new PseudoNthSpecifierChecker((PseudoNthSpecifier) specifier);
}
break;
case NEGATION:
final Set<Node> negationNodes = checkNegationSpecifier((NegationSpecifier) specifier);
checker = new NodeTraversalChecker() {
@Override
public Set<Node> check(Set<Node> nodes, Node root) throws NodeSelectorException {
Set<Node> set = new LinkedHashSet<Node>(nodes);
set.removeAll(negationNodes);
return set;
}
};
break;
}
result = checker.check(result, root);
if (result.isEmpty()) {
// Bail out early.
return result;
}
}
}
}
return result;
} | Check the list of selector <em>parts</em> and return a set of nodes with the result.
@param parts A list of selector <em>parts</em>.
@return A set of nodes.
@throws NodeSelectorException In case of an error. |
private Set<Node> checkNegationSpecifier(NegationSpecifier specifier) throws NodeSelectorException {
List<Selector> parts = new ArrayList<Selector>(1);
parts.add(specifier.getSelector());
return check(parts);
} | Check the {@link NegationSpecifier}.
<p/>
This method will add the {@link Selector} from the specifier in
a list and invoke {@link #check(List)} with that list as the argument.
@param specifier The negation specifier.
@return A set of nodes after invoking {@link #check(List)}.
@throws NodeSelectorException In case of an error. |
private void addEmptyElements() {
for (Node node : nodes) {
boolean empty = true;
if(node instanceof NestableNode) {
List<Node> nl = ((NestableNode) node).getChildren();
for (Node n : nl) {
if (n instanceof Element) {
empty = false;
break;
} else if (n instanceof Text) {
// TODO: Should we trim the text and see if it's length 0?
String value = ((Text) n).getContent();
if (value.length() > 0) {
empty = false;
break;
}
}
}
}
if (empty) {
result.add(node);
}
}
} | Add {@code :empty} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#empty-pseudo"><code>:empty</code> pseudo-class</a> |
private void addFirstChildElements() {
for (Node node : nodes) {
if (DOMHelper.getPreviousSiblingElement(node) == null) {
result.add(node);
}
}
} | Add {@code :first-child} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#first-child-pseudo"><code>:first-child</code> pseudo-class</a> |
private void addFirstOfType() {
for (Node node : nodes) {
Node n = DOMHelper.getPreviousSiblingElement(node);
while (n != null) {
if (DOMHelper.getNodeName(n).equals(DOMHelper.getNodeName(node))) {
break;
}
n = DOMHelper.getPreviousSiblingElement(n);
}
if (n == null) {
result.add(node);
}
}
} | Add {@code :first-of-type} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#first-of-type-pseudo"><code>:first-of-type</code> pseudo-class</a> |
private void addLastChildElements() {
for (Node node : nodes) {
if (DOMHelper.getNextSiblingElement(node) == null) {
result.add(node);
}
}
} | Add {@code :last-child} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#last-child-pseudo"><code>:last-child</code> pseudo-class</a> |
private void addLastOfType() {
for (Node node : nodes) {
Node n = DOMHelper.getNextSiblingElement(node);
while (n != null) {
if (DOMHelper.getNodeName(n).equals(DOMHelper.getNodeName(node))) {
break;
}
n = DOMHelper.getNextSiblingElement(n);
}
if (n == null) {
result.add(node);
}
}
} | Add {@code :last-of-type} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#last-of-type-pseudo"><code>:last-of-type</code> pseudo-class</a> |
private void addOnlyChildElements() {
for (Node node : nodes) {
if (DOMHelper.getPreviousSiblingElement(node) == null &&
DOMHelper.getNextSiblingElement(node) == null) {
result.add(node);
}
}
} | Add {@code :only-child} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#only-child-pseudo"><code>:only-child</code> pseudo-class</a> |
private void addOnlyOfTypeElements() {
for (Node node : nodes) {
Node n = DOMHelper.getPreviousSiblingElement(node);
while (n != null) {
if (DOMHelper.getNodeName(n).equals(DOMHelper.getNodeName(node))) {
break;
}
n = DOMHelper.getPreviousSiblingElement(n);
}
if (n == null) {
n = DOMHelper.getNextSiblingElement(node);
while (n != null) {
if (DOMHelper.getNodeName(n).equals(DOMHelper.getNodeName(node))) {
break;
}
n = DOMHelper.getNextSiblingElement(n);
}
if (n == null) {
result.add(node);
}
}
}
} | Add {@code :only-of-type} elements.
@see <a href="http://www.w3.org/TR/css3-selectors/#only-of-type-pseudo"><code>:only-of-type</code> pseudo-class</a> |
private void addRootElement() {
if (root instanceof Document) {
// Get the single element child of the document node.
// There could be a doctype node and comment nodes that we must skip.
Element element = DOMHelper.getFirstChildElement(root);
Assert.notNull(element, "there should be a root element!");
result.add(element);
} else {
Assert.isTrue(root instanceof Element, "root must be a document or element node!");
result.add(root);
}
} | Add the {@code :root} element.
@see <a href="http://www.w3.org/TR/css3-selectors/#root-pseudo"><code>:root</code> pseudo-class</a> |
public boolean hasOnlyName(OutputConfig outputConfig) {
if (StringUtils.hasText(this.name) && !StringUtils.hasText(this.type)
&& this.defaultValue == null && !StringUtils.hasText(this.dateFormat)
&& !StringUtils.hasText(this.mapping) && this.persist == null
&& !StringUtils.hasText(this.convert)) {
if (outputConfig.getOutputFormat() == OutputFormat.EXTJS4) {
return this.useNull == null;
}
else if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2) {
return this.allowNull == null;
}
else if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
return this.allowNull == null && this.critical == null
&& !StringUtils.hasText(this.calculate)
&& (this.validators == null || this.validators.isEmpty())
&& (this.depends == null || this.depends.isEmpty())
&& this.reference == null && this.allowBlank == null
&& this.unique == null;
}
}
return false;
} | Returns true if only the name property is set |
public void setModelType(ModelType type) {
this.modelType = type;
if (type != ModelType.AUTO) {
this.type = type.getJsName();
}
else {
this.type = null;
}
} | Type of the field. Property '
<a href="http://docs.sencha.com/ext-js/4-2/#!/api/Ext.data.Field-cfg-type" >type
</a>' in JS.
@param type new type for the field |
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
if (!request.getServletPath().endsWith("insecure")) {
response.addHeader("Content-Security-Policy", buildCSPHeader());
}
request.getRequestDispatcher("WEB-INF/chatq.jspx").forward(request, response);
} | Processes requests for both HTTP <code>GET</code> and <code>POST</code>
methods.
@param request servlet request
@param response servlet response
@throws ServletException if a servlet-specific error occurs
@throws IOException if an I/O error occurs |
public void merge(ExponentialHistogram b) {
if (b.mergeThreshold != mergeThreshold) {
throw new IllegalArgumentException();
}
merge(b.boxes, b.total);
} | Merge the supplied ExponentialHistogram in to this one.
@param b histogram to merge
@throws IllegalArgumentException if the two merge-thresholds are not equals |
public void insert(long time, long count) throws IllegalArgumentException {
if (count < 0) {
throw new IllegalArgumentException("negative count");
} else if (count > 0) {
if (time == MIN_VALUE) {
//MIN_VALUE means a box is unused so we avoid it
time++;
}
merge(makeBoxes(time, count), count);
}
} | Bulk insert {@code count} events at {@code time}.
@param time event time
@param count event count
@throws IllegalArgumentException if count is negative |
public void insert(long time) {
if (time == MIN_VALUE) {
time++;
}
total += 1L;
for (int logSize = 0; ; logSize++) {
ensureCapacity(logSize);
int insertIndex = insert[logSize];
long previous = boxes[insertIndex];
boxes[insertIndex--] = time;
if (insertIndex < min_l(logSize)) {
insertIndex = max_l(logSize) - 1;
}
insert[logSize] = insertIndex;
if (previous == MIN_VALUE) {
//previous unoccupied
long finalSize = 1L << logSize;
if (finalSize > last) {
last = finalSize;
}
return;
} else if ((time - previous) < window) {
//no space available - time to merge
time = boxes[insertIndex];
if (time == MIN_VALUE) {
//previous expired - assume expiry of it's partner
total -= 1L << logSize;
return;
} else {
boxes[insertIndex] = MIN_VALUE;
}
} else {
//previous aged out - decrement size
total -= 1L << logSize;
return;
}
}
} | Insert a single event at {@code time}
@param time event timestamp |
public long expire(long time) {
for (int logSize = (Long.SIZE - 1) - numberOfLeadingZeros(last); logSize >= 0; logSize--) {
boolean live = false;
for (int i = min_l(logSize); i < max_l(logSize); i++) {
long end = boxes[i];
if (end != MIN_VALUE) {
if ((time - end) >= window) {
total -= 1L << logSize;
boxes[i] = MIN_VALUE;
} else {
live = true;
}
}
}
if (live) {
last = 1L << logSize;
return count();
}
}
last = 0;
return 0;
} | Expire old events.
@param time current timestamp
@return the count following expiry |
public ExponentialHistogram split(double fraction) {
long[] originalBoxes = boxes;
ExponentialHistogram that = new ExponentialHistogram(epsilon, window);
that.total = round(this.total * fraction);
this.total -= that.total;
int[] thisCanonical = tailedLCanonical(mergeThreshold - 1, this.total);
int[] thatCanonical = tailedLCanonical(mergeThreshold - 1, that.total);
this.last = this.total == 0 ? 0 : 1L << (thisCanonical.length - 1);
that.last = that.total == 0 ? 0 : 1L << (thatCanonical.length - 1);
this.initializeArrays(thisCanonical.length - 1);
that.initializeArrays(thatCanonical.length - 1);
for (int logSize = 0; logSize < max(thisCanonical.length, thatCanonical.length); logSize++) {
int thisBoxCount = logSize < thisCanonical.length ? thisCanonical[logSize] : 0;
int thatBoxCount = logSize < thatCanonical.length ? thatCanonical[logSize] : 0;
/*
* transfer(...) reverse-sorts putting the highest (i.e. most recent) stuff first. This means we bias recent stuff
* in to the boxes we transfer to first, and older stuff in to the one we transfer second. In order to minimize
* the effect this has on the stats we care about we do the transfers based on the split fraction. We target
* newer stuff in to the smaller split so that the better stats are on the newer stuff. The upshot of this is
* that we are biasing high percentiles up, and low percentiles down. The former is 'better' the latter is
* just life. Sorry!
*/
if (fraction < 0.5) {
transfer(originalBoxes, that.boxes, logSize, thatBoxCount);
transfer(originalBoxes, this.boxes, logSize, thisBoxCount);
} else {
transfer(originalBoxes, this.boxes, logSize, thisBoxCount);
transfer(originalBoxes, that.boxes, logSize, thatBoxCount);
}
}
return that;
} | Split an exponential histogram off this one.
<p>
The returned histogram will contain {code fraction} of the events in this one.
</p>
@param fraction splitting fraction
@return the new histogram |
@PUT
@Consumes("application/json")
public void putJson(IncomingMessage msg) {
chatBean.addMessage(msg.nick, msg.content);
} | PUT method for updating or creating an instance of ChatService
@param content representation for the resource
@return an HTTP response with content of the updated or created resource. |
protected void callback(String name, Bundle resultData) {
if (resultData == null) resultData = new Bundle();
resultData.putString(Groundy.KEY_CALLBACK_NAME, name);
resultData.putSerializable(Groundy.TASK_IMPLEMENTATION, getClass());
send(OnCallback.class, resultData);
} | Sends this data to the callback methods annotated with the specified name.
@param name the name of the callback to invoke
@param resultData optional arguments to send |
public void updateProgress(int progress, Bundle extraData) {
if (mReceiver != null) {
Bundle resultData = new Bundle();
resultData.putInt(Groundy.PROGRESS, progress);
resultData.putSerializable(Groundy.TASK_IMPLEMENTATION, getClass());
if (extraData != null) resultData.putAll(extraData);
send(OnProgress.class, resultData);
}
} | Prepare and sends a progress update to the current receiver. Callback used is {@link
com.telly.groundy.annotations.OnProgress} and it will contain a bundle with an integer extra
called {@link Groundy#PROGRESS}
@param extraData additional information to send to the progress callback
@param progress percentage to send to receiver |
@Nonnull
public static <T> EbInterfaceReader <T> create (@Nonnull final Class <T> aClass)
{
return new EbInterfaceReader <> (aClass);
} | Create a new reader builder.
@param aClass
The UBL class to be read. May not be <code>null</code>.
@return The new reader builder. Never <code>null</code>.
@param <T>
The ebInterface document implementation type |
private void mergeProxiesWithClassHierarchy() {
for (Map.Entry<HandlerAndTask, Set<ProxyImplContent>> elementSetEntry : implMap.entrySet()) {
final HandlerAndTask handlerAndTask = elementSetEntry.getKey();
// 1. merge super tasks, for same handler
final Set<Element> superTasks = getSuperClasses(handlerAndTask.task);
for (Element superTask : superTasks) {
final HandlerAndTask handlerAndSuperTask = new HandlerAndTask(handlerAndTask.handler, superTask);
if (implMap.containsKey(handlerAndSuperTask)) {
appendNonExistentCallbacks(handlerAndSuperTask, handlerAndTask);
}
}
// 2. merge super handlers, for same task
final Set<Element> superHandlers = getSuperClasses(handlerAndTask.handler);
for (Element superHandler : superHandlers) {
final HandlerAndTask superHandlerAndTask = new HandlerAndTask(superHandler, handlerAndTask.task);
if (implMap.containsKey(superHandlerAndTask)) {
appendNonExistentCallbacks(superHandlerAndTask, handlerAndTask);
}
// 3. merge super handlers, for super tasks
for (Element superTask : superTasks) {
final HandlerAndTask superHandlerAndSuperTask = new HandlerAndTask(superHandler, superTask);
if (implMap.containsKey(superHandlerAndSuperTask)) {
appendNonExistentCallbacks(superHandlerAndSuperTask, handlerAndTask);
}
}
}
}
} | Merges callbacks implementations taking into account the supper types of the handlers and
the tasks.
1. It will look for callbacks of the super classes of the tasks, in the same handler.
2. It will look for callbacks of the super classes of the handler, that use the same task.
3. It will look for callbacks of the super classes of the handler, that use super classes of the task. |
private void appendNonExistentCallbacks(HandlerAndTask from, HandlerAndTask to) {
final Set<ProxyImplContent> proxyImplContentsTo = implMap.get(to);
if (proxyImplContentsTo == null) {
return;
}
final Set<ProxyImplContent> proxyImplContentsFrom = implMap.get(from);
if (proxyImplContentsFrom == null) {
return;
}
for (ProxyImplContent proxyImplContentFrom : proxyImplContentsFrom) {
boolean exists = false;
for (ProxyImplContent proxyImplContentTo : proxyImplContentsTo) {
if (proxyImplContentTo.annotation.equals(proxyImplContentFrom.annotation)) {
exists = true;
break;
}
}
if (!exists) {
proxyImplContentsTo.add(proxyImplContentFrom);
}
}
} | Copy all callbacks implementations from -> to the specified set. It makes sure
to copy the callbacks that don't exist already on the destination set.
@param from key for the set of callbacks to copy from
@param to key for the set of callbacks to copy to |
private static List<NameAndType> getParamNames(Element callbackMethod) {
Element parentClass = callbackMethod.getEnclosingElement();
String methodFullInfo = parentClass + "#" + callbackMethod;
ExecutableElement method = (ExecutableElement) callbackMethod;
if (!method.getModifiers().contains(Modifier.PUBLIC)) {
LOGGER.info(methodFullInfo + " must be public.");
System.exit(-1);
}
if (method.getReturnType().getKind() != TypeKind.VOID) {
LOGGER.info(methodFullInfo + " must return void.");
System.exit(-1);
}
List<NameAndType> paramNames = new ArrayList<NameAndType>();
for (VariableElement param : method.getParameters()) {
Param paramAnnotation = param.getAnnotation(Param.class);
if (paramAnnotation == null) {
LOGGER.info(methodFullInfo
+ ": all parameters must be annotated with the @"
+ Param.class.getName());
System.exit(-1);
}
paramNames.add(new NameAndType(paramAnnotation.value(), param.asType().toString()));
}
return paramNames;
} | Makes sure method is public, returns void and all its parameters are annotated too. |
public boolean hasAnyProperties() {
return StringUtils.hasText(this.type) || StringUtils.hasText(this.association)
|| StringUtils.hasText(this.child) || StringUtils.hasText(this.parent)
|| StringUtils.hasText(this.role) || StringUtils.hasText(this.inverse);
} | Tests if something is set. |
public static void writeModel(HttpServletRequest request,
HttpServletResponse response, Class<?> clazz, OutputFormat format)
throws IOException {
writeModel(request, response, clazz, format, IncludeValidation.NONE, false);
} | Instrospects the provided class, creates a model object (JS code) and writes it
into the response. Creates compressed JS code. Method ignores any validation
annotations.
@param request the http servlet request
@param response the http servlet response
@param clazz class that the generator should introspect
@param format specifies which code (ExtJS or Touch) the generator should create.
@throws IOException
@see #writeModel(HttpServletRequest, HttpServletResponse, Class, OutputFormat,
boolean) |
public static void writeModel(HttpServletRequest request,
HttpServletResponse response, Class<?> clazz, OutputFormat format,
IncludeValidation includeValidation, boolean debug) throws IOException {
OutputConfig outputConfig = new OutputConfig();
outputConfig.setIncludeValidation(includeValidation);
outputConfig.setOutputFormat(format);
outputConfig.setDebug(debug);
ModelBean model = createModel(clazz, outputConfig);
writeModel(request, response, model, outputConfig);
} | Instrospects the provided class, creates a model object (JS code) and writes it
into the response.
@param request the http servlet request
@param response the http servlet response
@param clazz class that the generator should introspect
@param format specifies which code (ExtJS or Touch) the generator should create
@param includeValidation specifies if any validation configurations should be added
to the model code
@param debug if true the generator creates the output in pretty format, false the
output is compressed
@throws IOException |
public static void writeModel(HttpServletRequest request,
HttpServletResponse response, ModelBean model, OutputFormat format)
throws IOException {
writeModel(request, response, model, format, false);
} | Creates a model object (JS code) based on the provided {@link ModelBean} and writes
it into the response. Creates compressed JS code.
@param request the http servlet request
@param response the http servlet response
@param model {@link ModelBean} describing the model to be generated
@param format specifies which code (ExtJS or Touch) the generator should create.
@throws IOException |
public static void writeModel(HttpServletRequest request,
HttpServletResponse response, ModelBean model, OutputFormat format,
boolean debug) throws IOException {
OutputConfig outputConfig = new OutputConfig();
outputConfig.setDebug(debug);
outputConfig.setOutputFormat(format);
writeModel(request, response, model, outputConfig);
} | Creates a model object (JS code) based on the provided ModelBean and writes it into
the response.
@param request the http servlet request
@param response the http servlet response
@param model {@link ModelBean} describing the model to be generated
@param format specifies which code (ExtJS or Touch) the generator should create.
@param debug if true the generator creates the output in pretty format, false the
output is compressed
@throws IOException |
public static ModelBean createModel(Class<?> clazz,
IncludeValidation includeValidation) {
OutputConfig outputConfig = new OutputConfig();
outputConfig.setIncludeValidation(includeValidation);
return createModel(clazz, outputConfig);
} | Instrospects the provided class and creates a {@link ModelBean} instance. A program
could customize this and call
{@link #generateJavascript(ModelBean, OutputFormat, boolean)} or
{@link #writeModel(HttpServletRequest, HttpServletResponse, ModelBean, OutputFormat)}
to create the JS code. Models are being cached. A second call with the same
parameters will return the model from the cache.
@param clazz the model will be created based on this class.
@param includeValidation specifies what validation configuration should be added
@return a instance of {@link ModelBean} that describes the provided class and can
be used for Javascript generation. |
public static String generateJavascript(Class<?> clazz, OutputFormat format,
boolean debug) {
OutputConfig outputConfig = new OutputConfig();
outputConfig.setIncludeValidation(IncludeValidation.NONE);
outputConfig.setOutputFormat(format);
outputConfig.setDebug(debug);
ModelBean model = createModel(clazz, outputConfig);
return generateJavascript(model, outputConfig);
} | Instrospects the provided class, creates a model object (JS code) and returns it.
This method does not add any validation configuration.
@param clazz class that the generator should introspect
@param format specifies which code (ExtJS or Touch) the generator should create
@param debug if true the generator creates the output in pretty format, false the
output is compressed
@return the generated model object (JS code) |
public static String generateJavascript(ModelBean model, OutputFormat format,
boolean debug) {
OutputConfig outputConfig = new OutputConfig();
outputConfig.setOutputFormat(format);
outputConfig.setDebug(debug);
return generateJavascript(model, outputConfig);
} | Creates JS code based on the provided {@link ModelBean} in the specified
{@link OutputFormat}. Code can be generated in pretty or compressed format. The
generated code is cached unless debug is true. A second call to this method with
the same model name and format will return the code from the cache.
@param model generate code based on this {@link ModelBean}
@param format specifies which code (ExtJS or Touch) the generator should create
@param debug if true the generator creates the output in pretty format, false the
output is compressed
@return the generated model object (JS code) |
public List<List<Selector>> scan() throws ScannerException {
char[] data = input.toCharArray();
int cs;
int top;
int[] stack = new int[32];
int eof = data.length;
int p = 0;
int pe = eof;
int mark = 0;
LinkedList<List<Selector>> selectors = new LinkedList<List<Selector>>();
// List<Selector> parts = new LinkedList<Selector>();
List<Selector> parts = null;
String tagName = Selector.UNIVERSAL_TAG;
String negationTagName = Selector.UNIVERSAL_TAG;
Selector.Combinator combinator = null;
List<Specifier> specifiers = new LinkedList<Specifier>();
String attributeName = null;
String attributeValue = null;
AttributeSpecifier.Match attributeMatch = null;
String pseudoNthClass = null;
boolean isNegation = false;
Selector negationSelector = null;
// line 1538 "../java/se/fishtank/css/selectors/scanner/Scanner.java"
{
cs = Scanner_start;
top = 0;
}
// line 221 "Scanner.java.rl"
// line 1546 "../java/se/fishtank/css/selectors/scanner/Scanner.java"
{
int _klen;
int _trans = 0;
int _acts;
int _nacts;
int _keys;
int _goto_targ = 0;
_goto: while (true) {
switch ( _goto_targ ) {
case 0:
if ( p == pe ) {
_goto_targ = 4;
continue _goto;
}
if ( cs == 0 ) {
_goto_targ = 5;
continue _goto;
}
case 1:
_match: do {
_keys = _Scanner_key_offsets[cs];
_trans = _Scanner_index_offsets[cs];
_klen = _Scanner_single_lengths[cs];
if ( _klen > 0 ) {
int _lower = _keys;
int _mid;
int _upper = _keys + _klen - 1;
while (true) {
if ( _upper < _lower )
break;
_mid = _lower + ((_upper-_lower) >> 1);
if ( data[p] < _Scanner_trans_keys[_mid] )
_upper = _mid - 1;
else if ( data[p] > _Scanner_trans_keys[_mid] )
_lower = _mid + 1;
else {
_trans += (_mid - _keys);
break _match;
}
}
_keys += _klen;
_trans += _klen;
}
_klen = _Scanner_range_lengths[cs];
if ( _klen > 0 ) {
int _lower = _keys;
int _mid;
int _upper = _keys + (_klen<<1) - 2;
while (true) {
if ( _upper < _lower )
break;
_mid = _lower + (((_upper-_lower) >> 1) & ~1);
if ( data[p] < _Scanner_trans_keys[_mid] )
_upper = _mid - 2;
else if ( data[p] > _Scanner_trans_keys[_mid+1] )
_lower = _mid + 2;
else {
_trans += ((_mid - _keys)>>1);
break _match;
}
}
_trans += _klen;
}
} while (false);
_trans = _Scanner_indicies[_trans];
cs = _Scanner_trans_targs[_trans];
if ( _Scanner_trans_actions[_trans] != 0 ) {
_acts = _Scanner_trans_actions[_trans];
_nacts = (int) _Scanner_actions[_acts++];
while ( _nacts-- > 0 )
{
switch ( _Scanner_actions[_acts++] )
{
case 0:
// line 44 "Scanner.java.rl"
{
AttributeSpecifier specifier;
if (attributeValue != null) {
specifier = new AttributeSpecifier(attributeName, attributeValue, attributeMatch);
} else {
specifier = new AttributeSpecifier(attributeName);
}
specifiers.add(specifier);
}
break;
case 1:
// line 55 "Scanner.java.rl"
{
attributeName = getSlice(mark, p);
}
break;
case 2:
// line 59 "Scanner.java.rl"
{
String m = getSlice(mark, p);
if ("=".equals(m)) {
attributeMatch = AttributeSpecifier.Match.EXACT;
} else if ("~=".equals(m)) {
attributeMatch = AttributeSpecifier.Match.LIST;
} else if ("|=".equals(m)) {
attributeMatch = AttributeSpecifier.Match.HYPHEN;
} else if ("^=".equals(m)) {
attributeMatch = AttributeSpecifier.Match.PREFIX;
} else if ("$=".equals(m)) {
attributeMatch = AttributeSpecifier.Match.SUFFIX;
} else if ("*=".equals(m)) {
attributeMatch = AttributeSpecifier.Match.CONTAINS;
}
}
break;
case 3:
// line 76 "Scanner.java.rl"
{
String value = getSlice(mark, p);
if (value.charAt(0) == '"' || value.charAt(0) == '\'') {
value = value.substring(1, value.length() - 1);
}
attributeValue = value;
}
break;
case 4:
// line 85 "Scanner.java.rl"
{
specifiers.add(new AttributeSpecifier("class",
getSlice(mark, p), AttributeSpecifier.Match.LIST));
}
break;
case 5:
// line 90 "Scanner.java.rl"
{
switch (data[p]) {
case ' ':
combinator = Selector.Combinator.DESCENDANT;
break;
case '>':
combinator = Selector.Combinator.CHILD;
break;
case '+':
combinator = Selector.Combinator.ADJACENT_SIBLING;
break;
case '~':
combinator = Selector.Combinator.GENERAL_SIBLING;
break;
}
}
break;
case 6:
// line 107 "Scanner.java.rl"
{
parts = new LinkedList<Selector>();
}
break;
case 7:
// line 111 "Scanner.java.rl"
{
selectors.add(parts);
}
break;
case 8:
// line 115 "Scanner.java.rl"
{
specifiers.add(new AttributeSpecifier("id",
getSlice(mark, p), AttributeSpecifier.Match.EXACT));
}
break;
case 9:
// line 120 "Scanner.java.rl"
{
mark = p;
}
break;
case 10:
// line 124 "Scanner.java.rl"
{
isNegation = true;
}
break;
case 11:
// line 128 "Scanner.java.rl"
{
specifiers.add(new NegationSpecifier(negationSelector));
isNegation = false;
}
break;
case 12:
// line 133 "Scanner.java.rl"
{
specifiers.add(new PseudoClassSpecifier(getSlice(mark, p)));
}
break;
case 13:
// line 137 "Scanner.java.rl"
{
specifiers.add(new PseudoNthSpecifier(pseudoNthClass, getSlice(mark, p)));
}
break;
case 14:
// line 141 "Scanner.java.rl"
{
pseudoNthClass = getSlice(mark, p);
}
break;
case 15:
// line 145 "Scanner.java.rl"
{
Selector selector;
List<Specifier> list = specifiers.isEmpty() ? null : specifiers;
if (isNegation) {
negationSelector = new Selector(negationTagName, list);
} else {
if (combinator == null) {
selector = new Selector(tagName, list);
} else {
selector = new Selector(tagName, combinator, list);
}
parts.add(selector);
tagName = Selector.UNIVERSAL_TAG;
combinator = null;
}
negationTagName = Selector.UNIVERSAL_TAG;
attributeName = null;
attributeValue = null;
attributeMatch = null;
pseudoNthClass = null;
specifiers = new LinkedList<Specifier>();
}
break;
case 16:
// line 170 "Scanner.java.rl"
{
if (isNegation) {
negationTagName = getSlice(mark, p);
} else {
tagName = getSlice(mark, p);
}
}
break;
case 17:
// line 28 "ScannerCommon.rl"
{ {stack[top++] = cs; cs = 150; _goto_targ = 2; if (true) continue _goto;} }
case 18:
// line 42 "ScannerCommon.rl"
{ {cs = stack[--top];_goto_targ = 2; if (true) continue _goto;} }
// line 1802 "../java/se/fishtank/css/selectors/scanner/Scanner.java"
}
}
}
case 2:
if ( cs == 0 ) {
_goto_targ = 5;
continue _goto;
}
if ( ++p != pe ) {
_goto_targ = 1;
continue _goto;
}
case 4:
if ( p == eof )
{
int __acts = _Scanner_eof_actions[cs];
int __nacts = (int) _Scanner_actions[__acts++];
while ( __nacts-- > 0 ) {
switch ( _Scanner_actions[__acts++] ) {
case 4:
// line 85 "Scanner.java.rl"
{
specifiers.add(new AttributeSpecifier("class",
getSlice(mark, p), AttributeSpecifier.Match.LIST));
}
break;
case 7:
// line 111 "Scanner.java.rl"
{
selectors.add(parts);
}
break;
case 8:
// line 115 "Scanner.java.rl"
{
specifiers.add(new AttributeSpecifier("id",
getSlice(mark, p), AttributeSpecifier.Match.EXACT));
}
break;
case 12:
// line 133 "Scanner.java.rl"
{
specifiers.add(new PseudoClassSpecifier(getSlice(mark, p)));
}
break;
case 15:
// line 145 "Scanner.java.rl"
{
Selector selector;
List<Specifier> list = specifiers.isEmpty() ? null : specifiers;
if (isNegation) {
negationSelector = new Selector(negationTagName, list);
} else {
if (combinator == null) {
selector = new Selector(tagName, list);
} else {
selector = new Selector(tagName, combinator, list);
}
parts.add(selector);
tagName = Selector.UNIVERSAL_TAG;
combinator = null;
}
negationTagName = Selector.UNIVERSAL_TAG;
attributeName = null;
attributeValue = null;
attributeMatch = null;
pseudoNthClass = null;
specifiers = new LinkedList<Specifier>();
}
break;
case 16:
// line 170 "Scanner.java.rl"
{
if (isNegation) {
negationTagName = getSlice(mark, p);
} else {
tagName = getSlice(mark, p);
}
}
break;
// line 1886 "../java/se/fishtank/css/selectors/scanner/Scanner.java"
}
}
}
case 5:
}
break; }
}
// line 222 "Scanner.java.rl"
if (cs < Scanner_first_final && p != pe) {
// TODO: Better error reporting ;)
throw new ScannerException("Bad input!");
}
return selectors;
} | Scan the {@link #input}.
@return A list of selector groups that contain a list of {@link Selector}s scanned.
@throws ScannerException If the input is invalid. |
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(pl.setblack.chatsample.web.ChatService.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(). |
private boolean hasSlf4jBinding(File file) throws MojoExecutionException {
try (JarFile jarFile = new JarFile(file)){
return jarFile.getEntry("org/slf4j/impl/StaticLoggerBinder.class") != null;
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
} | Returns true if the given jar file contains an SLF4J binding
@param file the file
@return true if the jar file contains an SLF4J binding |
@Nullable
public static Templates getXSLTTemplates (@Nonnull final EEbInterfaceVersion eVersion)
{
final String sNamespaceURI = eVersion.getNamespaceURI ();
final Templates ret = s_aRWLock.readLocked ( () -> s_aTemplates.get (sNamespaceURI));
if (ret != null)
return ret;
return s_aRWLock.writeLocked ( () -> {
// Try again in write lock
Templates ret2 = s_aTemplates.get (sNamespaceURI);
if (ret2 == null)
{
// Definitely not present - init
final IReadableResource aXSLTRes = eVersion.getXSLTResource ();
ret2 = XMLTransformerFactory.newTemplates (aXSLTRes);
if (ret2 == null)
LOGGER.error ("Failed to parse XSLT template " + aXSLTRes);
else
if (LOGGER.isDebugEnabled ())
LOGGER.debug ("Compiled XSLT template " + aXSLTRes);
s_aTemplates.put (sNamespaceURI, ret2);
}
return ret2;
});
} | Get the precompiled XSLT template to be used. It is lazily initialized upon
first call.
@param eVersion
The ebInterface version to be used. May not be <code>null</code>.
@return The XSLT {@link Templates} to be used to visualize invoices or
<code>null</code> if the template is buggy! |
@Nonnull
public static ESuccess visualize (@Nonnull final EEbInterfaceVersion eVersion,
@Nonnull final Source aSource,
@Nonnull final Result aResult)
{
ValueEnforcer.notNull (eVersion, "version");
// Get cache XSL templates
final Templates aTemplates = getXSLTTemplates (eVersion);
if (aTemplates == null)
return ESuccess.FAILURE;
// Start the main transformation
try
{
final Transformer aTransformer = aTemplates.newTransformer ();
aTransformer.transform (aSource, aResult);
return ESuccess.SUCCESS;
}
catch (final TransformerException ex)
{
LOGGER.error ("Failed to apply transformation for ebInterface " + eVersion + " invoice", ex);
return ESuccess.FAILURE;
}
} | Visualize a source to a result for a certain ebInterface version using
XSLT. This is the most generic method.
@param eVersion
ebInterface version to use.
@param aSource
Source.
@param aResult
Destination
@return {@link ESuccess} |
@Nullable
public static Document visualizeToDOMDocument (@Nonnull final EEbInterfaceVersion eVersion,
@Nonnull final Source aSource)
{
final Document aDoc = XMLFactory.newDocument ();
return visualize (eVersion, aSource, new DOMResult (aDoc)).isSuccess () ? aDoc : null;
} | Visualize a source to a DOM document for a certain ebInterface version.
@param eVersion
ebInterface version to use. May not be <code>null</code>.
@param aSource
Source. May not be <code>null</code>.
@return <code>null</code> if the XSLT could not be applied. |
@Nullable
public static Document visualizeToDOMDocument (@Nonnull final EEbInterfaceVersion eVersion,
@Nonnull final IReadableResource aResource)
{
return visualizeToDOMDocument (eVersion, TransformSourceFactory.create (aResource));
} | Visualize a source to a DOM document for a certain ebInterface version.
@param eVersion
ebInterface version to use. May not be <code>null</code>.
@param aResource
Source resource. May not be <code>null</code>.
@return <code>null</code> if the XSLT could not be applied. |
@Nullable
public static ESuccess visualizeToFile (@Nonnull final EEbInterfaceVersion eVersion,
@Nonnull final Source aSource,
@Nonnull final File aDestinationFile)
{
return visualize (eVersion, aSource, TransformResultFactory.create (aDestinationFile));
} | Visualize a source to a file for a certain ebInterface version.
@param eVersion
ebInterface version to use. May not be <code>null</code>.
@param aSource
Source. May not be <code>null</code>.
@param aDestinationFile
The file to write the result to. May not be <code>null</code>.
@return {@link ESuccess} |
@Nullable
public static ESuccess visualizeToFile (@Nonnull final EEbInterfaceVersion eVersion,
@Nonnull final IReadableResource aResource,
@Nonnull final File aDestinationFile)
{
return visualize (eVersion,
TransformSourceFactory.create (aResource),
TransformResultFactory.create (aDestinationFile));
} | Visualize a source to a file for a certain ebInterface version.
@param eVersion
ebInterface version to use. May not be <code>null</code>.
@param aResource
Source resource. May not be <code>null</code>.
@param aDestinationFile
The file to write the result to. May not be <code>null</code>.
@return {@link ESuccess} |
public static void downloadFile(Context context, String fromUrl, File toFile,
DownloadProgressListener listener) throws IOException {
downloadFile(context, fromUrl, toFile, listener, null);
} | Download a file at <code>fromUrl</code> to a file specified by <code>toFile</code>.
@param fromUrl An url pointing to a file to download
@param toFile File to save to, if existent will be overwrite
@param listener Callback that notifies the download progress
@throws java.io.IOException If fromUrl is invalid or there is any IO issue. |
public static void downloadFile(Context context, String fromUrl, File toFile,
DownloadProgressListener listener, DownloadCancelListener cancelListener) throws IOException {
downloadFileHandleRedirect(context, fromUrl, toFile, 0, listener, cancelListener);
} | Download a file at <code>fromUrl</code> to a file specified by <code>toFile</code>.
@param fromUrl An url pointing to a file to download
@param toFile File to save to, if existent will be overwrite
@param listener Callback that notifies the download progress
@param cancelListener Used to interrupt the download if necessary
@throws java.io.IOException If fromUrl is invalid or there is any IO issue. |
public static DownloadProgressListener getDownloadListenerForTask(final GroundyTask groundyTask) {
return new DownloadProgressListener() {
@Override
public void onProgress(String url, int progress) {
groundyTask.updateProgress(progress);
}
};
} | Returns a progress listener that will post progress to the specified groundyTask.
@param groundyTask the groundyTask to post progress to. Cannot be null.
@return a progress listener |
private static void downloadFileHandleRedirect(Context context, String fromUrl, File toFile,
int redirect, DownloadProgressListener listener, DownloadCancelListener cancelListener) throws IOException {
if (context == null) {
throw new RuntimeException("Context shall not be null");
}
if (!alreadyCheckedInternetPermission) {
checkForInternetPermissions(context);
}
if (redirect > MAX_REDIRECTS) {
throw new IOException("Too many redirects for " + fromUrl);
}
if (cancelListener != null && cancelListener.shouldCancelDownload()) {
return;
}
URL url = new URL(fromUrl);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
urlConnection.connect();
String redirectTarget = urlConnection.getHeaderField("Location");
if (redirectTarget != null) {
downloadFileHandleRedirect(context, redirectTarget, toFile, redirect + 1, listener,
cancelListener);
return;
}
if (cancelListener != null && cancelListener.shouldCancelDownload()) {
return;
}
InputStream input = urlConnection.getInputStream();
if ("gzip".equals(urlConnection.getContentEncoding())) {
input = new GZIPInputStream(input);
}
if (cancelListener != null && cancelListener.shouldCancelDownload()) {
input.close();
return;
}
OutputStream output = new FileOutputStream(toFile);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long total = 0;
int count;
int fileLength = urlConnection.getContentLength();
if (fileLength == -1 && listener != null) {
listener.onProgress(fromUrl, Groundy.NO_SIZE_AVAILABLE);
}
while ((count = input.read(buffer)) > 0) {// > 0 due zero sized streams
if (cancelListener != null && cancelListener.shouldCancelDownload()) {
output.close();
input.close();
return;
}
total += count;
output.write(buffer, 0, count);
if (listener != null && fileLength > 0) {
listener.onProgress(fromUrl, (int) (total * 100 / fileLength));
}
}
output.close();
input.close();
} | Internal version of {@link #downloadFile(Context, String, java.io.File,
DownloadUtils.DownloadProgressListener)}.
@param fromUrl the url to download from
@param toFile the file to download to
@param redirect true if it should accept redirects
@param listener used to report result back
@param cancelListener used to interrupt the download if necessary
@throws java.io.IOException |
public static Matcher<TreeNode> context(final Matcher<ContextElement> matcher) {
return new Matcher<TreeNode>() {
@Override
protected boolean matchesSafely(TreeNode t) {
return matcher.matches(t.getContext());
}
@Override
public String toString() {
return "a context that has " + matcher;
}
};
} | Returns a matcher that matches tree nodes whose {@link TreeNode#getContext()}
match against the supplied matcher.
@param matcher {@code ContextElement} matcher
@return a {@code TreeNode} matcher |
public static Matcher<ContextElement> attributes(final Matcher<Map<String, Object>> matcher) {
return new Matcher<ContextElement>() {
@Override
protected boolean matchesSafely(ContextElement t) {
return matcher.matches(t.attributes());
}
@Override
public String toString() {
return "an attributes " + matcher;
}
};
} | Returns a matcher that matches context elements whose {@link ContextElement#attributes()}
match against the supplied matcher.
@param matcher a {@code Map} (attributes) matcher
@return a {@code ContextElement} matcher |
public static Matcher<ContextElement> identifier(final Matcher<Class<?>> matcher) {
return new Matcher<ContextElement>() {
@Override
protected boolean matchesSafely(ContextElement t) {
return matcher.matches(t.identifier());
}
@Override
public String toString() {
return "an identifier that is " + matcher;
}
};
} | Returns a matcher that matches context elements whose {@link ContextElement#identifier()}
match against the supplied matcher.
@param matcher {@code Class<?>} matcher
@return a {@code ContextElement} matcher |
public static Matcher<Class<?>> subclassOf(final Class<?> klazz) {
return new Matcher<Class<?>>() {
@Override
protected boolean matchesSafely(Class<?> t) {
return klazz.isAssignableFrom(t);
}
@Override
public String toString() {
return "a subtype of " + klazz;
}
};
} | Returns a matcher that matches classes that are sub-types of the supplied
class.
@param klazz a potential super-type
@return a {@code Class<?>} matcher |
public static Matcher<Map<String, Object>> hasAttribute(final String key, final Object value) {
return new Matcher<Map<String, Object>>() {
@Override
protected boolean matchesSafely(Map<String, Object> object) {
return object.containsKey(key) && value.equals(object.get(key));
}
};
} | Returns a matcher that matches attribute maps that include the given
attribute entry.
@param key attribute name
@param value attribute value
@return a {@code Map<String, Object>} matcher |
@SafeVarargs
public static <T> Matcher<T> anyOf(final Matcher<? super T>... matchers) {
return new Matcher<T>() {
@Override
protected boolean matchesSafely(T object) {
for (Matcher<? super T> matcher : matchers) {
if (matcher.matches(object)) {
return true;
}
}
return false;
}
};
} | Returns a matcher that matches when against objects which match <em>any</em>
of the supplied matchers.
@param <T> type of the object to be matched
@param matchers list of matchers to match
@return a compound matcher |
public Object getValue(String expression, Class<?> expectedType) {
ValueExpression exp = factory.createValueExpression(
elManager.getELContext(),
bracket(expression), expectedType);
return exp.getValue(elManager.getELContext());
} | Evaluates an EL expression, and coerces the result to the specified type.
@param expression The EL expression to be evaluated.
@param expectedType Specifies the type that the resultant evaluation
will be coerced to.
@return The result of the expression evaluation. |
public void setValue(String expression, Object value) {
ValueExpression exp = factory.createValueExpression(
elManager.getELContext(),
bracket(expression), Object.class);
exp.setValue(elManager.getELContext(), value);
} | Sets an expression with a new value.
The target expression is evaluated, up to the last property resolution,
and the resultant (base, property) pair is set to the provided value.
@param expression The target expression
@param value The new value to set.
@throws PropertyNotFoundException if one of the property
resolutions failed because a specified variable or property
does not exist or is not readable.
@throws PropertyNotWritableException if the final variable or
property resolution failed because the specified
variable or property is not writable.
@throws ELException if an exception was thrown while attempting to
set the property or variable. The thrown exception
must be included as the cause property of this exception, if
available. |
public void setVariable(String var, String expression) {
ValueExpression exp = factory.createValueExpression(
elManager.getELContext(),
bracket(expression), Object.class);
elManager.setVariable(var, exp);
} | Assign an EL expression to an EL variable. The expression is parsed,
but not evaluated, and the parsed expression is mapped to the EL
variable in the local variable map.
Any previously assigned expression to the same variable will be replaced.
If the expression is <code>null</code>, the variable will be removed.
@param var The name of the variable.
@param expression The EL expression to be assigned to the variable. |
public void defineFunction(String prefix, String function,
String className,
String method)
throws ClassNotFoundException, NoSuchMethodException {
if (prefix == null || function == null || className == null
|| method == null) {
throw new NullPointerException("Null argument for defineFunction");
}
Method meth = null;
ClassLoader loader = getClass().getClassLoader();
Class<?> klass = Class.forName(className, false, loader);
int j = method.indexOf('(');
if (j < 0) {
// Just a name is given
for (Method m: klass.getDeclaredMethods()) {
if (m.getName().equals(method)) {
meth = m;
}
}
if (meth == null) {
throw new NoSuchMethodException();
}
} else {
// method is the signature
// First get the method name, ignore the return type
int p = method.indexOf(' ');
if (p < 0) {
throw new NoSuchMethodException(
"Bad method singnature: " + method);
}
String methodName = method.substring(p+1, j).trim();
// Extract parameter types
p = method.indexOf(')', j+1);
if (p < 0) {
throw new NoSuchMethodException(
"Bad method singnature: " + method);
}
String[] params = method.substring(j+1, p).split(",");
Class<?>[] paramTypes = new Class<?>[params.length];
for (int i = 0; i < params.length; i++) {
paramTypes[i] = toClass(params[i], loader);
}
meth = klass.getDeclaredMethod(methodName, paramTypes);
}
if (! Modifier.isStatic(meth.getModifiers())) {
throw new NoSuchMethodException("The method specified in defineFunction must be static: " + meth);
}
if (function.equals("")) {
function = method;
}
elManager.mapFunction(prefix, function, meth);
} | Define an EL function in the local function mapper.
@param prefix The namespace for the function or "" for no namesapce.
@param function The name of the function.
If empty (""), the method name is used as the function name.
@param className The full Java class name that implements the function.
@param method The name (specified without parenthesis) or the signature
(as in the Java Language Spec) of the static method that implements
the function. If the name (e.g. "sum") is given, the first declared
method in class that matches the name is selected. If the signature
(e.g. "int sum(int, int)" ) is given, then the declared method
with the signature is selected.
@throws NullPointerException if any of the arguments is null.
@throws ClassNotFoundException if the specified class does not exists.
@throws NoSuchMethodException if the method (with or without the
signature) is not a declared method of the class, or if the method
signature is not valid, or if the method is not a static method. |
public void defineFunction(String prefix, String function, Method method)
throws NoSuchMethodException {
if (prefix == null || function == null || method == null) {
throw new NullPointerException("Null argument for defineFunction");
}
if (! Modifier.isStatic(method.getModifiers())) {
throw new NoSuchMethodException("The method specified in defineFunction must be static: " + method);
}
if (function.equals("")) {
function = method.getName();
}
elManager.mapFunction(prefix, function, method);
} | Define an EL function in the local function mapper.
@param prefix The namespace for the function or "" for no namesapce.
@param function The name of the function.
If empty (""), the method name is used as the function name.
@param method The <code>java.lang.reflect.Method</code> instance of
the method that implements the function.
@throws NullPointerException if any of the arguments is null.
@throws NoSuchMethodException if the method is not a static method |
public String getText(String indentation, char indentationChar) {
newCode = FormatterHelper.indent(
newNode.getPrettySource(indentationChar, indentationLevel, indentationSize, acceptedComments),
indentation, indentationChar, indentationLevel, indentationSize, requiresExtraIndentationOnFirstLine());
return newCode;
} | Returns the new text to insert with the appropriate indentation and comments
@param indentation
the existing indentation at the file. It never should be null and it is needed for
files that mix tabs and spaces in the same line.
@param indentationChar
the used indentation char (' ', or '\t')
@return the new text that replaces the existing one |
public void setPropertyResolved(Object base, Object property) {
setPropertyResolved(true); // Don't set the variable here, for 2.2 users
// ELContext may be overridden or delegated.
notifyPropertyResolved(base, property);
} | Called to indicate that a <code>ELResolver</code> has successfully
resolved a given (base, property) pair and to notify the
{@link EvaluationListener}s.
<p>The {@link CompositeELResolver} checks this property to determine
whether it should consider or skip other component resolvers.</p>
@see CompositeELResolver
@param base The base object
@param property The property object
@since EL 3.0 |
public void putContext(Class key, Object contextObject) {
if((key == null) || (contextObject == null)) {
throw new NullPointerException();
}
map.put(key, contextObject);
} | Associates a context object with this <code>ELContext</code>.
<p>The <code>ELContext</code> maintains a collection of context objects
relevant to the evaluation of an expression. These context objects
are used by <code>ELResolver</code>s. This method is used to
add a context object to that collection.</p>
<p>By convention, the <code>contextObject</code> will be of the
type specified by the <code>key</code>. However, this is not
required and the key is used strictly as a unique identifier.</p>
@param key The key used by an @{link ELResolver} to identify this
context object.
@param contextObject The context object to add to the collection.
@throws NullPointerException if key is null or contextObject is null. |
public Object getContext(Class key) {
if(key == null) {
throw new NullPointerException();
}
return map.get(key);
} | Returns the context object associated with the given key.
<p>The <code>ELContext</code> maintains a collection of context objects
relevant to the evaluation of an expression. These context objects
are used by <code>ELResolver</code>s. This method is used to
retrieve the context with the given key from the collection.</p>
<p>By convention, the object returned will be of the type specified by
the <code>key</code>. However, this is not required and the key is
used strictly as a unique identifier.</p>
@param key The unique identifier that was used to associate the
context object with this <code>ELContext</code>.
@return The context object associated with the given key, or null
if no such context was found.
@throws NullPointerException if key is null. |
public void addEvaluationListener(EvaluationListener listener) {
if (listeners == null) {
listeners = new ArrayList<EvaluationListener>();
}
listeners.add(listener);
} | Registers an evaluation listener to the ELContext.
@param listener The listener to be added.
@since EL 3.0 |
public void notifyBeforeEvaluation(String expr) {
if (getEvaluationListeners() == null)
return;
for (EvaluationListener listener: getEvaluationListeners()) {
listener.beforeEvaluation(this, expr);
}
} | Notifies the listeners before an EL expression is evaluated
@param expr The EL expression string to be evaluated |
public void notifyAfterEvaluation(String expr) {
if (getEvaluationListeners() == null)
return;
for (EvaluationListener listener: getEvaluationListeners()) {
listener.afterEvaluation(this, expr);
}
} | Notifies the listeners after an EL expression is evaluated
@param expr The EL expression string that has been evaluated |
public void notifyPropertyResolved(Object base, Object property) {
if (getEvaluationListeners() == null)
return;
for (EvaluationListener listener: getEvaluationListeners()) {
listener.propertyResolved(this, base, property);
}
} | Notifies the listeners when the (base, property) pair is resolved
@param base The base object
@param property The property Object |
public boolean isLambdaArgument(String arg) {
if (lambdaArgs == null) {
return false;
}
for (int i = lambdaArgs.size() - 1; i >= 0; i--) {
Map<String, Object> lmap = lambdaArgs.elementAt(i);
if (lmap.containsKey(arg)) {
return true;
}
}
return false;
} | Inquires if the name is a LambdaArgument
@param arg A possible Lambda formal parameter name
@return true if arg is a LambdaArgument, false otherwise. |
public Object getLambdaArgument(String arg) {
if (lambdaArgs == null) {
return null;
}
for (int i = lambdaArgs.size() - 1; i >= 0; i--) {
Map<String, Object> lmap = lambdaArgs.elementAt(i);
Object v = lmap.get(arg);
if (v != null) {
return v;
}
}
return null;
} | Retrieves the Lambda argument associated with a formal parameter.
If the Lambda expression is nested within other Lambda expressions, the
arguments for the current Lambda expression is first searched, and if
not found, the arguments for the immediate nesting Lambda expression
then searched, and so on.
@param arg The formal parameter for the Lambda argument
@return The object associated with formal parameter. Null if
no object has been associated with the parameter.
@since EL 3.0 |
public void enterLambdaScope(Map<String,Object> args) {
if (lambdaArgs == null) {
lambdaArgs = new Stack<Map<String,Object>>();
}
lambdaArgs.push(args);
} | Installs a Lambda argument map, in preparation for the evaluation
of a Lambda expression. The arguments in the map will be in scope
during the evaluation of the Lambda expression.
@param args The Lambda arguments map
@since EL 3.0 |
public Object convertToType(Object obj,
Class<?> targetType) {
boolean propertyResolvedSave = isPropertyResolved();
try {
setPropertyResolved(false);
ELResolver elResolver = getELResolver();
if (elResolver != null) {
Object res = elResolver.convertToType(this, obj, targetType);
if (isPropertyResolved()) {
return res;
}
}
} catch (ELException ex) {
throw ex;
} catch (Exception ex) {
throw new ELException(ex);
} finally {
setPropertyResolved(propertyResolvedSave);
}
return ELUtil.getExpressionFactory().coerceToType(obj, targetType);
} | Converts an object to a specific type. If a custom converter in the
<code>ELResolver</code> handles this conversion, it is used. Otherwise
the standard coercions is applied.
<p>An <code>ELException</code> is thrown if an error occurs during
the conversion.</p>
@param obj The object to convert.
@param targetType The target type for the conversion.
@throws ELException thrown if errors occur.
@since EL 3.0 |
public void setPackage(PackageDeclaration pakage) {
if (this.pakage != null) {
updateReferences(this.pakage);
}
this.pakage = pakage;
setAsParentNodeOf(pakage);
} | Sets or clear the package declarations of this compilation unit.
@param pakage
the pakage declaration to set or <code>null</code> to default package |
@Override
public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) {
// get set of candidate IDs for removal and addition (possibly fixed IDs are discarded)
Set<Integer> removeCandidates = getRemoveCandidates(solution);
Set<Integer> addCandidates = getAddCandidates(solution);
// check if swap is possible
if(removeCandidates.isEmpty() || addCandidates.isEmpty()){
// impossible to perform a swap
return null;
}
// select random ID to remove from selection
int del = SetUtilities.getRandomElement(removeCandidates, rnd);
// select random ID to add to selection
int add = SetUtilities.getRandomElement(addCandidates, rnd);
// create and return swap move
return new SwapMove(add, del);
} | Generates a random swap move for the given subset solution that removes a single ID from the set of currently selected IDs,
and replaces it with a random ID taken from the set of currently unselected IDs. Possible fixed IDs are not considered to be
swapped. If no swap move can be generated, <code>null</code> is returned.
@param solution solution for which a random swap move is generated
@param rnd source of randomness used to generate random move
@return random swap move, <code>null</code> if no swap move can be generated |
@Override
public List<SubsetMove> getAllMoves(SubsetSolution solution) {
// get set of candidate IDs for removal and addition (possibly fixed IDs are discarded)
Set<Integer> removeCandidates = getRemoveCandidates(solution);
Set<Integer> addCandidates = getAddCandidates(solution);
// first check if swaps are possible, for efficiency (avoids superfluous loop iterations)
if(removeCandidates.isEmpty() || addCandidates.isEmpty()){
// no swap moves can be applied, return empty set
return Collections.emptyList();
}
// create swap move for all combinations of add and remove candidates
return addCandidates.stream()
.flatMap(add -> removeCandidates.stream().map(remove -> new SwapMove(add, remove)))
.collect(Collectors.toList());
} | Generates a list of all possible swap moves that transform the given subset solution by removing a single ID from
the current selection and replacing it with a new ID which is currently not selected. Possible fixed IDs are not
considered to be swapped. May return an empty list if no swap moves can be generated.
@param solution solution for which all possible swap moves are generated
@return list of all swap moves, may be empty |
public void setName(NameExpr name) {
if (this.name != null) {
updateReferences(this.name);
}
this.name = name;
setAsParentNodeOf(name);
} | Sets the name of this package declaration.
@param name
the name to set |
@Override
public void setNeighbourhood(Neighbourhood<? super SolutionType> neighbourhood){
// synchronize with status updates
synchronized(getStatusLock()){
// call super
super.setNeighbourhood(neighbourhood);
// set neighbourhood in every replica
replicas.forEach(r -> r.setNeighbourhood(neighbourhood));
}
} | Set the same neighbourhood for each replica. Note that <code>neighbourhood</code> can not
be <code>null</code> and that this method may only be called when the search is idle.
@param neighbourhood neighbourhood to be set for each replica
@throws NullPointerException if <code>neighbourhood</code> is <code>null</code>
@throws SearchException if the search is not idle |
@Override
public void setCurrentSolution(SolutionType solution){
// synchronize with status updates
synchronized(getStatusLock()){
// call super (also verifies status)
super.setCurrentSolution(solution);
// pass current solution to every replica (copy!)
replicas.forEach(r -> r.setCurrentSolution(Solution.checkedCopy(solution)));
}
} | Set a custom current solution, of which a copy is set as the current solution in each replica.
Note that <code>solution</code> can not be <code>null</code> and that this method may only be
called when the search is idle.
@param solution current solution to be set for each replica
@throws NullPointerException if <code>solution</code> is <code>null</code>
@throws SearchException if the search is not idle |
@Override
protected void searchStep() {
// submit replicas for execution in thread pool
// (future returns index of respective replica)
for(int i=0; i < replicas.size(); i++){
futures.add(pool.submit(replicas.get(i), i));
}
// logger.debug("{}: started {} Metropolis replicas", this, futures.size());
// wait for completion of all replicas and remove corresponding future
while(!futures.isEmpty()){
// remove next future from queue and wait until it has completed
try{
int i = futures.poll().get();
// logger.debug("{}: {}/{} replicas finished", this, replicas.size()-futures.size(), replicas.size());
// update total number of accepted/rejected moves
incNumAcceptedMoves(replicas.get(i).getNumAcceptedMoves());
incNumRejectedMoves(replicas.get(i).getNumRejectedMoves());
} catch (InterruptedException | ExecutionException ex){
throw new SearchException("An error occured during concurrent execution of Metropolis replicas "
+ "in the parallel tempering algorithm.", ex);
}
}
// consider swapping solutions of adjacent replicas
for(int i=swapBase; i<replicas.size()-1; i+=2){
MetropolisSearch<SolutionType> r1 = replicas.get(i);
MetropolisSearch<SolutionType> r2 = replicas.get(i+1);
// compute delta
double delta = computeDelta(r2.getCurrentSolutionEvaluation(), r1.getCurrentSolutionEvaluation());
// check if solutions should be swapped
boolean swap = false;
if(delta >= 0){
// always swap
swap = true;
} else {
// compute factor based on difference in temperature
double b1 = 1.0 / (r1.getTemperature());
double b2 = 1.0 / (r2.getTemperature());
double diffb = b1 - b2;
// randomized swap (with probability p)
double p = Math.exp(diffb * delta);
// generate random number
double r = getRandom().nextDouble();
// swap with probability p
if(r < p){
swap = true;
}
}
// swap solutions
if(swap){
SolutionType r1Sol = r1.getCurrentSolution();
Evaluation r1Eval = r1.getCurrentSolutionEvaluation();
Validation r1Val = r1.getCurrentSolutionValidation();
r1.setCurrentSolution(
r2.getCurrentSolution(),
r2.getCurrentSolutionEvaluation(),
r2.getCurrentSolutionValidation()
);
r2.setCurrentSolution(r1Sol, r1Eval, r1Val);
}
}
// flip swap base
swapBase = 1 - swapBase;
} | In each search step, every replica performs several steps after which solutions of adjacent
replicas may be swapped.
@throws SearchException if an error occurs during concurrent execution of the Metropolis replicas
@throws JamesRuntimeException if depending on malfunctioning components (problem,
neighbourhood, replicas, ...) |
@Override
protected void searchDisposed(){
// dispose replicas
replicas.forEach(r -> r.dispose());
// shut down thread pool
pool.shutdown();
// dispose super
super.searchDisposed();
} | When disposing a parallel tempering search, it will dispose each contained Metropolis replica and will
shut down the thread pool used for concurrent execution of replicas. |
public int getIfdCount() {
int c = 0;
if (metadata != null && metadata.contains("IFD"))
c = getMetadataList("IFD").size();
return c;
} | Gets the ifd count.
@return the ifd count |
public int getIfdImagesCount() {
int c = 0;
if (metadata.contains("IFD")) {
List<TiffObject> l = getMetadataList("IFD");
int n = 0;
for (TiffObject to : l) {
if (to instanceof IFD) {
IFD ifd = (IFD) to;
if (ifd.isImage())
n++;
}
}
c = n;
}
return c;
} | Gets the images count (main images and thumbnails).
@return the ifd count |
public int getMainImagesCount() {
int count = 0;
List<TiffObject> list = new ArrayList<>();
list.addAll(getMetadataList("IFD"));
list.addAll(getMetadataList("SubIFDs"));
for (TiffObject to : list) {
if (to instanceof IFD) {
IFD ifd = (IFD) to;
if (ifd.isImage() && !ifd.isThumbnail())
count++;
}
}
return count;
} | Gets the main images count.
@return the ifd count |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.