code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public <E> Iterable<E> searchForAll(final Collection<E> collection) {
Assert.notNull(collection, "The collection to search cannot be null!");
final List<E> results = new ArrayList<>(collection.size());
for (E element : collection) {
if (getMatcher().isMatch(element)) {
results.add(element);
... | java |
public <E> Iterable<E> searchForAll(final Searchable<E> searchable) {
try {
return searchForAll(configureMatcher(searchable).asList());
}
finally {
MatcherHolder.unset();
}
} | java |
protected <T> Searchable<T> configureMatcher(final Searchable<T> searchable) {
if (isCustomMatcherAllowed()) {
Matcher<T> matcher = searchable.getMatcher();
if (matcher != null) {
MatcherHolder.set(matcher);
}
}
return searchable;
} | java |
@NullSafe
public static File assertExists(File path) throws FileNotFoundException {
if (isExisting(path)) {
return path;
}
throw new FileNotFoundException(String.format("[%1$s] was not found", path));
} | java |
public static String getExtension(File file) {
Assert.notNull(file, "File cannot be null");
String filename = file.getName();
int dotIndex = filename.indexOf(StringUtils.DOT_SEPARATOR);
return (dotIndex != -1 ? filename.substring(dotIndex + 1) : StringUtils.EMPTY_STRING);
} | java |
public static String getLocation(File file) {
Assert.notNull(file, "File cannot be null");
File parent = file.getParentFile();
Assert.notNull(parent, new IllegalArgumentException(String.format(
"Unable to determine the location of file [%1$s]", file)));
return tryGetCanonicalPathElseGetAbsolutePat... | java |
public static File tryGetCanonicalFileElseGetAbsoluteFile(File file) {
try {
return file.getCanonicalFile();
}
catch (IOException ignore) {
return file.getAbsoluteFile();
}
} | java |
public static String tryGetCanonicalPathElseGetAbsolutePath(File file) {
try {
return file.getCanonicalPath();
}
catch (IOException ignore) {
return file.getAbsolutePath();
}
} | java |
public static br_currentconfig get(nitro_service client, br_currentconfig resource) throws Exception
{
resource.validate("get");
return ((br_currentconfig[]) resource.get_resources(client))[0];
} | java |
public static String join(Collection<? extends Object> lst, String separator) {
StringBuilder buf = new StringBuilder(lst.size() * 64);
boolean first = true;
for (Object value : lst) {
if (first) first = false; else buf.append(separator);
buf.append(value.toString());
... | java |
public static <T> T last(List<T> lst) {
if (lst == null || lst.isEmpty()) return null;
return lst.get(lst.size() - 1);
} | java |
@SuppressWarnings("unchecked")
public static <From, To> List<To> map(List<From> list, MapClosure<From,To> f) {
List<To> result = new ArrayList<To>(list.size());
for (From value : list) {
result.add( f.eval(value) );
}
return result;
} | java |
public static <Accumulator, Value> Accumulator reduce(List<Value> list, Accumulator init, ReduceClosure<Accumulator,Value> f) {
Accumulator accumulator = init;
for (Value value : list) {
accumulator = f.eval(accumulator, value);
}
return accumulator;
} | java |
@SuppressWarnings("unchecked")
public static int median(List<Integer> values) {
if (values == null || values.isEmpty()) return 0;
values = new ArrayList<Integer>(values);
Collections.sort(values);
final int size = values.size();
final int sizeHalf = size / 2;
if (si... | java |
static JsonRpcResponse error(JsonRpcError error, JsonElement id) {
return new JsonRpcResponse(id, error, null);
} | java |
public static JsonRpcResponse success(JsonObject payload, JsonElement id) {
return new JsonRpcResponse(id, null, payload);
} | java |
public JsonObject toJson() {
JsonObject body = new JsonObject();
body.add(JsonRpcProtocol.ID, id());
if (isError()) {
body.add(JsonRpcProtocol.ERROR, error().toJson());
} else {
body.add(JsonRpcProtocol.RESULT, result());
}
return body;
} | java |
public static traceroute get(nitro_service client, traceroute resource) throws Exception
{
resource.validate("get");
return ((traceroute[]) resource.get_resources(client))[0];
} | java |
public static traceroute[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception
{
traceroute obj = new traceroute();
options option = new options();
option.set_filter(filter);
traceroute[] response = (traceroute[]) obj.getfiltered(service, option);
return response;
} | java |
public boolean isMatching(MouseEvent event) {
return (event != null) && !event.isConsumed()
&& (mouseModifiers.isNone()
|| ((event.isPrimaryButtonDown() == mouseButtons.isPrimary())
&& (event.isMiddleButtonDown() == mouseButtons.isMiddle())
&& (eve... | java |
private WebTarget configure(String token, boolean debug, Logger log, int maxLog) {
Client client = ClientBuilder.newBuilder()
.register(MultiPartFeature.class)
.register(JsonProcessingFeature.class)
.build();
client.register(HttpAuthenticationFeature.basi... | java |
protected <JsonType extends JsonStructure, ValueType>
ValueType invoke(String operation, String id, String action, QueryClosure queryClosure, RequestClosure<JsonType> requestClosure, ResponseClosure<JsonType, ValueType> responseClosure) {
try {
WebTarget ws = wsBase.path(operation);
... | java |
protected void checkApiToken(String apiToken) {
if (StringUtils.isBlank(apiToken)) throw new MissingApiTokenException("Empty key");
if (apiToken.length() != TOKEN_LENGTH) throw new MissingApiTokenException("Wrong length");
if (!apiToken.matches(HEX_PATTERN)) throw new MissingApiTokenException("N... | java |
public boolean isValidToken() {
try {
// Response response = wsBase.path(TEST_CONFIGS).request(MediaType.APPLICATION_JSON_TYPE).get();
// return response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL;
LoadZone zone = getLoadZone(LoadZone.AMAZON_US_ASHBURN.ui... | java |
public LoadZone getLoadZone(String id) {
return invoke(LOAD_ZONES, id, null, null,
new RequestClosure<JsonArray>() {
@Override
public JsonArray call(Invocation.Builder request) {
return request.get(JsonArray.class);
... | java |
public List<LoadZone> getLoadZone() {
return invoke(LOAD_ZONES,
new RequestClosure<JsonArray>() {
@Override
public JsonArray call(Invocation.Builder request) {
return request.get(JsonArray.class);
}
... | java |
public DataStore getDataStore(int id) {
return invoke(DATA_STORES, id,
new RequestClosure<JsonObject>() {
@Override
public JsonObject call(Invocation.Builder request) {
return request.get(JsonObject.class);
}
... | java |
public List<DataStore> getDataStores() {
return invoke(DATA_STORES,
new RequestClosure<JsonArray>() {
@Override
public JsonArray call(Invocation.Builder request) {
return request.get(JsonArray.class);
}
... | java |
public void deleteDataStore(final int id) {
invoke(DATA_STORES, id,
new RequestClosure<JsonStructure>() {
@Override
public JsonStructure call(Invocation.Builder request) {
Response response = request.delete();
... | java |
public DataStore createDataStore(final File file, final String name, final int fromline, final DataStore.Separator separator, final DataStore.StringDelimiter delimiter) {
return invoke(DATA_STORES,
new RequestClosure<JsonObject>() {
@Override
public JsonOb... | java |
public UserScenario getUserScenario(int id) {
return invoke(USER_SCENARIOS, id,
new RequestClosure<JsonObject>() {
@Override
public JsonObject call(Invocation.Builder request) {
return request.get(JsonObject.class);
... | java |
public List<UserScenario> getUserScenarios() {
return invoke(USER_SCENARIOS,
new RequestClosure<JsonArray>() {
@Override
public JsonArray call(Invocation.Builder request) {
return request.get(JsonArray.class);
}
... | java |
public UserScenario createUserScenario(final UserScenario scenario) {
return invoke(USER_SCENARIOS,
new RequestClosure<JsonObject>() {
@Override
public JsonObject call(Invocation.Builder request) {
String json = scenario.toJ... | java |
public UserScenarioValidation getUserScenarioValidation(int id) {
return invoke(USER_SCENARIO_VALIDATIONS, id,
new RequestClosure<JsonObject>() {
@Override
public JsonObject call(Invocation.Builder request) {
return request.get(Json... | java |
@Override
@SuppressWarnings("unchecked")
public void setModifiedBy(USER modifiedBy) {
this.modifiedBy = assertNotNull(modifiedBy, () -> "Modified by is required");
this.lastModifiedBy = defaultIfNull(this.lastModifiedBy, this.modifiedBy);
} | java |
public static br reboot(nitro_service client, br resource) throws Exception
{
return ((br[]) resource.perform_operation(client, "reboot"))[0];
} | java |
public static br stop(nitro_service client, br resource) throws Exception
{
return ((br[]) resource.perform_operation(client, "stop"))[0];
} | java |
public static br force_reboot(nitro_service client, br resource) throws Exception
{
return ((br[]) resource.perform_operation(client, "force_reboot"))[0];
} | java |
public static br force_stop(nitro_service client, br resource) throws Exception
{
return ((br[]) resource.perform_operation(client, "force_stop"))[0];
} | java |
public static br start(nitro_service client, br resource) throws Exception
{
return ((br[]) resource.perform_operation(client, "start"))[0];
} | java |
public boolean isMatching(GestureEvent event) {
return (event != null) && !event.isConsumed()
&& (gestureModifiers.isNone()
|| ((event.isAltDown() == gestureModifiers.isAlt())
&& (event.isShiftDown() == gestureModifiers.isShift())
&& (event.isContr... | java |
public static prune_policy get(nitro_service client, prune_policy resource) throws Exception
{
resource.validate("get");
return ((prune_policy[]) resource.get_resources(client))[0];
} | java |
@Override
@SuppressWarnings("unchecked")
public <E> E search(final Collection<E> collection) {
Assert.isInstanceOf(collection, List.class, "The collection {0} must be an instance of java.util.List!",
ClassUtils.getClassName(collection));
return doSearch((List<E>) collection);
} | java |
public void close() {
refuseNewRequests.set(true);
channel.close().awaitUninterruptibly();
channel.eventLoop().shutdownGracefully().awaitUninterruptibly();
} | java |
protected FraggleFragment peek(String tag) {
if (fm != null) {
return (FraggleFragment) fm.findFragmentByTag(tag);
}
return new EmptyFragment();
} | java |
protected void processAnimations(FragmentAnimation animation, FragmentTransaction ft) {
if (animation != null) {
if (animation.isCompletedAnimation()) {
ft.setCustomAnimations(animation.getEnterAnim(), animation.getExitAnim(),
animation.getPushInAnim(), animat... | java |
protected void configureAdditionMode(Fragment frag, int flags, FragmentTransaction ft, int containerId) {
if ((flags & DO_NOT_REPLACE_FRAGMENT) != DO_NOT_REPLACE_FRAGMENT) {
ft.replace(containerId, frag, ((FraggleFragment) frag).getFragmentTag());
} else {
ft.add(containerId, fra... | java |
protected void performTransaction(Fragment frag, int flags, FragmentTransaction ft, int containerId) {
configureAdditionMode(frag, flags, ft, containerId);
ft.commitAllowingStateLoss();
} | java |
protected FraggleFragment peek() {
if (fm.getBackStackEntryCount() > 0) {
return ((FraggleFragment) fm.findFragmentByTag(
fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName()));
} else {
return new EmptyFragment();
}
} | java |
public void clear() {
if (fm != null) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
fm = null;
} | java |
public void reattach(String tag) {
final Fragment currentFragment = (Fragment) peek(tag);
FragmentTransaction fragTransaction = fm.beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
} | java |
public Set<String> keys(String pattern) {
Set<String> result = new TreeSet<String>();
for (String key : keys()) {
if (key.matches(pattern)) result.add(key);
}
return result;
} | java |
public String get(String key, String defaultValue) {
String value = parameters.get(key);
return StringUtils.isBlank(value) ? defaultValue : value;
} | java |
public static system_settings get(nitro_service client) throws Exception
{
system_settings resource = new system_settings();
resource.validate("get");
return ((system_settings[]) resource.get_resources(client))[0];
} | java |
@Override
@SuppressWarnings("unchecked")
public <E> Comparator<E> getOrderBy() {
return ObjectUtils.defaultIfNull(ComparatorHolder.get(), ObjectUtils.defaultIfNull(
orderBy, ComparableComparator.INSTANCE));
} | java |
@Override
@SuppressWarnings("unchecked")
public <E> E[] sort(final E... elements) {
sort(new SortableArrayList(elements));
return elements;
} | java |
@Override
public <E> Sortable<E> sort(final Sortable<E> sortable) {
try {
sort(configureComparator(sortable).asList());
return sortable;
}
finally {
ComparatorHolder.unset();
}
} | java |
@SafeVarargs
public static <T> @NonNull Optional<T> first(final @NonNull Optional<T>... optionals) {
return Arrays.stream(optionals)
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
} | java |
@SuppressWarnings("unchecked")
public static <T extends Searcher> T createSearcher(final SearchType type) {
switch (ObjectUtils.defaultIfNull(type, SearchType.UNKNOWN_SEARCH)) {
case BINARY_SEARCH:
return (T) new BinarySearch();
case LINEAR_SEARCH:
return (T) new LinearSearch();
... | java |
public static <T extends Searcher> T createSearcherElseDefault(final SearchType type, final T defaultSearcher) {
try {
return createSearcher(type);
}
catch (IllegalArgumentException ignore) {
return defaultSearcher;
}
} | java |
private void balance() {
// only try to balance when we're not terminating
if(!isTerminated()) {
Set<Map.Entry<Thread, Tracking>> threads = liveThreads.entrySet();
long liveAvgTimeTotal = 0;
long liveAvgCpuTotal = 0;
long liveCount = 0;
for (Ma... | java |
public void setMenu(Menu menu) {
this.menu = menu;
RadialMenuItem.setupMenuButton(this, radialMenuParams, (menu != null) ? menu.getGraphic() : null, (menu != null) ? menu.getText() : null, true);
} | java |
@Override
public <E> List<E> sort(final List<E> elements) {
int size = elements.size();
// create the heap
for (int parentIndex = ((size - 2) / 2); parentIndex >= 0; parentIndex--) {
siftDown(elements, parentIndex, size - 1);
}
// swap the first and last elements in the heap of array since... | java |
protected <E> void siftDown(final List<E> elements, final int startIndex, final int endIndex) {
int rootIndex = startIndex;
while ((rootIndex * 2 + 1) <= endIndex) {
int swapIndex = rootIndex;
int leftChildIndex = (rootIndex * 2 + 1);
int rightChildIndex = (leftChildIndex + 1);
if (get... | java |
public void fireChangeEvent() {
ChangeEvent event = createChangeEvent(getSource());
for (ChangeListener listener : this) {
listener.stateChanged(event);
}
} | java |
@Override
public <E> List<E> sort(final List<E> elements) {
int elementsSize = elements.size();
if (elementsSize <= getSizeThreshold()) {
return getSorter().sort(elements);
}
else {
int beginIndex = 1;
int endIndex = (elementsSize - 1);
E pivotElement = elements.get(0);
... | java |
public void onBeforeAdd(E value) {
long freeHeapSpace = RUNTIME.freeMemory() + (RUNTIME.maxMemory() - RUNTIME.totalMemory());
// start flow control if we cross the threshold
if (freeHeapSpace < minimumHeapSpaceBeforeFlowControl) {
// x indicates how close we are to overflowing the ... | java |
public void onAfterRemove(E value) {
if (value != null) {
dequeued++;
if (dequeued % dequeueHint == 0) {
RUNTIME.gc();
}
}
} | java |
public void propertyChange(final PropertyChangeEvent event) {
if (objectStateMap.containsKey(event.getPropertyName())) {
if (objectStateMap.get(event.getPropertyName()) == ObjectUtils.hashCode(event.getNewValue())) {
// NOTE the state of the property identified by the event has been reverted to it's o... | java |
public void setResponse(JsonRpcResponse response) {
if (response.isError()) {
setException(response.error());
return;
}
try {
set((V) Messages.fromJson(method.outputBuilder(), response.result()));
} catch (Exception e) {
setException(e);
}
} | java |
@SuppressWarnings("unchecked")
protected Class[] getArgumentTypes(final Object... arguments) {
Class[] argumentTypes = new Class[arguments.length];
int index = 0;
for (Object argument : arguments) {
argumentTypes[index++] = ObjectUtils.defaultIfNull(ClassUtils.getClass(argument), Object.class);
... | java |
protected Constructor resolveConstructor(final Class<?> objectType, final Class... parameterTypes) {
try {
return objectType.getConstructor(parameterTypes);
}
catch (NoSuchMethodException e) {
if (!ArrayUtils.isEmpty(parameterTypes)) {
Constructor constructor = resolveCompatibleConstruct... | java |
@SuppressWarnings("unchecked")
protected Constructor resolveCompatibleConstructor(final Class<?> objectType, final Class<?>[] parameterTypes) {
for (Constructor constructor : objectType.getConstructors()) {
Class[] constructorParameterTypes = constructor.getParameterTypes();
if (parameterTypes.length... | java |
@Override
@SuppressWarnings("unchecked")
public <T> T create(final String objectTypeName, final Object... args) {
return (T) create(ClassUtils.loadClass(objectTypeName), getArgumentTypes(args), args);
} | java |
@Override
public <T> T create(final Class<T> objectType, final Object... args) {
return create(objectType, getArgumentTypes(args), args);
} | java |
private static int copyPathFragment(char[] input, int beginIndex, StringBuilder output)
{
int inputCharIndex = beginIndex;
while (inputCharIndex < input.length)
{
final char inputChar = input[inputCharIndex];
if (inputChar == '/')
{
break;
}
output.append(inputChar);
inputCharIndex += 1;
... | java |
public ListenableFuture<JsonRpcResponse> invoke(JsonRpcRequest request) {
Service service = services.lookupByName(request.service());
if (service == null) {
JsonRpcError error = new JsonRpcError(HttpResponseStatus.BAD_REQUEST,
"Unknown service: " + request.service());
JsonRpcResponse respo... | java |
private <I extends Message, O extends Message> ListenableFuture<JsonRpcResponse> invoke(
ServerMethod<I, O> method, JsonObject parameter, JsonElement id) {
I request;
try {
request = (I) Messages.fromJson(method.inputBuilder(), parameter);
} catch (Exception e) {
serverLogger.logServerFail... | java |
protected synchronized void addContent(Artifact record, String filename) {
if (record != null) {
if (filename.endsWith(".jar")) {
// this is an embedded archive
embedded.add(record);
} else {
contents.add(record);
}
}
... | java |
protected void submitJob(ExecutorService executor, Content file) {
// lifted from http://stackoverflow.com/a/5853198/1874604
class OneShotTask implements Runnable {
Content file;
OneShotTask(Content file) {
this.file = file;
}
public void... | java |
public static <T extends Comparable<T>> ComparableValueHolder<T> withComparableValue(final T value) {
return new ComparableValueHolder<>(value);
} | java |
public static <T extends Cloneable> ValueHolder<T> withImmutableValue(final T value) {
return new ValueHolder<T>(ObjectUtils.clone(value)) {
@Override public T getValue() {
return ObjectUtils.clone(super.getValue());
}
@Override public void setValue(final T value) {
super.setValue... | java |
public static <T> ValueHolder<T> withNonNullValue(final T value) {
Assert.notNull(value, "The value must not be null!");
return new ValueHolder<T>(value) {
@Override
public void setValue(final T value) {
Assert.notNull(value, "The value must not be null!");
super.setValue(value);
... | java |
public static xen reboot(nitro_service client, xen resource) throws Exception
{
return ((xen[]) resource.perform_operation(client, "reboot"))[0];
} | java |
public static xen stop(nitro_service client, xen resource) throws Exception
{
return ((xen[]) resource.perform_operation(client, "stop"))[0];
} | java |
public static xen[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception
{
xen obj = new xen();
options option = new options();
option.set_filter(filter);
xen[] response = (xen[]) obj.getfiltered(service, option);
return response;
} | java |
public static sdx_license get(nitro_service client) throws Exception
{
sdx_license resource = new sdx_license();
resource.validate("get");
return ((sdx_license[]) resource.get_resources(client))[0];
} | java |
@Override
public void visit(final Visitable visitable) {
if (visitable instanceof Auditable) {
modified |= ((Auditable) visitable).isModified();
}
} | java |
public FilterBuilder<T> addWithAnd(final Filter<T> filter) {
filterInstance = ComposableFilter.and(filterInstance, filter);
return this;
} | java |
public FilterBuilder<T> addWithOr(final Filter<T> filter) {
filterInstance = ComposableFilter.or(filterInstance, filter);
return this;
} | java |
@SuppressWarnings("unchecked")
public static <T> T[] filter(T[] array, Filter<T> filter) {
Assert.notNull(array, "Array is required");
Assert.notNull(filter, "Filter is required");
List<T> arrayList = stream(array).filter(filter::accept).collect(Collectors.toList());
return arrayList.toArray((T[]) ... | java |
@SuppressWarnings("unchecked")
public static <T> T[] filterAndTransform(T[] array, FilteringTransformer<T> filteringTransformer) {
return transform(filter(array, filteringTransformer), filteringTransformer);
} | java |
@SuppressWarnings("unchecked")
public static <T> T[] insert(T element, T[] array, int index) {
Assert.notNull(array, "Array is required");
assertThat(index).throwing(new ArrayIndexOutOfBoundsException(
String.format("[%1$d] is not a valid index [0, %2$d] in the array", index, array.length)))
.... | java |
@SuppressWarnings("unchecked")
public static <T> T[] remove(T[] array, int index) {
Assert.notNull(array, "Array is required");
assertThat(index).throwing(new ArrayIndexOutOfBoundsException(
String.format("[%1$d] is not a valid index [0, %2$d] in the array", index, array.length)))
.isGreaterTh... | java |
public static <T> T[] sort(T[] array, Comparator<T> comparator) {
Arrays.sort(array, comparator);
return array;
} | java |
@SuppressWarnings("unchecked")
public static <T> T[] subArray(T[] array, int... indices) {
List<T> subArrayList = new ArrayList<>(indices.length);
for (int index : indices) {
subArrayList.add(array[index]);
}
return subArrayList.toArray((T[]) Array.newInstance(array.getClass().getComponentTyp... | java |
public static <T> T[] swap(T[] array, int indexOne, int indexTwo) {
T elementAtIndexOne = array[indexOne];
array[indexOne] = array[indexTwo];
array[indexTwo] = elementAtIndexOne;
return array;
} | java |
public static void warnFormatted(final Exception exception) {
logWriterInstance.warn(exception);
UaiWebSocketLogManager.addLogText("[WARN] An exception just happened: " + exception.getMessage());
} | java |
public static JsonObject toJson(Message output) {
JsonObject object = new JsonObject();
for (Map.Entry<Descriptors.FieldDescriptor, Object> field : output.getAllFields().entrySet()) {
String jsonName = CaseFormat.LOWER_UNDERSCORE.to(
CaseFormat.LOWER_CAMEL, field.getKey().getName());
if (f... | java |
public static Message fromJson(Message.Builder builder, JsonObject input) throws Exception {
Descriptors.Descriptor descriptor = builder.getDescriptorForType();
for (Map.Entry<String, JsonElement> entry : input.entrySet()) {
String protoName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.g... | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.