defaultSupplier;
State() {
}
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/ContextPermission.java 0000664 0000000 0000000 00000030754 13615110664 0031735 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.context;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.function.Supplier;
import org.wildfly.common.Assert;
import org.wildfly.common._private.CommonMessages;
import org.wildfly.common.annotation.NotNull;
/**
* A permission object for operations on {@link ContextManager} instances.
*
* This type of permission requires a {@code name} and an {@code action}. The {@code name} may be the name
* of a context manager, or the special {@code *} name which means the permission applies to all context managers.
*
* The {@code action} may be one or more of the following (each action name being separated by a comma):
*
* - {@code get} - allow {@linkplain ContextManager#get() getting} the current context
* - {@code getPrivilegedSupplier} - allow access to the {@link ContextManager#getPrivilegedSupplier()} method
* - {@code getGlobalDefault} - allow access to the {@linkplain ContextManager#getGlobalDefault() global default context}
* - {@code setGlobalDefault} - allow {@linkplain ContextManager#setGlobalDefault(Contextual) setting the global default instance}
* - {@code setGlobalDefaultSupplier} - allow {@linkplain ContextManager#setGlobalDefaultSupplier(Supplier) setting the global default instance supplier}
* - {@code getThreadDefault} - allow access to the {@linkplain ContextManager#getThreadDefault() per-thread default context}
* - {@code setThreadDefault} - allow {@linkplain ContextManager#setThreadDefault(Contextual) setting the per-thread default instance}
* - {@code setThreadDefaultSupplier} - allow {@linkplain ContextManager#setThreadDefaultSupplier(Supplier) setting the per-thread default instance supplier}
*
* Additionally, the special {@code *} action name is allowed which implies all of the above actions.
*
* The {@link #newPermissionCollection()} method returns an optimized container for context permissions.
*
* @author David M. Lloyd
*/
public final class ContextPermission extends Permission {
private static final long serialVersionUID = 2149744699461086708L;
private static final int ACTION_GET = 0b00000000001;
private static final int ACTION_GET_PRIV_SUP = 0b00000000010;
private static final int ACTION_GET_GLOBAL_DEF = 0b00000000100;
private static final int ACTION_SET_GLOBAL_DEF = 0b00000001000;
private static final int ACTION_SET_GLOBAL_DEF_SUP = 0b00000010000;
private static final int ACTION_GET_THREAD_DEF = 0b00000100000;
private static final int ACTION_SET_THREAD_DEF = 0b00001000000;
private static final int ACTION_SET_THREAD_DEF_SUP = 0b00010000000;
private static final int ACTION_GET_CLASSLOADER_DEF = 0b00100000000;
private static final int ACTION_SET_CLASSLOADER_DEF = 0b01000000000;
private static final int ACTION_SET_CLASSLOADER_DEF_SUP = 0b10000000000;
private static final int ACTION_ALL = 0b11111111111;
static final String STR_GET = "get";
static final String STR_GET_PRIV_SUP = "getPrivilegedSupplier";
static final String STR_GET_GLOBAL_DEF = "getGlobalDefault";
static final String STR_SET_GLOBAL_DEF = "setGlobalDefault";
static final String STR_SET_GLOBAL_DEF_SUP = "setGlobalDefaultSupplier";
static final String STR_GET_THREAD_DEF = "getThreadDefault";
static final String STR_SET_THREAD_DEF = "setThreadDefault";
static final String STR_SET_THREAD_DEF_SUP = "setThreadDefaultSupplier";
static final String STR_GET_CLASSLOADER_DEF = "getClassLoaderDefault";
static final String STR_SET_CLASSLOADER_DEF = "setClassLoaderDefault";
static final String STR_SET_CLASSLOADER_DEF_SUP = "setClassLoaderDefaultSupplier";
private final transient int actionBits;
private transient String actionString;
/**
* Constructs a permission with the specified name.
*
* @param name name of the Permission object being created (must not be {@code null})
* @param actions the actions string (must not be {@code null})
*/
public ContextPermission(final String name, final String actions) {
super(name);
Assert.checkNotNullParam("name", name);
Assert.checkNotNullParam("actions", actions);
actionBits = parseActions(actions);
}
ContextPermission(final String name, final int actionBits) {
super(name);
Assert.checkNotNullParam("name", name);
this.actionBits = actionBits & ACTION_ALL;
}
private static int parseActions(final String actions) throws IllegalArgumentException {
int bits = 0;
int start = 0;
int idx = actions.indexOf(',');
if (idx == -1) {
return parseAction(actions);
} else do {
bits |= parseAction(actions.substring(start, idx));
start = idx + 1;
idx = actions.indexOf(',', start);
} while (idx != -1);
bits |= parseAction(actions.substring(start));
return bits;
}
private static int parseAction(final String action) {
switch (action.trim()) {
case STR_GET: return ACTION_GET;
case STR_GET_PRIV_SUP: return ACTION_GET_PRIV_SUP;
case STR_GET_GLOBAL_DEF: return ACTION_GET_GLOBAL_DEF;
case STR_SET_GLOBAL_DEF: return ACTION_SET_GLOBAL_DEF;
case STR_SET_GLOBAL_DEF_SUP: return ACTION_SET_GLOBAL_DEF_SUP;
case STR_GET_THREAD_DEF: return ACTION_GET_THREAD_DEF;
case STR_SET_THREAD_DEF: return ACTION_SET_THREAD_DEF;
case STR_SET_THREAD_DEF_SUP: return ACTION_SET_THREAD_DEF_SUP;
case STR_GET_CLASSLOADER_DEF: return ACTION_GET_CLASSLOADER_DEF;
case STR_SET_CLASSLOADER_DEF: return ACTION_SET_CLASSLOADER_DEF;
case STR_SET_CLASSLOADER_DEF_SUP: return ACTION_SET_CLASSLOADER_DEF_SUP;
case "*": return ACTION_ALL;
case "": return 0;
default: {
throw CommonMessages.msg.invalidPermissionAction(action);
}
}
}
/**
* Determine if the given permission is implied by this permission.
*
* @param permission the other permission
* @return {@code true} if the other permission is not {@code null} and is a context permission which is implied by
* this permission instance; {@code false} otherwise
*/
public boolean implies(final Permission permission) {
return permission instanceof ContextPermission && implies((ContextPermission) permission);
}
/**
* Determine if the given permission is implied by this permission.
*
* @param permission the other permission
* @return {@code true} if the other permission is not {@code null} and is a context permission which is implied by
* this permission instance; {@code false} otherwise
*/
public boolean implies(final ContextPermission permission) {
return this == permission || permission != null && isSet(this.actionBits, permission.actionBits) && impliesName(permission.getName());
}
private boolean impliesName(String otherName) {
final String myName = getName();
return myName.equals("*") || myName.equals(otherName);
}
static boolean isSet(int mask, int test) {
return (mask & test) == test;
}
/**
* Determine if this permission is equal to the given object.
*
* @param obj the other object
* @return {@code true} if the object is a context permission that is exactly equal to this one; {@code false} otherwise
*/
public boolean equals(final Object obj) {
return obj instanceof ContextPermission && equals((ContextPermission) obj);
}
/**
* Determine if this permission is equal to the given permission.
*
* @param permission the other permission
* @return {@code true} if the permission is a context permission that is exactly equal to this one; {@code false} otherwise
*/
public boolean equals(final ContextPermission permission) {
return this == permission || permission != null && actionBits == permission.actionBits && getName().equals(permission.getName());
}
/**
* Get the hash code of this permission.
*
* @return the hash code of this permission
*/
public int hashCode() {
return getName().hashCode() * 17 + actionBits;
}
/**
* Get the actions string. This string will be returned in a canonical format.
*
* @return the actions string
*/
public String getActions() {
String actionString = this.actionString;
if (actionString == null) {
final int actionBits = this.actionBits;
if (isSet(actionBits, ACTION_ALL)) {
return this.actionString = "*";
} else if (actionBits == 0) {
return this.actionString = "";
}
final StringBuilder b = new StringBuilder();
if (isSet(actionBits, ACTION_GET)) b.append(STR_GET).append(',');
if (isSet(actionBits, ACTION_GET_PRIV_SUP)) b.append(STR_GET_PRIV_SUP).append(',');
if (isSet(actionBits, ACTION_GET_GLOBAL_DEF)) b.append(STR_GET_GLOBAL_DEF).append(',');
if (isSet(actionBits, ACTION_SET_GLOBAL_DEF)) b.append(STR_SET_GLOBAL_DEF).append(',');
if (isSet(actionBits, ACTION_SET_GLOBAL_DEF_SUP)) b.append(STR_SET_GLOBAL_DEF_SUP).append(',');
if (isSet(actionBits, ACTION_GET_THREAD_DEF)) b.append(STR_GET_THREAD_DEF).append(',');
if (isSet(actionBits, ACTION_SET_THREAD_DEF)) b.append(STR_SET_THREAD_DEF).append(',');
if (isSet(actionBits, ACTION_SET_THREAD_DEF_SUP)) b.append(STR_SET_THREAD_DEF_SUP).append(',');
if (isSet(actionBits, ACTION_GET_CLASSLOADER_DEF)) b.append(STR_GET_CLASSLOADER_DEF).append(',');
if (isSet(actionBits, ACTION_SET_CLASSLOADER_DEF)) b.append(STR_SET_CLASSLOADER_DEF).append(',');
if (isSet(actionBits, ACTION_SET_CLASSLOADER_DEF_SUP)) b.append(STR_SET_CLASSLOADER_DEF_SUP).append(',');
assert b.length() > 0;
b.setLength(b.length() - 1);
return this.actionString = b.toString();
}
return actionString;
}
/**
* Create a copy of this permission with the additional given actions.
*
* @param actions the additional actions (must not be {@code null})
* @return the new permission (not {@code null})
*/
@NotNull
public ContextPermission withActions(String actions) {
return withActionBits(parseActions(actions));
}
ContextPermission withActionBits(int actionBits) {
if (isSet(this.actionBits, actionBits)) {
return this;
} else {
return new ContextPermission(getName(), this.actionBits | actionBits);
}
}
/**
* Create a copy of this permission without any of the given actions.
*
* @param actions the actions to subtract (must not be {@code null})
* @return the new permission (not {@code null})
*/
@NotNull
public ContextPermission withoutActions(String actions) {
return withoutActionBits(parseActions(actions));
}
ContextPermission withoutActionBits(final int actionBits) {
if ((actionBits & this.actionBits) == 0) {
return this;
} else {
return new ContextPermission(getName(), this.actionBits & ~actionBits);
}
}
/**
* Get a new permission collection instance which can hold this type of permissions.
*
* @return a new permission collection instance (not {@code null})
*/
public PermissionCollection newPermissionCollection() {
return new ContextPermissionCollection();
}
int getActionBits() {
return actionBits;
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/ContextPermissionCollection.java0000664 0000000 0000000 00000023305 13615110664 0033743 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.context;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.wildfly.common.Assert;
import org.wildfly.common._private.CommonMessages;
/**
* @author David M. Lloyd
*/
final class ContextPermissionCollection extends PermissionCollection {
private static final long serialVersionUID = - 3651721703337368351L;
private volatile State state = emptyState;
private static final AtomicReferenceFieldUpdater stateUpdater = AtomicReferenceFieldUpdater.newUpdater(ContextPermissionCollection.class, State.class, "state");
public void add(final Permission permission) throws SecurityException, IllegalArgumentException {
Assert.checkNotNullParam("permission", permission);
if (permission instanceof ContextPermission) {
add((ContextPermission) permission);
} else {
throw CommonMessages.msg.invalidPermissionType(ContextPermission.class, permission.getClass());
}
}
public void add(final ContextPermission contextPermission) throws SecurityException {
Assert.checkNotNullParam("contextPermission", contextPermission);
if (isReadOnly()) {
throw CommonMessages.msg.readOnlyPermissionCollection();
}
final int actionBits = contextPermission.getActionBits();
if (actionBits == 0) {
// no operation
return;
}
final String name = contextPermission.getName();
State oldState, newState;
do {
oldState = this.state;
final ContextPermission oldGlobalPermission = oldState.globalPermission;
final int globalActions = oldGlobalPermission == null ? 0 : oldGlobalPermission.getActionBits();
if (oldGlobalPermission != null && oldGlobalPermission.implies(contextPermission)) {
// already fully implied by global permission
return;
} else {
final Map oldPermissions = oldState.permissions;
final Map newPermissions;
final ContextPermission newGlobalPermission;
if (name.equals("*")) {
// it's global but with some bits we don't have; calculate the new global actions and subtract from the map
if (oldGlobalPermission == null) {
newGlobalPermission = contextPermission;
} else {
newGlobalPermission = oldGlobalPermission.withActionBits(contextPermission.getActionBits());
}
// now subtract
newPermissions = cloneWithout(oldPermissions, newGlobalPermission);
} else {
newGlobalPermission = oldGlobalPermission;
// it's not global; check & add actions to our map permission
final ContextPermission mapPermission = oldPermissions.get(name);
if (mapPermission == null) {
// no map entry; just create one (but without any global actions we have defined)
if (oldPermissions.isEmpty()) {
// change empty map to singleton map
newPermissions = Collections.singletonMap(name, contextPermission.withoutActionBits(globalActions));
} else {
// make a copy of the map plus the new entry
newPermissions = new HashMap<>(oldPermissions);
newPermissions.put(name, contextPermission.withoutActionBits(globalActions));
}
} else if (((mapPermission.getActionBits() | globalActions) & actionBits) == actionBits) {
// already fully implied by a map entry
return;
} else {
// replace the map entry
if (oldPermissions.size() == 1) {
// it was a singleton map, just replace it
newPermissions = Collections.singletonMap(name, mapPermission.withActionBits(actionBits & ~globalActions));
} else {
// copy the map and replace the entry
newPermissions = new HashMap<>(oldPermissions);
newPermissions.put(name, mapPermission.withActionBits(actionBits & ~globalActions));
}
}
}
newState = new State(newGlobalPermission, newPermissions);
}
} while (! stateUpdater.compareAndSet(this, oldState, newState));
}
private static Map cloneWithout(final Map oldPermissions, final ContextPermission newGlobalPermission) {
final Iterator iterator = oldPermissions.values().iterator();
ContextPermission first;
for (;;) {
if (! iterator.hasNext()) {
return Collections.emptyMap();
}
first = iterator.next();
if (! newGlobalPermission.implies(first)) {
// break into next phase
break;
}
}
final int globalActionBits = newGlobalPermission.getActionBits();
ContextPermission second;
for (;;) {
if (! iterator.hasNext()) {
return Collections.singletonMap(first.getName(), first.withoutActionBits(globalActionBits));
}
second = iterator.next();
if (! newGlobalPermission.implies(second)) {
// break into next phase
break;
}
}
HashMap newMap = new HashMap<>();
newMap.put(first.getName(), first.withoutActionBits(globalActionBits));
newMap.put(second.getName(), second.withoutActionBits(globalActionBits));
ContextPermission subsequent;
while (iterator.hasNext()) {
subsequent = iterator.next();
if (! newGlobalPermission.implies(subsequent)) {
newMap.put(subsequent.getName(), subsequent.withoutActionBits(globalActionBits));
}
}
return newMap;
}
public boolean implies(final Permission permission) {
return permission instanceof ContextPermission && implies((ContextPermission) permission);
}
public boolean implies(final ContextPermission permission) {
if (permission == null) return false;
final State state = this.state;
final ContextPermission globalPermission = state.globalPermission;
final int globalBits;
if (globalPermission != null) {
if (globalPermission.implies(permission)) {
return true;
}
globalBits = globalPermission.getActionBits();
} else {
globalBits = 0;
}
final int bits = permission.getActionBits();
final String name = permission.getName();
if (name.equals("*")) {
return false;
}
final ContextPermission ourPermission = state.permissions.get(name);
if (ourPermission == null) {
return false;
}
final int ourBits = ourPermission.getActionBits() | globalBits;
return (bits & ourBits) == bits;
}
public Enumeration elements() {
final State state = this.state;
final Iterator iterator = state.permissions.values().iterator();
return new Enumeration() {
Permission next = state.globalPermission;
public boolean hasMoreElements() {
if (next != null) {
return true;
}
if (iterator.hasNext()) {
next = iterator.next();
return true;
}
return false;
}
public Permission nextElement() {
if (! hasMoreElements()) throw new NoSuchElementException();
try {
return next;
} finally {
next = null;
}
}
};
}
static class State {
private final ContextPermission globalPermission;
private final Map permissions;
State(final ContextPermission globalPermission, final Map permissions) {
this.globalPermission = globalPermission;
this.permissions = permissions;
}
}
private static final State emptyState = new State(null, Collections.emptyMap());
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/Contextual.java 0000664 0000000 0000000 00000040766 13615110664 0030372 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.context;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.Callable;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.LongFunction;
import java.util.function.Predicate;
import org.wildfly.common.Assert;
import org.wildfly.common._private.CommonMessages;
import org.wildfly.common.annotation.NotNull;
import org.wildfly.common.function.ExceptionBiConsumer;
import org.wildfly.common.function.ExceptionBiFunction;
import org.wildfly.common.function.ExceptionBiPredicate;
import org.wildfly.common.function.ExceptionConsumer;
import org.wildfly.common.function.ExceptionFunction;
import org.wildfly.common.function.ExceptionIntFunction;
import org.wildfly.common.function.ExceptionLongFunction;
import org.wildfly.common.function.ExceptionPredicate;
/**
* A base class for contexts which are activated in a thread-local context.
*
* @param the public type of the contextual object
*
* @author David M. Lloyd
*/
public interface Contextual> {
/**
* Get the context manager for this object. The implementation of this method normally should return a constant
* instance.
*
* @return the context manager (must not be {@code null})
*/
@NotNull
ContextManager getInstanceContextManager();
/**
* Run the given task with this contextual object selected.
*
* @param runnable the task to run (must not be {@code null})
*/
default void run(Runnable runnable) {
Assert.checkNotNullParam("runnable", runnable);
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
runnable.run();
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param action the task to run (must not be {@code null})
* @param the return value type
* @return the action return value
*/
default R runAction(PrivilegedAction action) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return action.run();
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param action the task to run (must not be {@code null})
* @param the return value type
* @return the action return value
* @throws PrivilegedActionException if the action fails with an exception
*/
default R runExceptionAction(PrivilegedExceptionAction action) throws PrivilegedActionException {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return action.run();
} catch (Exception e) {
throw CommonMessages.msg.privilegedActionFailed(e);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param callable the task to run (must not be {@code null})
* @param the return value type
* @return the action return value
*/
default V runCallable(Callable callable) throws Exception {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return callable.call();
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param consumer the task to run (must not be {@code null})
* @param param1 the first parameter to pass to the task
* @param param2 the second parameter to pass to the task
* @param the first parameter type
* @param the second parameter type
*/
default void runBiConsumer(BiConsumer consumer, T param1, U param2) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
consumer.accept(param1, param2);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param consumer the task to run (must not be {@code null})
* @param param1 the first parameter to pass to the task
* @param param2 the second parameter to pass to the task
* @param the first parameter type
* @param the second parameter type
* @param the exception type
* @throws E if an exception occurs in the task
*/
default void runExBiConsumer(ExceptionBiConsumer consumer, T param1, U param2) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
consumer.accept(param1, param2);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param consumer the task to run (must not be {@code null})
* @param param the parameter to pass to the task
* @param the parameter type
*/
default void runConsumer(Consumer consumer, T param) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
consumer.accept(param);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param consumer the task to run (must not be {@code null})
* @param param the parameter to pass to the task
* @param the parameter type
* @param the exception type
* @throws E if an exception occurs in the task
*/
default void runExConsumer(ExceptionConsumer consumer, T param) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
consumer.accept(param);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param param1 the first parameter to pass to the task
* @param param2 the second parameter to pass to the task
* @param the first parameter type
* @param the second parameter type
* @param the return value type
* @return the action return value
*/
default R runBiFunction(BiFunction function, T param1, U param2) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(param1, param2);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param param1 the first parameter to pass to the task
* @param param2 the second parameter to pass to the task
* @param the first parameter type
* @param the second parameter type
* @param the return value type
* @param the exception type
* @return the action return value
* @throws E if an exception occurs in the task
*/
default R runExBiFunction(ExceptionBiFunction function, T param1, U param2) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(param1, param2);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param param the parameter to pass to the task
* @param the parameter type
* @param the return value type
* @return the action return value
*/
default R runFunction(Function function, T param) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(param);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param param the parameter to pass to the task
* @param the parameter type
* @param the return value type
* @param the exception type
* @return the action return value
* @throws E if an exception occurs in the task
*/
default R runExFunction(ExceptionFunction function, T param) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(param);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param predicate the task to run (must not be {@code null})
* @param param1 the first parameter to pass to the task
* @param param2 the second parameter to pass to the task
* @param the first parameter type
* @param the second parameter type
* @return the action return value
*/
default boolean runBiPredicate(BiPredicate predicate, T param1, U param2) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return predicate.test(param1, param2);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param predicate the task to run (must not be {@code null})
* @param param1 the first parameter to pass to the task
* @param param2 the second parameter to pass to the task
* @param the first parameter type
* @param the second parameter type
* @param the exception type
* @return the action return value
* @throws E if an exception occurs in the task
*/
default boolean runExBiPredicate(ExceptionBiPredicate predicate, T param1, U param2) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return predicate.test(param1, param2);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param predicate the task to run (must not be {@code null})
* @param param the parameter to pass to the task
* @param the first parameter type
* @return the action return value
*/
default boolean runPredicate(Predicate predicate, T param) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return predicate.test(param);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param predicate the task to run (must not be {@code null})
* @param param the parameter to pass to the task
* @param the first parameter type
* @param the exception type
* @return the action return value
* @throws E if an exception occurs in the task
*/
default boolean runExPredicate(ExceptionPredicate predicate, T param) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return predicate.test(param);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param value the parameter to pass to the task
* @param the return value type
* @return the action return value
*/
default T runIntFunction(IntFunction function, int value) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(value);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param value the parameter to pass to the task
* @param the return value type
* @param the exception type
* @return the action return value
* @throws E if an exception occurs in the task
*/
default T runExIntFunction(ExceptionIntFunction function, int value) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(value);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param value the parameter to pass to the task
* @param the return value type
* @return the action return value
*/
default T runLongFunction(LongFunction function, long value) {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(value);
} finally {
contextManager.restoreCurrent(old);
}
}
/**
* Run the given task with this contextual object selected.
*
* @param function the task to run (must not be {@code null})
* @param value the parameter to pass to the task
* @param the return value type
* @param the exception type
* @return the action return value
* @throws E if an exception occurs in the task
*/
default T runExLongFunction(ExceptionLongFunction function, long value) throws E {
final ContextManager contextManager = getInstanceContextManager();
final C old = contextManager.getAndSetCurrent(this);
try {
return function.apply(value);
} finally {
contextManager.restoreCurrent(old);
}
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/context/package-info.java 0000664 0000000 0000000 00000001763 13615110664 0030562 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Types related to management of contextual objects. Such objects may implement {@link org.wildfly.common.context.Contextual Contextual}
* to gain thread-contextual functionality.
*
* @author David M. Lloyd
*/
package org.wildfly.common.context;
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/ 0000775 0000000 0000000 00000000000 13615110664 0024467 5 ustar 00root root 0000000 0000000 wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/CacheInfo.java 0000664 0000000 0000000 00000026733 13615110664 0027164 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.cpu;
import static java.security.AccessController.doPrivileged;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Locale;
/**
* A class which exposes any available cache line information for the current CPU.
*
* @author David M. Lloyd
*/
public final class CacheInfo {
private static final CacheLevelInfo[] cacheLevels;
/**
* Get the number of CPU cache level entries. If no cache information could be gathered, 0 is returned.
*
* @return the number of CPU cache levels, or 0 if unknown
*/
public static int getLevelEntryCount() {
return cacheLevels.length;
}
/**
* Get the CPU cache level information for a cache level. The {@code index} argument must be greater than zero and
* less than the number of levels returned by {@link #getLevelEntryCount()}.
*
* @param index the cache level index
* @return the CPU cache level information
*/
public static CacheLevelInfo getCacheLevelInfo(int index) {
return cacheLevels[index];
}
/**
* Get the smallest known data cache line size. If no cache line sizes are known, 0 is returned. Note that smaller
* cache lines may exist if one or more cache line sizes are unknown.
*
* @return the smallest cache line size, or 0 if unknown
*/
public static int getSmallestDataCacheLineSize() {
int minSize = Integer.MAX_VALUE;
for (CacheLevelInfo cacheLevel : cacheLevels) {
if (cacheLevel.getCacheType().isData()) {
final int cacheLineSize = cacheLevel.getCacheLineSize();
if (cacheLineSize != 0 && cacheLineSize < minSize) {
minSize = cacheLineSize;
}
}
}
return minSize == Integer.MAX_VALUE ? 0 : minSize;
}
/**
* Get the smallest known instruction cache line size. If no cache line sizes are known, 0 is returned. Note that smaller
* cache lines may exist if one or more cache line sizes are unknown.
*
* @return the smallest cache line size, or 0 if unknown
*/
public static int getSmallestInstructionCacheLineSize() {
int minSize = Integer.MAX_VALUE;
for (CacheLevelInfo cacheLevel : cacheLevels) {
if (cacheLevel.getCacheType().isInstruction()) {
final int cacheLineSize = cacheLevel.getCacheLineSize();
if (cacheLineSize != 0 && cacheLineSize < minSize) {
minSize = cacheLineSize;
}
}
}
return minSize == Integer.MAX_VALUE ? 0 : minSize;
}
static {
cacheLevels = doPrivileged((PrivilegedAction) () -> {
try {
String osArch = System.getProperty("os.name", "unknown").toLowerCase(Locale.US);
if (osArch.contains("linux")) {
// try to read /sys fs
final File cpu0 = new File("/sys/devices/system/cpu/cpu0/cache");
if (cpu0.exists()) {
// great!
final File[] files = cpu0.listFiles();
if (files != null) {
ArrayList indexes = new ArrayList();
for (File file : files) {
if (file.getName().startsWith("index")) {
indexes.add(file);
}
}
final CacheLevelInfo[] levelInfoArray = new CacheLevelInfo[indexes.size()];
for (int i = 0; i < indexes.size(); i++) {
File file = indexes.get(i);
int index = parseIntFile(new File(file, "level"));
final CacheType type;
switch (parseStringFile(new File(file, "type"))) {
case "Data": type = CacheType.DATA; break;
case "Instruction": type = CacheType.INSTRUCTION; break;
case "Unified": type = CacheType.UNIFIED; break;
default: type = CacheType.UNKNOWN; break;
}
int size = parseIntKBFile(new File(file, "size"));
int lineSize = parseIntFile(new File(file, "coherency_line_size"));
levelInfoArray[i] = new CacheLevelInfo(index, type, size, lineSize);
}
return levelInfoArray;
}
}
} else if (osArch.contains("mac os x")) {
// cache line size
final int lineSize = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.cachelinesize"));
if (lineSize != 0) {
// cache sizes
final int l1d = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l1dcachesize"));
final int l1i = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l1icachesize"));
final int l2 = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l2cachesize"));
final int l3 = safeParseInt(parseProcessOutput("/usr/sbin/sysctl", "-n", "hw.l3cachesize"));
ArrayList list = new ArrayList();
if (l1d != 0) {
list.add(new CacheLevelInfo(1, CacheType.DATA, l1d / 1024, lineSize));
}
if (l1i != 0) {
list.add(new CacheLevelInfo(1, CacheType.INSTRUCTION, l1i / 1024, lineSize));
}
if (l2 != 0) {
list.add(new CacheLevelInfo(2, CacheType.UNIFIED, l2 / 1024, lineSize));
}
if (l3 != 0) {
list.add(new CacheLevelInfo(3, CacheType.UNIFIED, l3 / 1024, lineSize));
}
if (list.size() > 0) {
return list.toArray(new CacheLevelInfo[list.size()]);
}
}
} else if (osArch.contains("windows")) {
// TODO: use the wmic utility to get cache line info
}
} catch (Throwable ignored) {}
// all has failed
return new CacheLevelInfo[0];
});
}
static int parseIntFile(final File file) {
return safeParseInt(parseStringFile(file));
}
static int safeParseInt(final String string) {
try {
return Integer.parseInt(string);
} catch (Throwable ignored) {
return 0;
}
}
static int parseIntKBFile(final File file) {
try {
final String s = parseStringFile(file);
if (s.endsWith("K")) {
return Integer.parseInt(s.substring(0, s.length() - 1));
} else if (s.endsWith("M")) {
return Integer.parseInt(s.substring(0, s.length() - 1)) * 1024;
} else if (s.endsWith("G")) {
return Integer.parseInt(s.substring(0, s.length() - 1)) * 1024 * 1024;
} else {
return Integer.parseInt(s);
}
} catch (Throwable ignored) {
return 0;
}
}
static String parseStringFile(final File file) {
try (FileInputStream is = new FileInputStream(file)) {
return parseStringStream(is);
} catch (Throwable ignored) {
return "";
}
}
static String parseStringStream(final InputStream is) {
try (Reader r = new InputStreamReader(is, StandardCharsets.UTF_8)) {
StringBuilder b = new StringBuilder();
char[] cb = new char[64];
int res;
while ((res = r.read(cb)) != -1) {
b.append(cb, 0, res);
}
return b.toString().trim();
} catch (Throwable ignored) {
return "";
}
}
static String parseProcessOutput(final String... args) {
final ProcessBuilder processBuilder = new ProcessBuilder(args);
try {
final Process process = processBuilder.start();
process.getOutputStream().close();
final InputStream errorStream = process.getErrorStream();
final Thread errorThread = new Thread(null, new StreamConsumer(errorStream), "Process thread", 32768L);
errorThread.start();
final String result;
try (final InputStream inputStream = process.getInputStream()) {
result = parseStringStream(inputStream);
}
boolean intr = false;
try {
process.waitFor();
} catch (InterruptedException e) {
intr = true;
return null;
} finally {
try {
errorThread.join();
} catch (InterruptedException e) {
intr = true;
} finally {
if (intr) {
Thread.currentThread().interrupt();
}
}
}
return result;
} catch (IOException e) {
return "";
}
}
static class StreamConsumer implements Runnable {
private final InputStream stream;
StreamConsumer(final InputStream stream) {
this.stream = stream;
}
public void run() {
byte[] buffer = new byte[128];
try {
while (stream.read(buffer) != -1) ;
} catch (IOException ignored) {
} finally {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
}
public static void main(String[] args) {
System.out.println("Detected cache info:");
for (CacheLevelInfo levelInfo : cacheLevels) {
System.out.printf("Level %d cache: type %s, size %d KiB, cache line is %d bytes%n",
Integer.valueOf(levelInfo.getCacheLevel()),
levelInfo.getCacheType(),
Integer.valueOf(levelInfo.getCacheLevelSizeKB()),
Integer.valueOf(levelInfo.getCacheLineSize())
);
}
}
} wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/CacheLevelInfo.java 0000664 0000000 0000000 00000004443 13615110664 0030146 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.cpu;
/**
* @author David M. Lloyd
*/
public final class CacheLevelInfo {
private final int cacheLevel;
private final CacheType cacheType;
private final int cacheLevelSizeKB;
private final int cacheLineSize;
CacheLevelInfo(final int cacheLevel, final CacheType cacheType, final int cacheLevelSizeKB, final int cacheLineSize) {
this.cacheLevel = cacheLevel;
this.cacheType = cacheType;
this.cacheLevelSizeKB = cacheLevelSizeKB;
this.cacheLineSize = cacheLineSize;
}
/**
* Get the level index. For example, the level of L1 cache will be "1", L2 will be "2", etc. If the level is
* not known, 0 is returned.
*
* @return the level index, or 0 if unknown
*/
public int getCacheLevel() {
return cacheLevel;
}
/**
* Get the type of cache. If the type is unknown, {@link CacheType#UNKNOWN} is returned.
*
* @return the type of cache (not {@code null})
*/
public CacheType getCacheType() {
return cacheType;
}
/**
* Get the size of this cache level in kilobytes. If the size is unknown, 0 is returned.
*
* @return the size of this cache level in kilobytes, or 0 if unknown
*/
public int getCacheLevelSizeKB() {
return cacheLevelSizeKB;
}
/**
* Get the cache line size in bytes. If the size is unknown, 0 is returned.
*
* @return the cache line size in bytes, or 0 if unknown
*/
public int getCacheLineSize() {
return cacheLineSize;
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/CacheType.java 0000664 0000000 0000000 00000007546 13615110664 0027213 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.cpu;
import java.util.EnumSet;
/**
* The type of cache.
*
* @author David M. Lloyd
*/
public enum CacheType {
/**
* Unknown cache type.
*/
UNKNOWN(false, false),
/**
* Data cache.
*/
DATA(false, true),
/**
* Instruction cache.
*/
INSTRUCTION(true, false),
/**
* Unified instruction/data cache.
*/
UNIFIED(true, true),
;
private static final int fullSize = values().length;
private final boolean instruction;
private final boolean data;
CacheType(final boolean instruction, final boolean data) {
this.instruction = instruction;
this.data = data;
}
/**
* Determine if this cache line type holds instructions.
*
* @return {@code true} if the cache line holds instructions, {@code false} if it does not or it cannot be determined
*/
public boolean isInstruction() {
return instruction;
}
/**
* Determine if this cache line type holds data.
*
* @return {@code true} if the cache line holds data, {@code false} if it does not or it cannot be determined
*/
public boolean isData() {
return data;
}
/**
* Determine whether the given set is fully populated (or "full"), meaning it contains all possible values.
*
* @param set the set
*
* @return {@code true} if the set is full, {@code false} otherwise
*/
public static boolean isFull(final EnumSet set) {
return set != null && set.size() == fullSize;
}
/**
* Determine whether this instance is equal to one of the given instances.
*
* @param v1 the first instance
*
* @return {@code true} if one of the instances matches this one, {@code false} otherwise
*/
public boolean in(final CacheType v1) {
return this == v1;
}
/**
* Determine whether this instance is equal to one of the given instances.
*
* @param v1 the first instance
* @param v2 the second instance
*
* @return {@code true} if one of the instances matches this one, {@code false} otherwise
*/
public boolean in(final CacheType v1, final CacheType v2) {
return this == v1 || this == v2;
}
/**
* Determine whether this instance is equal to one of the given instances.
*
* @param v1 the first instance
* @param v2 the second instance
* @param v3 the third instance
*
* @return {@code true} if one of the instances matches this one, {@code false} otherwise
*/
public boolean in(final CacheType v1, final CacheType v2, final CacheType v3) {
return this == v1 || this == v2 || this == v3;
}
/**
* Determine whether this instance is equal to one of the given instances.
*
* @param values the possible values
*
* @return {@code true} if one of the instances matches this one, {@code false} otherwise
*/
public boolean in(final CacheType... values) {
if (values != null) for (CacheType value : values) {
if (this == value) return true;
}
return false;
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/ProcessorInfo.java 0000664 0000000 0000000 00000010170 13615110664 0030124 0 ustar 00root root 0000000 0000000 package org.wildfly.common.cpu;
/*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Locale;
/**
* Provides general information about the processors on this host.
*
* @author Jason T. Greene
*/
public class ProcessorInfo {
private ProcessorInfo() {
}
private static final String CPUS_ALLOWED = "Cpus_allowed:";
private static final byte[] BITS = new byte[]{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
private static final Charset ASCII = Charset.forName("US-ASCII");
/**
* Returns the number of processors available to this process. On most operating systems this method
* simply delegates to {@link Runtime#availableProcessors()}. However, on Linux, this strategy
* is insufficient, since the JVM does not take into consideration the process' CPU set affinity
* which is employed by cgroups and numactl. Therefore this method will analyze the Linux proc filesystem
* to make the determination. Since the CPU affinity of a process can be change at any time, this method does
* not cache the result. Calls should be limited accordingly.
*
* Note tha on Linux, both SMT units (Hyper-Threading) and CPU cores are counted as a processor.
*
* @return the available processors on this system.
*/
public static int availableProcessors() {
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged((PrivilegedAction) () -> Integer.valueOf(determineProcessors())).intValue();
}
return determineProcessors();
}
private static int determineProcessors() {
int javaProcs = Runtime.getRuntime().availableProcessors();
if (!isLinux()) {
return javaProcs;
}
int maskProcs = 0;
try {
maskProcs = readCPUMask();
} catch (Exception e) {
// yum
}
return maskProcs > 0 ? Math.min(javaProcs, maskProcs) : javaProcs;
}
private static int readCPUMask() throws IOException {
final FileInputStream stream = new FileInputStream("/proc/self/status");
final InputStreamReader inputReader = new InputStreamReader(stream, ASCII);
try (BufferedReader reader = new BufferedReader(inputReader)) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(CPUS_ALLOWED)) {
int count = 0;
int start = CPUS_ALLOWED.length();
for (int i = start; i < line.length(); i++) {
char ch = line.charAt(i);
if (ch >= '0' && ch <= '9') {
count += BITS[ch - '0'];
} else if (ch >= 'a' && ch <= 'f') {
count += BITS[ch - 'a' + 10];
} else if (ch >= 'A' && ch <= 'F') {
count += BITS[ch - 'A' + 10];
}
}
return count;
}
}
}
return -1;
}
private static boolean isLinux() {
String osArch = System.getProperty("os.name", "unknown").toLowerCase(Locale.US);
return (osArch.contains("linux"));
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/cpu/package-info.java 0000664 0000000 0000000 00000001635 13615110664 0027663 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2015 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A set of utility classes to determine information about the runtime environment's CPU configuration.
*
* @author David M. Lloyd
*/
package org.wildfly.common.cpu;
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/ 0000775 0000000 0000000 00000000000 13615110664 0026077 5 ustar 00root root 0000000 0000000 wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/CompositeNode.java 0000664 0000000 0000000 00000003506 13615110664 0031516 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.expression;
import java.util.HashSet;
import java.util.List;
import org.wildfly.common.function.ExceptionBiConsumer;
/**
* @author David M. Lloyd
*/
final class CompositeNode extends Node {
private final Node[] subNodes;
CompositeNode(final Node[] subNodes) {
this.subNodes = subNodes;
}
CompositeNode(final List subNodes) {
this.subNodes = subNodes.toArray(NO_NODES);
}
void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E {
for (Node subNode : subNodes) {
subNode.emit(context, resolveFunction);
}
}
void catalog(final HashSet strings) {
for (Node node : subNodes) {
node.catalog(strings);
}
}
public String toString() {
StringBuilder b = new StringBuilder();
b.append('*');
for (Node subNode : subNodes) {
b.append('<').append(subNode.toString()).append('>');
}
return b.toString();
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/Expression.java 0000664 0000000 0000000 00000077465 13615110664 0031124 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.expression;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import org.wildfly.common.Assert;
import org.wildfly.common._private.CommonMessages;
import org.wildfly.common.function.ExceptionBiConsumer;
/**
* A compiled property-expansion expression string. An expression string is a mix of plain strings and expression
* segments, which are wrapped by the sequence "{@code ${ ... }}".
*
* @author David M. Lloyd
*/
public final class Expression {
private final Node content;
private final Set referencedStrings;
Expression(Node content) {
this.content = content;
HashSet strings = new HashSet<>();
content.catalog(strings);
referencedStrings = strings.isEmpty() ? Collections.emptySet() : strings.size() == 1 ? Collections.singleton(strings.iterator().next()) : Collections.unmodifiableSet(strings);
}
/**
* Get the immutable set of string keys that are referenced by expressions in this compiled expression. If there
* are no expansions in this expression, the set is empty. Note that this will not include any string keys
* that themselves contain expressions, in the case that {@link Flag#NO_RECURSE_KEY} was not specified.
*
* @return the immutable set of strings (not {@code null})
*/
public Set getReferencedStrings() {
return referencedStrings;
}
/**
* Evaluate the expression with the given expansion function, which may throw a checked exception. The given "function"
* is a predicate which returns {@code true} if the expansion succeeded or {@code false} if it failed (in which case
* a default value may be used). If expansion succeeds, the expansion function should append the result to the
* given {@link StringBuilder}.
*
* @param expandFunction the expansion function to apply (must not be {@code null})
* @param the exception type thrown by the expansion function
* @return the expanded string
* @throws E if the expansion function throws an exception
*/
public String evaluateException(final ExceptionBiConsumer, StringBuilder, E> expandFunction) throws E {
Assert.checkNotNullParam("expandFunction", expandFunction);
final StringBuilder b = new StringBuilder();
content.emit(new ResolveContext(expandFunction, b), expandFunction);
return b.toString();
}
/**
* Evaluate the expression with the given expansion function. The given "function"
* is a predicate which returns {@code true} if the expansion succeeded or {@code false} if it failed (in which case
* a default value may be used). If expansion succeeds, the expansion function should append the result to the
* given {@link StringBuilder}.
*
* @param expandFunction the expansion function to apply (must not be {@code null})
* @return the expanded string
*/
public String evaluate(BiConsumer, StringBuilder> expandFunction) {
return evaluateException(expandFunction::accept);
}
/**
* Evaluate the expression using a default expansion function that evaluates system and environment properties
* in the JBoss style (i.e. using the prefix {@code "env."} to designate an environment property).
* The caller must have all required security manager permissions.
*
* @param failOnNoDefault {@code true} to throw an {@link IllegalArgumentException} if an unresolvable key has no
* default value; {@code false} to expand such keys to an empty string
* @return the expanded string
*/
public String evaluateWithPropertiesAndEnvironment(boolean failOnNoDefault) {
return evaluate((c, b) -> {
final String key = c.getKey();
if (key.startsWith("env.")) {
final String env = key.substring(4);
final String val = System.getenv(env);
if (val == null) {
if (failOnNoDefault && ! c.hasDefault()) {
throw CommonMessages.msg.unresolvedEnvironmentProperty(env);
}
c.expandDefault();
} else {
b.append(val);
}
} else {
final String val = System.getProperty(key);
if (val == null) {
if (failOnNoDefault && ! c.hasDefault()) {
throw CommonMessages.msg.unresolvedSystemProperty(key);
}
c.expandDefault();
} else {
b.append(val);
}
}
});
}
/**
* Evaluate the expression using a default expansion function that evaluates system properties.
* The caller must have all required security manager permissions.
*
* @param failOnNoDefault {@code true} to throw an {@link IllegalArgumentException} if an unresolvable key has no
* default value; {@code false} to expand such keys to an empty string
* @return the expanded string
*/
public String evaluateWithProperties(boolean failOnNoDefault) {
return evaluate((c, b) -> {
final String key = c.getKey();
final String val = System.getProperty(key);
if (val == null) {
if (failOnNoDefault && ! c.hasDefault()) {
throw CommonMessages.msg.unresolvedSystemProperty(key);
}
c.expandDefault();
} else {
b.append(val);
}
});
}
/**
* Evaluate the expression using a default expansion function that evaluates environment properties.
* The caller must have all required security manager permissions.
*
* @param failOnNoDefault {@code true} to throw an {@link IllegalArgumentException} if an unresolvable key has no
* default value; {@code false} to expand such keys to an empty string
* @return the expanded string
*/
public String evaluateWithEnvironment(boolean failOnNoDefault) {
return evaluate((c, b) -> {
final String key = c.getKey();
final String val = System.getenv(key);
if (val == null) {
if (failOnNoDefault && ! c.hasDefault()) {
throw CommonMessages.msg.unresolvedEnvironmentProperty(key);
}
c.expandDefault();
} else {
b.append(val);
}
});
}
/**
* Compile an expression string.
*
* @param string the expression string (must not be {@code null})
* @param flags optional flags to apply which affect the compilation
* @return the compiled expression (not {@code null})
*/
public static Expression compile(String string, Flag... flags) {
return compile(string, flags == null || flags.length == 0 ? NO_FLAGS : EnumSet.of(flags[0], flags));
}
/**
* Compile an expression string.
*
* @param string the expression string (must not be {@code null})
* @param flags optional flags to apply which affect the compilation (must not be {@code null})
* @return the compiled expression (not {@code null})
*/
public static Expression compile(String string, EnumSet flags) {
Assert.checkNotNullParam("string", string);
Assert.checkNotNullParam("flags", flags);
final Node content;
final Itr itr;
if (flags.contains(Flag.NO_TRIM)) {
itr = new Itr(string);
} else {
itr = new Itr(string.trim());
}
content = parseString(itr, true, false, false, flags);
return content == Node.NULL ? EMPTY : new Expression(content);
}
private static final Expression EMPTY = new Expression(Node.NULL);
static final class Itr {
private final String str;
private int idx;
Itr(final String str) {
this.str = str;
}
boolean hasNext() {
return idx < str.length();
}
int next() {
final int idx = this.idx;
try {
return str.codePointAt(idx);
} finally {
this.idx = str.offsetByCodePoints(idx, 1);
}
}
int prev() {
final int idx = this.idx;
try {
return str.codePointBefore(idx);
} finally {
this.idx = str.offsetByCodePoints(idx, -1);
}
}
int getNextIdx() {
return idx;
}
int getPrevIdx() {
return str.offsetByCodePoints(idx, -1);
}
String getStr() {
return str;
}
int peekNext() {
return str.codePointAt(idx);
}
int peekPrev() {
return str.codePointBefore(idx);
}
void rewind(final int newNext) {
idx = newNext;
}
}
private static Node parseString(Itr itr, final boolean allowExpr, final boolean endOnBrace, final boolean endOnColon, final EnumSet flags) {
int ignoreBraceLevel = 0;
final List list = new ArrayList<>();
int start = itr.getNextIdx();
while (itr.hasNext()) {
// index of this character
int idx = itr.getNextIdx();
int ch = itr.next();
switch (ch) {
case '$': {
if (! allowExpr) {
// TP 1
// treat as plain content
continue;
}
// check to see if it's a dangling $
if (! itr.hasNext()) {
if (! flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 2
throw invalidExpressionSyntax(itr.getStr(), idx);
}
// TP 3
list.add(new LiteralNode(itr.getStr(), start, itr.getNextIdx()));
start = itr.getNextIdx();
continue;
}
// enqueue what we have acquired so far
if (idx > start) {
// TP 4
list.add(new LiteralNode(itr.getStr(), start, idx));
}
// next char should be an expression starter of some sort
idx = itr.getNextIdx();
ch = itr.next();
switch (ch) {
case '{': {
// ${
boolean general = flags.contains(Flag.GENERAL_EXPANSION) && itr.hasNext() && itr.peekNext() == '{';
// consume double-{
if (general) itr.next();
// set start to the beginning of the key for later
start = itr.getNextIdx();
// the expression name starts in the next position
Node keyNode = parseString(itr, ! flags.contains(Flag.NO_RECURSE_KEY), true, true, flags);
if (! itr.hasNext()) {
if (! flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 5
throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx());
}
// TP 6
// otherwise treat it as a properly terminated expression
list.add(new ExpressionNode(general, keyNode, Node.NULL));
start = itr.getNextIdx();
continue;
} else if (itr.peekNext() == ':') {
if (flags.contains(Flag.DOUBLE_COLON) && itr.hasNext() && itr.peekNext() == ':') {
// TP 7
// OK actually the whole thing is really going to be part of the key
// Best approach is, rewind and do it over again, but without end-on-colon
itr.rewind(start);
keyNode = parseString(itr, ! flags.contains(Flag.NO_RECURSE_KEY), true, false, flags);
list.add(new ExpressionNode(general, keyNode, Node.NULL));
} else {
// TP 8
itr.next(); // consume it
final Node defaultValueNode = parseString(itr, ! flags.contains(Flag.NO_RECURSE_DEFAULT), true, false, flags);
list.add(new ExpressionNode(general, keyNode, defaultValueNode));
}
// now expect }
if (! itr.hasNext()) {
if (! flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 9
throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx());
}
// TP 10
// otherwise treat it as a properly terminated expression
start = itr.getNextIdx();
continue;
} else {
// TP 11
assert itr.peekNext() == '}';
itr.next(); // consume
if (general) {
if (! itr.hasNext()) {
if (! flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 11_1
throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx());
}
// TP 11_2
// otherwise treat it as a properly terminated expression
start = itr.getNextIdx();
continue;
} else {
if (itr.peekNext() == '}') {
itr.next(); // consume it
// TP 11_3
start = itr.getNextIdx();
continue;
} else {
if (! flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 11_4
throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx());
}
// otherwise treat it as a properly terminated expression
start = itr.getNextIdx();
continue;
}
}
} else {
start = itr.getNextIdx();
continue;
}
//throw Assert.unreachableCode();
}
} else {
// TP 12
assert itr.peekNext() == '}';
itr.next(); // consume
list.add(new ExpressionNode(general, keyNode, Node.NULL));
if (general) {
if (! itr.hasNext()) {
if (! flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 12_1
throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx());
}
// TP 12_2
// otherwise treat it as a properly terminated expression
start = itr.getNextIdx();
continue;
} else {
if (itr.peekNext() == '}') {
itr.next(); // consume it
// TP 12_3
start = itr.getNextIdx();
continue;
} else {
if (! flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 12_4
throw invalidExpressionSyntax(itr.getStr(), itr.getNextIdx());
}
// otherwise treat it as a properly terminated expression
start = itr.getNextIdx();
continue;
}
}
}
start = itr.getNextIdx();
continue;
}
//throw Assert.unreachableCode();
}
case '$': {
// $$
if (flags.contains(Flag.MINI_EXPRS)) {
// TP 13
list.add(new ExpressionNode(false, LiteralNode.DOLLAR, Node.NULL));
} else {
// just resolve $$ to $
// TP 14
list.add(LiteralNode.DOLLAR);
}
start = itr.getNextIdx();
continue;
}
case '}': {
// $}
if (flags.contains(Flag.MINI_EXPRS)) {
// TP 15
list.add(new ExpressionNode(false, LiteralNode.CLOSE_BRACE, Node.NULL));
start = itr.getNextIdx();
continue;
} else if (endOnBrace) {
if (flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 16
// just treat the $ that we got like plain text, and return
list.add(LiteralNode.DOLLAR);
itr.prev(); // back up to point at } again
return Node.fromList(list);
} else {
// TP 17
throw invalidExpressionSyntax(itr.getStr(), idx);
}
} else {
if (flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 18
// just treat $} like plain text
list.add(LiteralNode.DOLLAR);
list.add(LiteralNode.CLOSE_BRACE);
start = itr.getNextIdx();
continue;
} else {
// TP 19
throw invalidExpressionSyntax(itr.getStr(), idx);
}
}
//throw Assert.unreachableCode();
}
case ':': {
// $:
if (flags.contains(Flag.MINI_EXPRS)) {
// $: is an expression
// TP 20
list.add(new ExpressionNode(false, LiteralNode.COLON, Node.NULL));
start = itr.getNextIdx();
continue;
} else if (endOnColon) {
if (flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 21
// just treat the $ that we got like plain text, and return
itr.prev(); // back up to point at : again
list.add(LiteralNode.DOLLAR);
return Node.fromList(list);
} else {
// TP 22
throw invalidExpressionSyntax(itr.getStr(), idx);
}
} else {
if (flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 23
// just treat $: like plain text
list.add(LiteralNode.DOLLAR);
list.add(LiteralNode.COLON);
start = itr.getNextIdx();
continue;
} else {
// TP 24
throw invalidExpressionSyntax(itr.getStr(), idx);
}
}
//throw Assert.unreachableCode();
}
default: {
// $ followed by anything else
if (flags.contains(Flag.MINI_EXPRS)) {
// TP 25
list.add(new ExpressionNode(false, new LiteralNode(itr.getStr(), idx, itr.getNextIdx()), Node.NULL));
start = itr.getNextIdx();
continue;
} else if (flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 26
// just treat it as literal
start = itr.getPrevIdx() - 1; // we can use 1 here because unicode '$' is one char in size
continue;
} else {
// TP 27
throw invalidExpressionSyntax(itr.getStr(), idx);
}
//throw Assert.unreachableCode();
}
}
//throw Assert.unreachableCode();
}
case ':': {
if (endOnColon) {
// TP 28
itr.prev(); // back up to point at : again
if (idx > start) {
list.add(new LiteralNode(itr.getStr(), start, idx));
}
return Node.fromList(list);
} else {
// TP 29
// plain content always
continue;
}
//throw Assert.unreachableCode();
}
case '{': {
if (! flags.contains(Flag.NO_SMART_BRACES)) {
// TP 1.2
ignoreBraceLevel++;
}
// TP 1.3
continue;
}
case '}': {
if (! flags.contains(Flag.NO_SMART_BRACES) && ignoreBraceLevel > 0) {
// TP 1.1
ignoreBraceLevel--;
continue;
} else if (endOnBrace) {
// TP 30
itr.prev(); // back up to point at } again
// TP 46 // allow an empty default value
if (idx >= start) {
list.add(new LiteralNode(itr.getStr(), start, idx));
}
return Node.fromList(list);
} else {
// TP 31
// treat as plain content
continue;
}
//throw Assert.unreachableCode();
}
case '\\': {
if (flags.contains(Flag.ESCAPES)) {
if (idx > start) {
list.add(new LiteralNode(itr.getStr(), start, idx));
start = idx;
}
if (! itr.hasNext()) {
if (flags.contains(Flag.LENIENT_SYNTAX)) {
// just treat it like plain content
// TP 33
continue;
} else {
// TP 34
throw invalidExpressionSyntax(itr.getStr(), idx);
}
} else {
ch = itr.next();
final LiteralNode node;
switch (ch) {
case 'n': {
// TP 35
node = LiteralNode.NEWLINE;
break;
}
case 'r': {
// TP 36
node = LiteralNode.CARRIAGE_RETURN;
break;
}
case 't': {
// TP 37
node = LiteralNode.TAB;
break;
}
case 'b': {
// TP 38
node = LiteralNode.BACKSPACE;
break;
}
case 'f': {
// TP 39
node = LiteralNode.FORM_FEED;
break;
}
case '\\': {
// TP 45
node = LiteralNode.BACKSLASH;
break;
}
default: {
if (flags.contains(Flag.LENIENT_SYNTAX)) {
// TP 40
// just append the literal character after the \, whatever it was
start = itr.getPrevIdx();
continue;
}
// TP 41
throw invalidExpressionSyntax(itr.getStr(), idx);
}
}
list.add(node);
start = itr.getNextIdx();
continue;
}
}
// TP 42
// otherwise, just...
continue;
}
default: {
// TP 43
// treat as plain content
//noinspection UnnecessaryContinue
continue;
}
}
//throw Assert.unreachableCode();
}
final int length = itr.getStr().length();
if (length > start) {
// TP 44
list.add(new LiteralNode(itr.getStr(), start, length));
}
return Node.fromList(list);
}
private static IllegalArgumentException invalidExpressionSyntax(final String string, final int index) {
String msg = CommonMessages.msg.invalidExpressionSyntax(index);
StringBuilder b = new StringBuilder(msg.length() + string.length() + string.length() + 5);
b.append(msg);
b.append('\n').append('\t').append(string);
b.append('\n').append('\t');
for (int i = 0; i < index; i = string.offsetByCodePoints(i, 1)) {
final int cp = string.codePointAt(i);
if (Character.isWhitespace(cp)) {
b.append(cp);
} else if (Character.isValidCodePoint(cp) && ! Character.isISOControl(cp)) {
b.append(' ');
}
}
b.append('^');
return new IllegalArgumentException(b.toString());
}
private static final EnumSet NO_FLAGS = EnumSet.noneOf(Flag.class);
/**
* Flags that can apply to a property expression compilation
*/
public enum Flag {
/**
* Do not trim leading and trailing whitespace off of the expression string before parsing it.
*/
NO_TRIM,
/**
* Ignore syntax problems instead of throwing an exception.
*/
LENIENT_SYNTAX,
/**
* Support single-character expressions that can be interpreted without wrapping in curly braces.
*/
MINI_EXPRS,
/**
* Do not support recursive expression expansion in the key part of the expression.
*/
NO_RECURSE_KEY,
/**
* Do not support recursion in default values.
*/
NO_RECURSE_DEFAULT,
/**
* Do not support smart braces.
*/
NO_SMART_BRACES,
/**
* Support {@code Policy} file style "general" expansion alternate expression syntax. "Smart" braces
* will only work if the opening brace is not the first character in the expression key.
*/
GENERAL_EXPANSION,
/**
* Support standard escape sequences in plain text and default value fields, which begin with a backslash ("{@code \}") character.
*/
ESCAPES,
/**
* Treat expressions containing a double-colon delimiter as special, encoding the entire content into the key.
*/
DOUBLE_COLON,
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/ExpressionNode.java 0000664 0000000 0000000 00000004227 13615110664 0031714 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.expression;
import java.util.HashSet;
import org.wildfly.common.function.ExceptionBiConsumer;
/**
* @author David M. Lloyd
*/
class ExpressionNode extends Node {
private final boolean generalExpression;
private final Node key;
private final Node defaultValue;
ExpressionNode(final boolean generalExpression, final Node key, final Node defaultValue) {
this.generalExpression = generalExpression;
this.key = key;
this.defaultValue = defaultValue;
}
void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E {
ExpressionNode oldCurrent = context.setCurrent(this);
try {
resolveFunction.accept(context, context.getStringBuilder());
} finally {
context.setCurrent(oldCurrent);
}
}
void catalog(final HashSet strings) {
if (key instanceof LiteralNode) {
strings.add(key.toString());
} else {
key.catalog(strings);
}
defaultValue.catalog(strings);
}
boolean isGeneralExpression() {
return generalExpression;
}
Node getKey() {
return key;
}
Node getDefaultValue() {
return defaultValue;
}
public String toString() {
return String.format("Expr<%s:%s>", key, defaultValue);
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/LiteralNode.java 0000664 0000000 0000000 00000004673 13615110664 0031156 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.expression;
import java.io.File;
import java.util.HashSet;
import org.wildfly.common.function.ExceptionBiConsumer;
/**
* @author David M. Lloyd
*/
class LiteralNode extends Node {
static final LiteralNode DOLLAR = new LiteralNode("$");
static final LiteralNode CLOSE_BRACE = new LiteralNode("}");
static final LiteralNode FILE_SEP = new LiteralNode(File.separator);
static final LiteralNode COLON = new LiteralNode(":");
static final LiteralNode NEWLINE = new LiteralNode("\n");
static final LiteralNode CARRIAGE_RETURN = new LiteralNode("\r");
static final LiteralNode TAB = new LiteralNode("\t");
static final LiteralNode BACKSPACE = new LiteralNode("\b");
static final LiteralNode FORM_FEED = new LiteralNode("\f");
static final LiteralNode BACKSLASH = new LiteralNode("\\");
private final String literalValue;
private final int start;
private final int end;
private String toString;
LiteralNode(final String literalValue, final int start, final int end) {
this.literalValue = literalValue;
this.start = start;
this.end = end;
}
LiteralNode(final String literalValue) {
this(literalValue, 0, literalValue.length());
}
void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E {
context.getStringBuilder().append(literalValue, start, end);
}
void catalog(final HashSet strings) {
}
public String toString() {
final String toString = this.toString;
return toString != null ? toString : (this.toString = literalValue.substring(start, end));
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/Node.java 0000664 0000000 0000000 00000003535 13615110664 0027635 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.expression;
import java.util.HashSet;
import java.util.List;
import org.wildfly.common.function.ExceptionBiConsumer;
/**
* @author David M. Lloyd
*/
abstract class Node {
static final Node[] NO_NODES = new Node[0];
Node() {
}
static Node fromList(List list) {
if (list == null || list.isEmpty()) {
return NULL;
} else if (list.size() == 1) {
return list.get(0);
} else {
return new CompositeNode(list);
}
}
static final Node NULL = new Node() {
void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E {
}
void catalog(final HashSet strings) {
}
public String toString() {
return "<>";
}
};
abstract void emit(final ResolveContext context, final ExceptionBiConsumer, StringBuilder, E> resolveFunction) throws E;
abstract void catalog(final HashSet strings);
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/ResolveContext.java 0000664 0000000 0000000 00000012540 13615110664 0031730 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.expression;
import org.wildfly.common.function.ExceptionBiConsumer;
/**
* The expression resolve context, which can be used to query the current expression key, write out expansions or
* default values, or perform validation.
*
* The expression context is not thread-safe and is not valid outside of the property expansion function body.
*
* @param the exception type that can be thrown by the expansion function
*
* @author David M. Lloyd
*/
public final class ResolveContext {
private final ExceptionBiConsumer, StringBuilder, E> function;
private StringBuilder builder;
private ExpressionNode current;
ResolveContext(final ExceptionBiConsumer, StringBuilder, E> function, final StringBuilder builder) {
this.function = function;
this.builder = builder;
}
/**
* Get the expression resolution key, as a string. If the key contains an expression, it will have been expanded
* unless {@link Expression.Flag#NO_RECURSE_KEY} was given.
* The result is not cached and will be re-expanded every time this method is called.
*
* @return the expanded key (not {@code null})
* @throws E if the recursive expansion threw an exception
*/
public String getKey() throws E {
if (current == null) throw new IllegalStateException();
final Node key = current.getKey();
if (key instanceof LiteralNode) {
return key.toString();
} else if (key == Node.NULL) {
return "";
}
final StringBuilder b = new StringBuilder();
emitToBuilder(b, key);
return b.toString();
}
/**
* Expand the default value to the given string builder. If the default value contains an expression, it will
* have been expanded unless {@link Expression.Flag#NO_RECURSE_DEFAULT} was given.
* The result is not cached and will be re-expanded every time this method is called.
*
* @param target the string builder target
* @throws E if the recursive expansion threw an exception
*/
public void expandDefault(StringBuilder target) throws E {
if (current == null) throw new IllegalStateException();
emitToBuilder(target, current.getDefaultValue());
}
private void emitToBuilder(final StringBuilder target, final Node node) throws E {
if (node == Node.NULL) {
return;
} else if (node instanceof LiteralNode) {
target.append(node.toString());
return;
} else {
final StringBuilder old = builder;
try {
builder = target;
node.emit(this, function);
} finally {
builder = old;
}
}
}
/**
* Expand the default value to the current target string builder. If the default value contains an expression, it will
* have been expanded unless {@link Expression.Flag#NO_RECURSE_DEFAULT} was given.
* The result is not cached and will be re-expanded every time this method is called.
*
* @throws E if the recursive expansion threw an exception
*/
public void expandDefault() throws E {
expandDefault(builder);
}
/**
* Expand the default value to a string. If the default value contains an expression, it will
* have been expanded unless {@link Expression.Flag#NO_RECURSE_DEFAULT} was given.
* The result is not cached and will be re-expanded every time this method is called.
*
* @return the expanded string (not {@code null})
* @throws E if the recursive expansion threw an exception
*/
public String getExpandedDefault() throws E {
if (current == null) throw new IllegalStateException();
final Node defaultValue = current.getDefaultValue();
if (defaultValue instanceof LiteralNode) {
return defaultValue.toString();
} else if (defaultValue == Node.NULL) {
return "";
}
final StringBuilder b = new StringBuilder();
emitToBuilder(b, defaultValue);
return b.toString();
}
/**
* Determine if the current expression has a default value.
*
* @return {@code true} if there is a default value, {@code false} otherwise
*/
public boolean hasDefault() {
return current.getDefaultValue() != Node.NULL;
}
StringBuilder getStringBuilder() {
return builder;
}
ExpressionNode setCurrent(final ExpressionNode current) {
try {
return this.current;
} finally {
this.current = current;
}
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/expression/package-info.java 0000664 0000000 0000000 00000001561 13615110664 0031271 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Expression string parsing and expansion classes.
*
* @author David M. Lloyd
*/
package org.wildfly.common.expression;
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/flags/ 0000775 0000000 0000000 00000000000 13615110664 0024774 5 ustar 00root root 0000000 0000000 wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/flags/Flags.java 0000664 0000000 0000000 00000037642 13615110664 0026707 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2018 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.flags;
import static java.lang.Integer.bitCount;
import static java.lang.Integer.highestOneBit;
import static java.lang.Integer.lowestOneBit;
import static java.lang.Integer.numberOfTrailingZeros;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.function.Consumer;
import org.wildfly.common.Assert;
/**
* A base class for implementing value-like flags and flag sets, where flags and flag sets may be used without allocation
* overhead.
*
*/
public abstract class Flags, This extends Flags> extends AbstractSet implements SortedSet {
final int bits;
/**
* Construct a new instance. This constructor should only be called during initial array construction.
*
* @param bits the bits of this set
*/
protected Flags(final int bits) {
this.bits = bits;
}
/**
* Get the set value of the given bit combination. The bit combination may contain extraneous one-bits so
* any bits beyond the bit of the last flag should be masked off if an array is used for lookup.
*
* @param bits the bit combination (possibly with extra bits)
* @return the set instance
*/
protected abstract This value(int bits);
/**
* Return {@code this}.
*
* @return {@code this}
*/
protected abstract This this_();
/**
* Get the flag item with the given index.
*
* @param index the index
* @return the flag
*/
protected abstract E itemOf(int index);
/**
* Get the item (cast to the correct {@code enum} type), or {@code null} if it is not of the correct type.
*
* @param obj the object to cast
* @return the cast object, or {@code null}
*/
protected abstract E castItemOrNull(Object obj);
/**
* Cast the given object to this class, throwing an exception if the cast fails.
*
* @param obj the object to cast
* @return the cast object
*/
protected abstract This castThis(Object obj);
/**
* Get the size of the flag set.
*
* @return the flag set size
*/
public final int size() {
return bitCount(bits);
}
/**
* Get the first flag in the set.
*
* @return the first flag
*/
public final E first() {
final int bits = this.bits;
if (bits == 0) throw new NoSuchElementException();
return itemOf(numberOfTrailingZeros(lowestOneBit(bits)));
}
/**
* Get the last flag in the set.
*
* @return the last flag
*/
public final E last() {
final int bits = this.bits;
if (bits == 0) throw new NoSuchElementException();
return itemOf(numberOfTrailingZeros(highestOneBit(bits)));
}
/**
* Get the {@code null} comparator, indicating that this set is always sorted in natural order.
*
* @return {@code null}
*/
public final Comparator super E> comparator() {
return null;
}
/**
* Determine if this flag set is empty.
*
* @return {@code true} if the flag set is empty, {@code false} otherwise
*/
public boolean isEmpty() {
return bits == 0;
}
/**
* Get the subset of flags from this set, up to (but not including) the given element.
*
* @param toElement the "to" element (must not be {@code null})
* @return the subset
*/
public final This headSet(final E toElement) {
Assert.checkNotNullParam("toElement", toElement);
return value(bits & bitOf(toElement) - 1);
}
/**
* Get the subset of flags from this set, starting from the given element.
*
* @param fromElement the "from" element (must not be {@code null})
* @return the subset
*/
public final This tailSet(final E fromElement) {
Assert.checkNotNullParam("fromElement", fromElement);
return value(bits & ~(bitOf(fromElement) - 1));
}
/**
* Get the subset of flags, starting from {@code fromElement} up to (but not including) {@code toElement}.
*
* @param fromElement the "from" element (must not be {@code null})
* @param toElement the "to" element (must not be {@code null})
* @return the subset
*/
public final This subSet(final E fromElement, final E toElement) {
Assert.checkNotNullParam("fromElement", fromElement);
Assert.checkNotNullParam("toElement", toElement);
return value(bits & (bitOf(toElement) - 1) & ~(bitOf(fromElement) - 1));
}
/**
* Get an {@code Object} array containing all the flag values of this set.
*
* @return the {@code Object} array
*/
public final Object[] toArray() {
int b = bits;
final Object[] array = new Object[bitCount(b)];
int idx = 0;
while (bitCount(b) > 0) {
final int lob = lowestOneBit(b);
array[idx + 1] = itemOf(numberOfTrailingZeros(lob));
b ^= lob;
}
return array;
}
/**
* Get a typed array containing all the flag values of this set.
*
* @param array the array to populate or clone
* @param the element type
* @return the populated array
*/
@SuppressWarnings("unchecked")
public final T[] toArray(T[] array) {
int b = bits;
final int size = bitCount(b);
if (size > array.length) {
array = Arrays.copyOf(array, size);
}
int idx = 0;
while (bitCount(b) > 0) {
final int lob = lowestOneBit(b);
array[idx + 1] = (T) itemOf(numberOfTrailingZeros(lob));
b ^= lob;
}
return array;
}
/**
* Determine if this flag set contains the given flag.
*
* @param flag the flag
* @return {@code true} if the flag is contained by this set
*/
public final boolean contains(E flag) {
return flag != null && (bits & bitOf(flag)) != 0;
}
/**
* Determine if this flag set contains the given object.
*
* @param o the object
* @return {@code true} if the object is contained by this set
*/
public final boolean contains(final Object o) {
return contains(castItemOrNull(o));
}
/**
* Determine if this flag set contains all of the objects in the given collection.
*
* @param c the collection
* @return {@code true} if all of the collection's objects are contained by this set
*/
public final boolean containsAll(final Collection> c) {
if (c.getClass() == getClass()) {
return containsAll(castThis(c));
} else {
for (Object o : c) {
if (! contains(o)) return false;
}
return true;
}
}
/**
* Determine if this flag set contains all of the flags in the given flag set.
*
* @param other the flag set
* @return {@code true} if all of the given set's flags are contained by this set
*/
public final boolean containsAll(This other) {
final int otherBits = other.bits;
return (this.bits & otherBits) == otherBits;
}
/**
* Determine if this flag set contains all of the given flags.
*
* @param flag1 the first flag
* @param flag2 the second flag
* @return {@code true} if all of the given flags are contained by this set
*/
public final boolean containsAll(E flag1, E flag2) {
return contains(flag1) && contains(flag2);
}
/**
* Determine if this flag set contains all of the given flags.
*
* @param flag1 the first flag
* @param flag2 the second flag
* @param flag3 the third flag
* @return {@code true} if all of the given flags are contained by this set
*/
public final boolean containsAll(E flag1, E flag2, E flag3) {
return containsAll(flag1, flag2) && contains(flag3);
}
/**
* Determine if this flag set contains any of the flags in the given flag set.
*
* @param other the flag set
* @return {@code true} if all of the given set's flags are contained by this set
*/
public final boolean containsAny(This other) {
return other != null && (bits & other.bits) != 0;
}
/**
* Determine if this flag set contains any of the given flags.
*
* @param flag1 the first flag
* @param flag2 the second flag
* @return {@code true} if any of the given flags are contained by this set
*/
public final boolean containsAny(E flag1, E flag2) {
return contains(flag1) || contains(flag2);
}
/**
* Determine if this flag set contains any of the given flags.
*
* @param flag1 the first flag
* @param flag2 the second flag
* @param flag3 the third flag
* @return {@code true} if any of the given flags are contained by this set
*/
public final boolean containsAny(E flag1, E flag2, E flag3) {
return containsAny(flag1, flag2) || contains(flag3);
}
/**
* Get the complement of this set.
*
* @return the complement of this set
*/
public final This complement() {
return value(~bits);
}
/**
* Return a set which includes all of the flags in this set and the given additional flag.
*
* @param flag the additional flag
* @return the combined set
*/
public final This with(E flag) {
return flag == null ? this_() : value(bits | bitOf(flag));
}
/**
* Return a set which includes all of the flags in this set and the given additional flags.
*
* @param flag1 the first flag
* @param flag2 the second flag
* @return the combined set
*/
public final This with(E flag1, E flag2) {
return with(flag1).with(flag2);
}
/**
* Return a set which includes all of the flags in this set and the given additional flags.
*
* @param flag1 the first flag
* @param flag2 the second flag
* @param flag3 the third flag
* @return the combined set
*/
public final This with(E flag1, E flag2, E flag3) {
return with(flag1, flag2).with(flag3);
}
/**
* Return a set which includes all of the flags in this set and the given additional flags.
*
* @param flags the additional flags
* @return the combined set
*/
@SafeVarargs
public final This with(E... flags) {
if (flags == null) return this_();
int b = bits;
for (E flag : flags) {
if (flag != null) b |= bitOf(flag);
}
return value(b);
}
/**
* Return a set which includes all of the flags in this set and the given additional flags.
*
* @param other the additional flags
* @return the combined set
*/
public final This with(This other) {
return other == null ? this_() : value(bits | other.bits);
}
/**
* Return a set which includes all of the flags except for the given flag.
*
* @param flag the flag
* @return the reduced set
*/
public final This without(E flag) {
return flag == null ? this_() : value(bits & ~bitOf(flag));
}
/**
* Return a set which includes all of the flags except for the given flags.
*
* @param other the flags
* @return the reduced set
*/
public final This without(This other) {
return other == null ? this_() : value(bits & ~other.bits);
}
/**
* Determine if this flag set is equal to the given object.
*
* @param o the other object
* @return {@code true} if the object is equal to this set, {@code false} otherwise
*/
public final boolean equals(final Object o) {
return o == this || o instanceof Set && equals((Set>) o);
}
/**
* Determine if this flag set is equal to the given set.
*
* @param o the other set
* @return {@code true} if the set is equal to this set, {@code false} otherwise
*/
public final boolean equals(final Set> o) {
return o == this || o.containsAll(this) && containsAll(o);
}
/**
* Determine if this flag set is equal to the given flag set.
*
* @param o the other flag set
* @return {@code true} if the flag set is equal to this set, {@code false} otherwise
*/
public final boolean equals(final This o) {
return o == this;
}
/**
* Get the hash code of this flag set.
*
* @return the flag set hash code
*/
public final int hashCode() {
int hc = 0;
int b = this.bits;
while (b != 0) {
int lob = lowestOneBit(b);
hc += itemOf(numberOfTrailingZeros(lob)).hashCode();
b ^= lob;
}
return hc;
}
/**
* Iterate this set in order from first to last flag.
*
* @return the iterator
*/
public final Iterator iterator() {
return new Iterator() {
int b = bits;
public boolean hasNext() {
return b != 0;
}
public E next() {
int b = this.b;
if (b == 0) throw new NoSuchElementException();
final int lob = lowestOneBit(b);
final E item = itemOf(numberOfTrailingZeros(lob));
this.b = b ^ lob;
return item;
}
};
}
/**
* Iterate this set in order from last to first flag.
*
* @return the iterator
*/
public final Iterator descendingIterator() {
return new Iterator() {
int b = bits;
public boolean hasNext() {
return b != 0;
}
public E next() {
int b = this.b;
if (b == 0) throw new NoSuchElementException();
final int hob = highestOneBit(b);
final E item = itemOf(numberOfTrailingZeros(hob));
this.b = b ^ hob;
return item;
}
};
}
/**
* Apply the given action for every flag in this set.
*
* @param action the action to apply
*/
public void forEach(final Consumer super E> action) {
Assert.checkNotNullParam("action", action);
int b = this.bits;
while (b != 0) {
int lob = lowestOneBit(b);
action.accept(itemOf(numberOfTrailingZeros(lob)));
b = b ^ lob;
}
}
/**
* Get a string representation of this flag set.
*
* @return the string representation
*/
public final String toString() {
StringBuilder buf = new StringBuilder();
buf.append(getClass().getSimpleName()).append('[');
int lob;
int bits = this.bits;
if (bits != 0) {
lob = lowestOneBit(bits);
buf.append(itemOf(numberOfTrailingZeros(lob)));
bits ^= lob;
while (bits != 0) {
buf.append(' ');
lob = lowestOneBit(bits);
buf.append(itemOf(numberOfTrailingZeros(lob)));
bits ^= lob;
}
}
buf.append(']');
return buf.toString();
}
private static int bitOf(Enum> item) {
return 1 << item.ordinal();
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ 0000775 0000000 0000000 00000000000 13615110664 0025525 5 ustar 00root root 0000000 0000000 wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBiConsumer.java 0000664 0000000 0000000 00000003436 13615110664 0032323 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.function;
import org.wildfly.common.Assert;
/**
* A two-argument consumer which can throw an exception.
*
* @author David M. Lloyd
*/
@FunctionalInterface
public interface ExceptionBiConsumer {
/**
* Performs this operation on the given arguments.
*
* @param t the first argument
* @param u the second argument
* @throws E if an exception occurs
*/
void accept(T t, U u) throws E;
default ExceptionBiConsumer andThen(ExceptionBiConsumer super T, ? super U, ? extends E> after) {
Assert.checkNotNullParam("after", after);
return (t, u) -> {
accept(t, u);
after.accept(t, u);
};
}
default ExceptionRunnable compose(ExceptionSupplier extends T, ? extends E> before1, ExceptionSupplier extends U, ? extends E> before2) {
Assert.checkNotNullParam("before1", before1);
Assert.checkNotNullParam("before2", before2);
return () -> accept(before1.get(), before2.get());
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBiFunction.java 0000664 0000000 0000000 00000003746 13615110664 0032321 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.function;
import org.wildfly.common.Assert;
/**
* A two-argument function which can throw an exception.
*
* @author David M. Lloyd
*/
@FunctionalInterface
public interface ExceptionBiFunction {
/**
* Applies this function to the given arguments.
*
* @param t the first argument
* @param u the second argument
* @return the function result
* @throws E if an exception occurs
*/
R apply(T t, U u) throws E;
default ExceptionBiFunction andThen(ExceptionFunction super R, ? extends R2, ? extends E> after) {
Assert.checkNotNullParam("after", after);
return (t, u) -> after.apply(apply(t, u));
}
default ExceptionBiConsumer andThen(ExceptionConsumer after) {
Assert.checkNotNullParam("after", after);
return (t, u) -> after.accept(apply(t, u));
}
default ExceptionSupplier compose(ExceptionSupplier extends T, ? extends E> before1, ExceptionSupplier extends U, ? extends E> before2) {
Assert.checkNotNullParam("before1", before1);
Assert.checkNotNullParam("before2", before2);
return () -> apply(before1.get(), before2.get());
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBiPredicate.java 0000664 0000000 0000000 00000003433 13615110664 0032425 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.function;
/**
* A two-argument predicate which can throw an exception.
*
* @author David M. Lloyd
*/
@FunctionalInterface
public interface ExceptionBiPredicate {
/**
* Evaluate this predicate on the given arguments.
*
* @param t the first argument
* @param u the second argument
* @return {@code true} if the predicate passes, {@code false} otherwise
* @throws E if an exception occurs
*/
boolean test(T t, U u) throws E;
default ExceptionBiPredicate and(ExceptionBiPredicate other) {
return (t, u) -> test(t, u) && other.test(t, u);
}
default ExceptionBiPredicate or(ExceptionBiPredicate other) {
return (t, u) -> test(t, u) || other.test(t, u);
}
default ExceptionBiPredicate xor(ExceptionBiPredicate other) {
return (t, u) -> test(t, u) != other.test(t, u);
}
default ExceptionBiPredicate not() {
return (t, u) -> !test(t, u);
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionBinaryOperator.java 0000664 0000000 0000000 00000002341 13615110664 0033207 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.function;
import org.wildfly.common.Assert;
/**
* A binary operator which can throw an exception.
*
* @author David M. Lloyd
*/
@FunctionalInterface
public interface ExceptionBinaryOperator extends ExceptionBiFunction {
default ExceptionBinaryOperator andThen(ExceptionUnaryOperator after) {
Assert.checkNotNullParam("after", after);
return (t, u) -> after.apply(apply(t, u));
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionConsumer.java 0000664 0000000 0000000 00000003477 13615110664 0032055 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.function;
import org.wildfly.common.Assert;
/**
* A one-argument consumer which can throw an exception.
*
* @author David M. Lloyd
*/
@FunctionalInterface
public interface ExceptionConsumer {
/**
* Performs this operation on the given argument.
*
* @param t the argument
* @throws E if an exception occurs
*/
void accept(T t) throws E;
default ExceptionConsumer andThen(ExceptionConsumer super T, ? extends E> after) {
Assert.checkNotNullParam("after", after);
return t -> {
accept(t);
after.accept(t);
};
}
default ExceptionConsumer compose(ExceptionConsumer super T, ? extends E> before) {
Assert.checkNotNullParam("before", before);
return t -> {
accept(t);
before.accept(t);
};
}
default ExceptionRunnable compose(ExceptionSupplier extends T, ? extends E> before) {
Assert.checkNotNullParam("before", before);
return () -> accept(before.get());
}
}
wildfly-common-1.5.3.Final/src/main/java/org/wildfly/common/function/ExceptionFunction.java 0000664 0000000 0000000 00000005526 13615110664 0032044 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wildfly.common.function;
import org.wildfly.common.Assert;
/**
* A one-argument function which can throw an exception.
*
* @author David M. Lloyd
*/
@FunctionalInterface
public interface ExceptionFunction {
/**
* Applies this function to the given arguments.
*
* @param t the argument
* @return the function result
* @throws E if an exception occurs
*/
R apply(T t) throws E;
default ExceptionFunction andThen(ExceptionFunction super R, ? extends R2, ? extends E> after) {
Assert.checkNotNullParam("after", after);
return t -> after.apply(apply(t));
}
default ExceptionFunction andThen(ExceptionBiFunction super T, ? super R, ? extends R2, ? extends E> after) {
Assert.checkNotNullParam("after", after);
return t -> after.apply(t, apply(t));
}
default ExceptionFunction compose(ExceptionFunction super T2, ? extends T, ? extends E> before) {
Assert.checkNotNullParam("before", before);
return t -> apply(before.apply(t));
}
default ExceptionConsumer