repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/MapPutFunction.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.function; import java.util.Map; /** * Function that puts an entry into a map. * @author Paul Ferraro * @param <K> the map key type * @param <V> the map value type */ public class MapPutFunction<K, V> extends MapFunction<K, V, Map.Entry<K, V>> { public MapPutFunction(Map.Entry<K, V> operand, Operations<Map<K, V>> operations) { super(operand, operations, operations); } @Override public Map.Entry<K, V> getOperand() { return super.getOperand(); } @Override public void accept(Map<K, V> map, Map.Entry<K, V> entry) { map.put(entry.getKey(), entry.getValue()); } }
1,693
33.571429
86
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/ConcurrentSetRemoveFunction.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.function; /** * Function that removes an item from a set within a non-transactional cache. * @author Paul Ferraro * @param <V> the set element type */ public class ConcurrentSetRemoveFunction<V> extends SetRemoveFunction<V> { public ConcurrentSetRemoveFunction(V value) { super(value, new ConcurrentSetOperations<>()); } }
1,409
38.166667
77
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/AbstractFunction.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.function; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; /** * Function that operates on an operable object. * @author Paul Ferraro * @param <T> the operand type * @param <O> the operable object type */ public abstract class AbstractFunction<T, O> implements BiFunction<Object, O, O>, BiConsumer<O, T> { private final T operand; private final UnaryOperator<O> copier; private final Supplier<O> factory; private final Function<O, Boolean> empty; public AbstractFunction(T operand, UnaryOperator<O> copier, Supplier<O> factory, Function<O, Boolean> empty) { this.operand = operand; this.copier = copier; this.factory = factory; this.empty = empty; } @Override public O apply(Object key, O operable) { // Transactional caches must operate on a copy of the operable object O result = (operable != null) ? this.copier.apply(operable) : this.factory.get(); this.accept(result, this.operand); return !this.empty.apply(result) ? result : null; } public T getOperand() { return this.operand; } }
2,319
36.419355
114
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/ConcurrentMapRemoveFunction.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.function; /** * Function that removes an entry from a map within a non-transactional cache. * @author Paul Ferraro * @param <K> the map key type * @param <V> the map value type */ public class ConcurrentMapRemoveFunction<K, V> extends MapRemoveFunction<K, V> { public ConcurrentMapRemoveFunction(K key) { super(key, new ConcurrentMapOperations<>()); } }
1,441
37.972973
80
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/function/FunctionSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.function; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Map; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; import org.wildfly.clustering.marshalling.protostream.FunctionalMarshaller; import org.wildfly.clustering.marshalling.protostream.FunctionalScalarMarshaller; import org.wildfly.clustering.marshalling.protostream.Scalar; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class FunctionSerializationContextInitializer extends AbstractSerializationContextInitializer { @SuppressWarnings("unchecked") @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new FunctionalMarshaller<>(ConcurrentMapPutFunction.class, (Class<Map.Entry<Object, Object>>) (Class<?>) SimpleImmutableEntry.class, ConcurrentMapPutFunction<Object, Object>::getOperand, ConcurrentMapPutFunction<Object, Object>::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(ConcurrentMapRemoveFunction.class, Scalar.ANY, ConcurrentMapRemoveFunction::getOperand, ConcurrentMapRemoveFunction::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(ConcurrentSetAddFunction.class, Scalar.ANY, ConcurrentSetAddFunction::getOperand, ConcurrentSetAddFunction::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(ConcurrentSetRemoveFunction.class, Scalar.ANY, ConcurrentSetRemoveFunction::getOperand, ConcurrentSetRemoveFunction::new)); context.registerMarshaller(new FunctionalMarshaller<>(CopyOnWriteMapPutFunction.class, (Class<Map.Entry<Object, Object>>) (Class<?>) SimpleImmutableEntry.class, CopyOnWriteMapPutFunction<Object, Object>::getOperand, CopyOnWriteMapPutFunction<Object, Object>::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(CopyOnWriteMapRemoveFunction.class, Scalar.ANY, CopyOnWriteMapRemoveFunction::getOperand, CopyOnWriteMapRemoveFunction::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(CopyOnWriteSetAddFunction.class, Scalar.ANY, CopyOnWriteSetAddFunction::getOperand, CopyOnWriteSetAddFunction::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(CopyOnWriteSetRemoveFunction.class, Scalar.ANY, CopyOnWriteSetRemoveFunction::getOperand, CopyOnWriteSetRemoveFunction::new)); } }
3,629
65
273
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/LinkedScheduledEntries.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.scheduler; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; /** * {@link ScheduledEntries} implemented using a {@link ConcurrentDirectDeque}. * Both {@link #add(Object, Object)} and {@link #remove(Object)} run in O(1) time. * @author Paul Ferraro */ public class LinkedScheduledEntries<K, V> implements ScheduledEntries<K, V> { private final ConcurrentDirectDeque<Map.Entry<K, V>> queue = ConcurrentDirectDeque.newInstance(); private final Map<K, Object> tokens = new ConcurrentHashMap<>(); @Override public boolean isSorted() { return false; } @Override public void add(K key, V value) { Object token = this.queue.offerLastAndReturnToken(new SimpleImmutableEntry<>(key, value)); this.tokens.put(key, token); } @Override public void remove(K key) { Object token = this.tokens.remove(key); if (token != null) { this.queue.removeToken(token); } } @Override public boolean contains(K key) { return this.tokens.containsKey(key); } @Override public Map.Entry<K, V> peek() { return this.queue.peekFirst(); } @Override public Stream<Map.Entry<K, V>> stream() { return this.queue.stream(); } @Override public Iterator<Map.Entry<K, V>> iterator() { Iterator<Map.Entry<K, V>> iterator = this.queue.iterator(); Map<K, Object> tokens = this.tokens; return new Iterator<>() { private K current = null; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Map.Entry<K, V> next() { Map.Entry<K, V> next = iterator.next(); this.current = next.getKey(); return next; } @Override public void remove() { iterator.remove(); tokens.remove(this.current); } }; } @Override public String toString() { return this.queue.toString(); } }
3,295
30.390476
101
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/LocalScheduler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.scheduler; import java.time.Duration; import java.time.Instant; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Iterator; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Stream; import org.wildfly.clustering.context.DefaultExecutorService; import org.wildfly.clustering.context.DefaultThreadFactory; import org.wildfly.clustering.ee.Scheduler; import org.wildfly.security.manager.WildFlySecurityManager; /** * Scheduler that uses a single scheduled task in concert with an {@link ScheduledEntries}. * @author Paul Ferraro */ public class LocalScheduler<T> implements Scheduler<T, Instant>, Runnable { private final ScheduledExecutorService executor; private final ScheduledEntries<T, Instant> entries; private final Predicate<T> task; private final Duration closeTimeout; private volatile Map.Entry<Map.Entry<T, Instant>, Future<?>> futureEntry = null; public LocalScheduler(ScheduledEntries<T, Instant> entries, Predicate<T> task, Duration closeTimeout) { ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new DefaultThreadFactory(this.getClass())); executor.setKeepAliveTime(1L, TimeUnit.MINUTES); executor.allowCoreThreadTimeOut(true); executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); executor.setRemoveOnCancelPolicy(entries.isSorted()); this.executor = executor; this.entries = entries; this.task = task; this.closeTimeout = closeTimeout; } @Override public void schedule(T id, Instant instant) { this.entries.add(id, instant); if (this.entries.isSorted()) { this.rescheduleIfEarlier(instant); } this.scheduleIfAbsent(); } @Override public void cancel(T id) { if (this.entries.isSorted()) { this.cancelIfPresent(id); } this.entries.remove(id); if (this.entries.isSorted()) { this.scheduleIfAbsent(); } } @Override public boolean contains(T id) { return this.entries.contains(id); } @Override public Stream<T> stream() { return this.entries.stream().map(Map.Entry::getKey); } @Override public void close() { WildFlySecurityManager.doPrivilegedWithParameter(this.executor, DefaultExecutorService.SHUTDOWN_ACTION); if (!this.closeTimeout.isNegative() && !this.closeTimeout.isZero()) { try { this.executor.awaitTermination(this.closeTimeout.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @Override public void run() { Iterator<Map.Entry<T, Instant>> entries = this.entries.iterator(); while (entries.hasNext()) { if (Thread.currentThread().isInterrupted() || this.executor.isShutdown()) return; Map.Entry<T, Instant> entry = entries.next(); if (entry.getValue().isAfter(Instant.now())) break; T key = entry.getKey(); // Remove only if task is successful if (this.task.test(key)) { entries.remove(); } } synchronized (this) { this.futureEntry = this.scheduleFirst(); } } private Map.Entry<Map.Entry<T, Instant>, Future<?>> scheduleFirst() { Map.Entry<T, Instant> entry = this.entries.peek(); return (entry != null) ? this.schedule(entry) : null; } private Map.Entry<Map.Entry<T, Instant>, Future<?>> schedule(Map.Entry<T, Instant> entry) { Duration delay = Duration.between(Instant.now(), entry.getValue()); long millis = !delay.isNegative() ? delay.toMillis() + 1 : 0; try { Future<?> future = this.executor.schedule(this, millis, TimeUnit.MILLISECONDS); return new SimpleImmutableEntry<>(entry, future); } catch (RejectedExecutionException e) { return null; } } private void scheduleIfAbsent() { if (this.futureEntry == null) { synchronized (this) { if (this.futureEntry == null) { this.futureEntry = this.scheduleFirst(); } } } } private void rescheduleIfEarlier(Instant instant) { if (this.futureEntry != null) { synchronized (this) { if (this.futureEntry != null) { if (instant.isBefore(this.futureEntry.getKey().getValue())) { this.futureEntry.getValue().cancel(true); this.futureEntry = this.scheduleFirst(); } } } } } private void cancelIfPresent(T id) { if (this.futureEntry != null) { synchronized (this) { if (this.futureEntry != null) { if (this.futureEntry.getKey().getKey().equals(id)) { this.futureEntry.getValue().cancel(true); this.futureEntry = null; } } } } } @Override public String toString() { return this.entries.toString(); } }
6,645
34.924324
125
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/SortedScheduledEntries.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.scheduler; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedSet; import java.util.Spliterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListSet; import java.util.function.Consumer; import java.util.stream.Stream; /** * {@link ScheduledEntries} implemented using a {@link ConcurrentSkipListSet}, where entries are sorted based on the entry value. * Both {@link #add(Object, Comparable)} and {@link #remove(Object)} run in O(log N) time. * @author Paul Ferraro */ public class SortedScheduledEntries<K, V extends Comparable<? super V>> implements ScheduledEntries<K, V> { private final SortedSet<Map.Entry<K, V>> sorted; private final Map<K, V> entries = new ConcurrentHashMap<>(); static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K, V>> comparingByValue() { return new Comparator<>() { @Override public int compare(Map.Entry<K, V> entry1, Map.Entry<K, V> entry2) { int result = entry1.getValue().compareTo(entry2.getValue()); // Compare using keys if necessary, as value comparison of 0 does not imply equality! return (result == 0) ? Integer.compare(entry1.getKey().hashCode(), entry2.getKey().hashCode()) : result; } }; } /** * Creates a new entries object whose iteration order is based on the entry value. */ public SortedScheduledEntries() { this(comparingByValue()); } /** * Creates a new entries object whose iteration order is based on the specified comparator. * @param comparator the comparator used to determine the iteration order */ public SortedScheduledEntries(Comparator<Map.Entry<K, V>> comparator) { this.sorted = new ConcurrentSkipListSet<>(comparator); } @Override public boolean isSorted() { return true; } @Override public void add(K key, V value) { V oldValue = this.entries.put(key, value); if (oldValue != null) { this.sorted.remove(new Entry<>(key, oldValue)); } this.sorted.add(new Entry<>(key, value)); } @Override public void remove(K key) { V value = this.entries.remove(key); if (value != null) { this.sorted.remove(new Entry<>(key, value)); } } @Override public boolean contains(K key) { return this.entries.containsKey(key); } @Override public Map.Entry<K, V> peek() { try { return this.sorted.first(); } catch (NoSuchElementException e) { return null; } } @Override public Stream<Map.Entry<K, V>> stream() { return this.sorted.stream(); } @Override public Iterator<Map.Entry<K, V>> iterator() { Iterator<Map.Entry<K, V>> iterator = this.sorted.iterator(); Map<K, V> entries = this.entries; return new Iterator<>() { private K current = null; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Map.Entry<K, V> next() { Map.Entry<K, V> next = iterator.next(); this.current = next.getKey(); return next; } @Override public void remove() { iterator.remove(); entries.remove(this.current); } }; } @Override public void forEach(Consumer<? super Map.Entry<K, V>> action) { this.sorted.forEach(action); } @Override public Spliterator<Map.Entry<K, V>> spliterator() { return this.sorted.spliterator(); } @Override public String toString() { return this.sorted.toString(); } /** * A {@link SimpleImmutableEntry} whose equality is based solely on the entry key. */ private static class Entry<K, V> extends SimpleImmutableEntry<K, V> { private static final long serialVersionUID = -1818780078437540182L; Entry(K key, V value) { super(key, value); } @Override public boolean equals(Object object) { if (!(object instanceof Entry)) return false; Entry<?, ?> entry = (Entry<?, ?>) object; return this.getKey().equals(entry.getKey()); } @Override public int hashCode() { return this.getKey().hashCode(); } @Override public String toString() { return this.getKey().toString(); } } }
5,844
31.115385
129
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/ScheduledEntries.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.scheduler; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Stream; /** * A collection of scheduled entries with a predictable iteration order. * @author Paul Ferraro */ public interface ScheduledEntries<K, V> extends Iterable<Map.Entry<K, V>> { /** * Indicates whether the entries are sorted, or if iteration order recapitulates insertion order. * @return true, if these entries are sorted, false otherwise. */ boolean isSorted(); /** * Adds an entry using the specified key and value. * @param key an entry key * @param value an entry value */ void add(K key, V value); /** * Removes the entry with the specified key. * @param key an entry key */ void remove(K key); /** * Indicates whether specified key exists among the scheduled entries. * @param key an entry key * @return true, if the key is a scheduled entry, false otherwise */ boolean contains(K key); /** * Returns, but does not remove, the first entry. */ default Map.Entry<K, V> peek() { return this.stream().findFirst().orElse(null); } /** * Returns a stream of scheduled entries. * @return a stream of scheduled entries. */ Stream<Map.Entry<K, V>> stream(); @Override default Iterator<Entry<K, V>> iterator() { return this.stream().iterator(); } }
2,514
31.24359
101
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/ConcurrentDirectDeque.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014 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.clustering.ee.cache.scheduler; import java.util.Deque; /** * A concurrent deque that allows direct item removal without traversal. * * @author Jason T. Greene * @author Paul Ferraro */ public interface ConcurrentDirectDeque<E> extends Deque<E> { static <K> ConcurrentDirectDeque<K> newInstance() { return new FastConcurrentDirectDeque<>(); } /** * Equivalent to {@link #offerFirst(Object)}, but returns a token used for fast removal. * @param e the element to offer * @return a token suitable for use by {@link #remove(Object)} */ Object offerFirstAndReturnToken(E e); /** * Equivalent to {@link #offerLast(Object)}, but returns a token used for fast removal. * @param e the element to offer * @return a token suitable for use by {@link #remove(Object)} */ Object offerLastAndReturnToken(E e); /** * Removes the element associated with the given token. * @param token the token returned via {@link #offerFirstAndReturnToken(Object)} or {@link #offerLastAndReturnToken(Object)}. */ void removeToken(Object token); // Delegate collection methods to deque methods @Override default boolean add(E e) { return this.offerLast(e); } @Override default boolean remove(Object o) { return this.removeFirstOccurrence(o); } // Delegate stack methods to deque methods @Override default E peek() { return this.peekFirst(); } @Override default E pop() { return this.removeFirst(); } @Override default void push(E e) { this.addFirst(e); } // Delegate queue methods to deque methods @Override default E element() { return this.getFirst(); } @Override default boolean offer(E e) { return this.offerLast(e); } @Override default E poll() { return this.pollFirst(); } @Override default E remove() { return this.removeFirst(); } }
2,751
24.962264
129
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/FastConcurrentDirectDeque.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014 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. */ /* * Written by Doug Lea and Martin Buchholz with assistance from members of * JCP JSR-166 Expert Group and released to the public domain, as explained * at http://creativecommons.org/publicdomain/zero/1.0/ */ package org.wildfly.clustering.ee.cache.scheduler; import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException; import java.io.Serializable; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import java.util.function.Predicate; /** * A modified version of ConcurrentLinkedDeque which includes direct * removal. Like the original, it relies on {@link VarHandle} for better performance. * * More specifically, an unbounded concurrent {@linkplain Deque deque} based on linked nodes. * Concurrent insertion, removal, and access operations execute safely * across multiple threads. * A {@code ConcurrentLinkedDeque} is an appropriate choice when * many threads will share access to a common collection. * Like most other concurrent collection implementations, this class * does not permit the use of {@code null} elements. * * <p>Iterators and spliterators are * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. * * <p>Beware that, unlike in most collections, the {@code size} method * is <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these deques, determining the current number * of elements requires a traversal of the elements, and so may report * inaccurate results if this collection is modified during traversal. * * <p>Bulk operations that add, remove, or examine multiple elements, * such as {@link #addAll}, {@link #removeIf} or {@link #forEach}, * are <em>not</em> guaranteed to be performed atomically. * For example, a {@code forEach} traversal concurrent with an {@code * addAll} operation might observe only some of the added elements. * * <p>This class and its iterator implement all of the <em>optional</em> * methods of the {@link Deque} and {@link Iterator} interfaces. * * <p>Memory consistency effects: As with other concurrent collections, * actions in a thread prior to placing an object into a * {@code ConcurrentLinkedDeque} * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> * actions subsequent to the access or removal of that element from * the {@code ConcurrentLinkedDeque} in another thread. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * Based on revision 1.88 of ConcurrentLinkedDeque * (see http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ConcurrentLinkedDeque.java?revision=1.88&amp;view=markup) * This is the version used in JDK 9 b156. * * @since 1.7 * @author Doug Lea * @author Martin Buchholz * @author Jason T. Grene * @param <E> the type of elements held in this deque */ @SuppressWarnings("unqualified-field-access") public class FastConcurrentDirectDeque<E> extends AbstractCollection<E> implements ConcurrentDirectDeque<E>, Serializable { /* * This is an implementation of a concurrent lock-free deque * supporting interior removes but not interior insertions, as * required to support the entire Deque interface. * * We extend the techniques developed for ConcurrentLinkedQueue and * LinkedTransferQueue (see the internal docs for those classes). * Understanding the ConcurrentLinkedQueue implementation is a * prerequisite for understanding the implementation of this class. * * The data structure is a symmetrical doubly-linked "GC-robust" * linked list of nodes. We minimize the number of volatile writes * using two techniques: advancing multiple hops with a single CAS * and mixing volatile and non-volatile writes of the same memory * locations. * * A node contains the expected E ("item") and links to predecessor * ("prev") and successor ("next") nodes: * * class Node<E> { volatile Node<E> prev, next; volatile E item; } * * A node p is considered "live" if it contains a non-null item * (p.item != null). When an item is CASed to null, the item is * atomically logically deleted from the collection. * * At any time, there is precisely one "first" node with a null * prev reference that terminates any chain of prev references * starting at a live node. Similarly there is precisely one * "last" node terminating any chain of next references starting at * a live node. The "first" and "last" nodes may or may not be live. * The "first" and "last" nodes are always mutually reachable. * * A new element is added atomically by CASing the null prev or * next reference in the first or last node to a fresh node * containing the element. The element's node atomically becomes * "live" at that point. * * A node is considered "active" if it is a live node, or the * first or last node. Active nodes cannot be unlinked. * * A "self-link" is a next or prev reference that is the same node: * p.prev == p or p.next == p * Self-links are used in the node unlinking process. Active nodes * never have self-links. * * A node p is active if and only if: * * p.item != null || * (p.prev == null && p.next != p) || * (p.next == null && p.prev != p) * * The deque object has two node references, "head" and "tail". * The head and tail are only approximations to the first and last * nodes of the deque. The first node can always be found by * following prev pointers from head; likewise for tail. However, * it is permissible for head and tail to be referring to deleted * nodes that have been unlinked and so may not be reachable from * any live node. * * There are 3 stages of node deletion; * "logical deletion", "unlinking", and "gc-unlinking". * * 1. "logical deletion" by CASing item to null atomically removes * the element from the collection, and makes the containing node * eligible for unlinking. * * 2. "unlinking" makes a deleted node unreachable from active * nodes, and thus eventually reclaimable by GC. Unlinked nodes * may remain reachable indefinitely from an iterator. * * Physical node unlinking is merely an optimization (albeit a * critical one), and so can be performed at our convenience. At * any time, the set of live nodes maintained by prev and next * links are identical, that is, the live nodes found via next * links from the first node is equal to the elements found via * prev links from the last node. However, this is not true for * nodes that have already been logically deleted - such nodes may * be reachable in one direction only. * * 3. "gc-unlinking" takes unlinking further by making active * nodes unreachable from deleted nodes, making it easier for the * GC to reclaim future deleted nodes. This step makes the data * structure "gc-robust", as first described in detail by Boehm * (http://portal.acm.org/citation.cfm?doid=503272.503282). * * GC-unlinked nodes may remain reachable indefinitely from an * iterator, but unlike unlinked nodes, are never reachable from * head or tail. * * Making the data structure GC-robust will eliminate the risk of * unbounded memory retention with conservative GCs and is likely * to improve performance with generational GCs. * * When a node is dequeued at either end, e.g. via poll(), we would * like to break any references from the node to active nodes. We * develop further the use of self-links that was very effective in * other concurrent collection classes. The idea is to replace * prev and next pointers with special values that are interpreted * to mean off-the-list-at-one-end. These are approximations, but * good enough to preserve the properties we want in our * traversals, e.g. we guarantee that a traversal will never visit * the same element twice, but we don't guarantee whether a * traversal that runs out of elements will be able to see more * elements later after enqueues at that end. Doing gc-unlinking * safely is particularly tricky, since any node can be in use * indefinitely (for example by an iterator). We must ensure that * the nodes pointed at by head/tail never get gc-unlinked, since * head/tail are needed to get "back on track" by other nodes that * are gc-unlinked. gc-unlinking accounts for much of the * implementation complexity. * * Since neither unlinking nor gc-unlinking are necessary for * correctness, there are many implementation choices regarding * frequency (eagerness) of these operations. Since volatile * reads are likely to be much cheaper than CASes, saving CASes by * unlinking multiple adjacent nodes at a time may be a win. * gc-unlinking can be performed rarely and still be effective, * since it is most important that long chains of deleted nodes * are occasionally broken. * * The actual representation we use is that p.next == p means to * goto the first node (which in turn is reached by following prev * pointers from head), and p.next == null && p.prev == p means * that the iteration is at an end and that p is a (static final) * dummy node, NEXT_TERMINATOR, and not the last active node. * Finishing the iteration when encountering such a TERMINATOR is * good enough for read-only traversals, so such traversals can use * p.next == null as the termination condition. When we need to * find the last (active) node, for enqueueing a new node, we need * to check whether we have reached a TERMINATOR node; if so, * restart traversal from tail. * * The implementation is completely directionally symmetrical, * except that most public methods that iterate through the list * follow next pointers ("forward" direction). * * We believe (without full proof) that all single-element deque * operations (e.g., addFirst, peekLast, pollLast) are linearizable * (see Herlihy and Shavit's book). However, some combinations of * operations are known not to be linearizable. In particular, * when an addFirst(A) is racing with pollFirst() removing B, it is * possible for an observer iterating over the elements to observe * A B C and subsequently observe A C, even though no interior * removes are ever performed. Nevertheless, iterators behave * reasonably, providing the "weakly consistent" guarantees. * * Empirically, microbenchmarks suggest that this class adds about * 40% overhead relative to ConcurrentLinkedQueue, which feels as * good as we can hope for. */ private static final long serialVersionUID = 876323262645176354L; /** * A node from which the first node on list (that is, the unique node p * with p.prev == null && p.next != p) can be reached in O(1) time. * Invariants: * - the first node is always O(1) reachable from head via prev links * - all live nodes are reachable from the first node via succ() * - head != null * - (tmp = head).next != tmp || tmp != head * - head is never gc-unlinked (but may be unlinked) * Non-invariants: * - head.item may or may not be null * - head may not be reachable from the first or last node, or from tail */ private transient volatile Node<E> head; /** * A node from which the last node on list (that is, the unique node p * with p.next == null && p.prev != p) can be reached in O(1) time. * Invariants: * - the last node is always O(1) reachable from tail via next links * - all live nodes are reachable from the last node via pred() * - tail != null * - tail is never gc-unlinked (but may be unlinked) * Non-invariants: * - tail.item may or may not be null * - tail may not be reachable from the first or last node, or from head */ private transient volatile Node<E> tail; private static final Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR; @SuppressWarnings("unchecked") Node<E> prevTerminator() { return (Node<E>) PREV_TERMINATOR; } @SuppressWarnings("unchecked") Node<E> nextTerminator() { return (Node<E>) NEXT_TERMINATOR; } static final class Node<E> { volatile Node<E> prev; volatile E item; volatile Node<E> next; } /** * Returns a new node holding item. Uses relaxed write because item * can only be seen after piggy-backing publication via CAS. */ static <E> Node<E> newNode(E item) { Node<E> node = new Node<>(); ITEM.set(node, item); return node; } /** * Links e as first element. */ private Node<E> linkFirst(E e) { final Node<E> newNode = newNode(Objects.requireNonNull(e)); restartFromHead: for (;;) for (Node<E> h = head, p = h, q;;) { if ((q = p.prev) != null && (q = (p = q).prev) != null) // Check for head updates every other hop. // If p == q, we are sure to follow head instead. p = (h != (h = head)) ? h : q; else if (p.next == p) // PREV_TERMINATOR continue restartFromHead; else { // p is first node NEXT.set(newNode, p); // CAS piggyback if (PREV.compareAndSet(p, null, newNode)) { // Successful CAS is the linearization point // for e to become an element of this deque, // and for newNode to become "live". if (p != h) // hop two nodes at a time; failure is OK HEAD.weakCompareAndSet(this, h, newNode); return newNode; } // Lost CAS race to another thread; re-read prev } } } /** * Links e as last element. */ private Node<E> linkLast(E e) { final Node<E> newNode = newNode(Objects.requireNonNull(e)); restartFromTail: for (;;) for (Node<E> t = tail, p = t, q;;) { if ((q = p.next) != null && (q = (p = q).next) != null) // Check for tail updates every other hop. // If p == q, we are sure to follow tail instead. p = (t != (t = tail)) ? t : q; else if (p.prev == p) // NEXT_TERMINATOR continue restartFromTail; else { // p is last node PREV.set(newNode, p); // CAS piggyback if (NEXT.compareAndSet(p, null, newNode)) { // Successful CAS is the linearization point // for e to become an element of this deque, // and for newNode to become "live". if (p != t) // hop two nodes at a time; failure is OK TAIL.weakCompareAndSet(this, t, newNode); return newNode; } // Lost CAS race to another thread; re-read next } } } private static final int HOPS = 2; /** * Unlinks non-null node x. */ void unlink(Node<E> x) { // assert x != null; // assert x.item == null; // assert x != PREV_TERMINATOR; // assert x != NEXT_TERMINATOR; final Node<E> prev = x.prev; final Node<E> next = x.next; if (prev == null) { unlinkFirst(x, next); } else if (next == null) { unlinkLast(x, prev); } else { // Unlink interior node. // // This is the common case, since a series of polls at the // same end will be "interior" removes, except perhaps for // the first one, since end nodes cannot be unlinked. // // At any time, all active nodes are mutually reachable by // following a sequence of either next or prev pointers. // // Our strategy is to find the unique active predecessor // and successor of x. Try to fix up their links so that // they point to each other, leaving x unreachable from // active nodes. If successful, and if x has no live // predecessor/successor, we additionally try to gc-unlink, // leaving active nodes unreachable from x, by rechecking // that the status of predecessor and successor are // unchanged and ensuring that x is not reachable from // tail/head, before setting x's prev/next links to their // logical approximate replacements, self/TERMINATOR. Node<E> activePred, activeSucc; boolean isFirst, isLast; int hops = 1; // Find active predecessor for (Node<E> p = prev; ; ++hops) { if (p.item != null) { activePred = p; isFirst = false; break; } Node<E> q = p.prev; if (q == null) { if (p.next == p) return; activePred = p; isFirst = true; break; } else if (p == q) return; else p = q; } // Find active successor for (Node<E> p = next; ; ++hops) { if (p.item != null) { activeSucc = p; isLast = false; break; } Node<E> q = p.next; if (q == null) { if (p.prev == p) return; activeSucc = p; isLast = true; break; } else if (p == q) return; else p = q; } // TODO: better HOP heuristics if (hops < HOPS // always squeeze out interior deleted nodes && (isFirst | isLast)) return; // Squeeze out deleted nodes between activePred and // activeSucc, including x. skipDeletedSuccessors(activePred); skipDeletedPredecessors(activeSucc); // Try to gc-unlink, if possible if ((isFirst | isLast) && // Recheck expected state of predecessor and successor (activePred.next == activeSucc) && (activeSucc.prev == activePred) && (isFirst ? activePred.prev == null : activePred.item != null) && (isLast ? activeSucc.next == null : activeSucc.item != null)) { updateHead(); // Ensure x is not reachable from head updateTail(); // Ensure x is not reachable from tail // Finally, actually gc-unlink PREV.setRelease(x, isFirst ? prevTerminator() : x); NEXT.setRelease(x, isLast ? nextTerminator() : x); } } } /** * Unlinks non-null first node. */ private void unlinkFirst(Node<E> first, Node<E> next) { // assert first != null; // assert next != null; // assert first.item == null; for (Node<E> o = null, p = next, q;;) { if (p.item != null || (q = p.next) == null) { if (o != null && p.prev != p && NEXT.compareAndSet(first, next, p)) { skipDeletedPredecessors(p); if (first.prev == null && (p.next == null || p.item != null) && p.prev == first) { updateHead(); // Ensure o is not reachable from head updateTail(); // Ensure o is not reachable from tail // Finally, actually gc-unlink NEXT.setRelease(o, o); PREV.setRelease(o, prevTerminator()); } } return; } else if (p == q) return; else { o = p; p = q; } } } /** * Unlinks non-null last node. */ private void unlinkLast(Node<E> last, Node<E> prev) { // assert last != null; // assert prev != null; // assert last.item == null; for (Node<E> o = null, p = prev, q;;) { if (p.item != null || (q = p.prev) == null) { if (o != null && p.next != p && PREV.compareAndSet(last, prev, p)) { skipDeletedSuccessors(p); if (last.next == null && (p.prev == null || p.item != null) && p.next == last) { updateHead(); // Ensure o is not reachable from head updateTail(); // Ensure o is not reachable from tail // Finally, actually gc-unlink PREV.setRelease(o, o); NEXT.setRelease(o, nextTerminator()); } } return; } else if (p == q) return; else { o = p; p = q; } } } /** * Guarantees that any node which was unlinked before a call to * this method will be unreachable from head after it returns. * Does not guarantee to eliminate slack, only that head will * point to a node that was active while this method was running. */ private void updateHead() { // Either head already points to an active node, or we keep // trying to cas it to the first node until it does. Node<E> h, p, q; restartFromHead: while ((h = head).item == null && (p = h.prev) != null) { for (;;) { if ((q = p.prev) == null || (q = (p = q).prev) == null) { // It is possible that p is PREV_TERMINATOR, // but if so, the CAS is guaranteed to fail. if (HEAD.compareAndSet(this, h, p)) return; continue restartFromHead; } else if (h != head) continue restartFromHead; else p = q; } } } /** * Guarantees that any node which was unlinked before a call to * this method will be unreachable from tail after it returns. * Does not guarantee to eliminate slack, only that tail will * point to a node that was active while this method was running. */ private void updateTail() { // Either tail already points to an active node, or we keep // trying to cas it to the last node until it does. Node<E> t, p, q; restartFromTail: while ((t = tail).item == null && (p = t.next) != null) { for (;;) { if ((q = p.next) == null || (q = (p = q).next) == null) { // It is possible that p is NEXT_TERMINATOR, // but if so, the CAS is guaranteed to fail. if (TAIL.compareAndSet(this, t, p)) return; continue restartFromTail; } else if (t != tail) continue restartFromTail; else p = q; } } } private void skipDeletedPredecessors(Node<E> x) { whileActive: do { Node<E> prev = x.prev; // assert prev != null; // assert x != NEXT_TERMINATOR; // assert x != PREV_TERMINATOR; Node<E> p = prev; findActive: for (;;) { if (p.item != null) break findActive; Node<E> q = p.prev; if (q == null) { if (p.next == p) continue whileActive; break findActive; } else if (p == q) continue whileActive; else p = q; } // found active CAS target if (prev == p || PREV.compareAndSet(x, prev, p)) return; } while (x.item != null || x.next == null); } private void skipDeletedSuccessors(Node<E> x) { whileActive: do { Node<E> next = x.next; // assert next != null; // assert x != NEXT_TERMINATOR; // assert x != PREV_TERMINATOR; Node<E> p = next; findActive: for (;;) { if (p.item != null) break findActive; Node<E> q = p.next; if (q == null) { if (p.prev == p) continue whileActive; break findActive; } else if (p == q) continue whileActive; else p = q; } // found active CAS target if (next == p || NEXT.compareAndSet(x, next, p)) return; } while (x.item != null || x.prev == null); } /** * Returns the successor of p, or the first node if p.next has been * linked to self, which will only be true if traversing with a * stale pointer that is now off the list. */ final Node<E> succ(Node<E> p) { // TODO: should we skip deleted nodes here? Node<E> q = p.next; return (p == q) ? first() : q; } /** * Returns the predecessor of p, or the last node if p.prev has been * linked to self, which will only be true if traversing with a * stale pointer that is now off the list. */ final Node<E> pred(Node<E> p) { Node<E> q = p.prev; return (p == q) ? last() : q; } /** * Returns the first node, the unique node p for which: * p.prev == null && p.next != p * The returned node may or may not be logically deleted. * Guarantees that head is set to the returned node. */ Node<E> first() { restartFromHead: for (;;) for (Node<E> h = head, p = h, q;;) { if ((q = p.prev) != null && (q = (p = q).prev) != null) // Check for head updates every other hop. // If p == q, we are sure to follow head instead. p = (h != (h = head)) ? h : q; else if (p == h // It is possible that p is PREV_TERMINATOR, // but if so, the CAS is guaranteed to fail. || HEAD.compareAndSet(this, h, p)) return p; else continue restartFromHead; } } /** * Returns the last node, the unique node p for which: * p.next == null && p.prev != p * The returned node may or may not be logically deleted. * Guarantees that tail is set to the returned node. */ Node<E> last() { restartFromTail: for (;;) for (Node<E> t = tail, p = t, q;;) { if ((q = p.next) != null && (q = (p = q).next) != null) // Check for tail updates every other hop. // If p == q, we are sure to follow tail instead. p = (t != (t = tail)) ? t : q; else if (p == t // It is possible that p is NEXT_TERMINATOR, // but if so, the CAS is guaranteed to fail. || TAIL.compareAndSet(this, t, p)) return p; else continue restartFromTail; } } // Minor convenience utilities /** * Returns element unless it is null, in which case throws * NoSuchElementException. * * @param v the element * @return the element */ private E screenNullResult(E v) { if (v == null) throw new NoSuchElementException(); return v; } /** * Constructs an empty deque. */ public FastConcurrentDirectDeque() { head = tail = new Node<>(); } /** * Constructs a deque initially containing the elements of * the given collection, added in traversal order of the * collection's iterator. * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public FastConcurrentDirectDeque(Collection<? extends E> c) { // Copy c into a private chain of Nodes Node<E> h = null, t = null; for (E e : c) { Node<E> newNode = newNode(Objects.requireNonNull(e)); if (h == null) h = t = newNode; else { NEXT.set(t, newNode); PREV.set(newNode, t); t = newNode; } } initHeadTail(h, t); } /** * Initializes head and tail, ensuring invariants hold. */ private void initHeadTail(Node<E> h, Node<E> t) { if (h == t) { if (h == null) h = t = new Node<>(); else { // Avoid edge case of a single Node with non-null item. Node<E> newNode = new Node<>(); NEXT.set(t, newNode); PREV.set(newNode, t); t = newNode; } } head = h; tail = t; } /** * Inserts the specified element at the front of this deque. * As the deque is unbounded, this method will never throw * {@link IllegalStateException}. * * @throws NullPointerException if the specified element is null */ @Override public void addFirst(E e) { linkFirst(e); } /** * Inserts the specified element at the end of this deque. * As the deque is unbounded, this method will never throw * {@link IllegalStateException}. * * <p>This method is equivalent to {@link #add}. * * @throws NullPointerException if the specified element is null */ @Override public void addLast(E e) { linkLast(e); } /** * Inserts the specified element at the front of this deque. * As the deque is unbounded, this method will never return {@code false}. * * @return {@code true} (as specified by {@link Deque#offerFirst}) * @throws NullPointerException if the specified element is null */ @Override public boolean offerFirst(E e) { linkFirst(e); return true; } @Override public Object offerFirstAndReturnToken(E e) { return linkFirst(e); } @Override public Object offerLastAndReturnToken(E e) { return linkLast(e); } @Override public void removeToken(Object token) { if (!(token instanceof Node)) { throw new IllegalArgumentException(); } @SuppressWarnings("unchecked") Node<E> node = (Node<E>) (token); while (! ITEM.compareAndSet(node, node.item, null)) {} unlink(node); } /** * Inserts the specified element at the end of this deque. * As the deque is unbounded, this method will never return {@code false}. * * <p>This method is equivalent to {@link #add}. * * @return {@code true} (as specified by {@link Deque#offerLast}) * @throws NullPointerException if the specified element is null */ @Override public boolean offerLast(E e) { linkLast(e); return true; } @Override public E peekFirst() { for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null) return item; } return null; } @Override public E peekLast() { for (Node<E> p = last(); p != null; p = pred(p)) { E item = p.item; if (item != null) return item; } return null; } /** * @throws NoSuchElementException {@inheritDoc} */ @Override public E getFirst() { return screenNullResult(peekFirst()); } /** * @throws NoSuchElementException {@inheritDoc} */ @Override public E getLast() { return screenNullResult(peekLast()); } @Override public E pollFirst() { for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null && ITEM.compareAndSet(p, item, null)) { unlink(p); return item; } } return null; } @Override public E pollLast() { for (Node<E> p = last(); p != null; p = pred(p)) { E item = p.item; if (item != null && ITEM.compareAndSet(p, item, null)) { unlink(p); return item; } } return null; } /** * @throws NoSuchElementException {@inheritDoc} */ @Override public E removeFirst() { return screenNullResult(pollFirst()); } /** * @throws NoSuchElementException {@inheritDoc} */ @Override public E removeLast() { return screenNullResult(pollLast()); } /** * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element {@code e} such that * {@code o.equals(e)} (if such an element exists). * Returns {@code true} if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return {@code true} if the deque contained the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean removeFirstOccurrence(Object o) { Objects.requireNonNull(o); for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null && o.equals(item) && ITEM.compareAndSet(p, item, null)) { unlink(p); return true; } } return false; } /** * Removes the last occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the last element {@code e} such that * {@code o.equals(e)} (if such an element exists). * Returns {@code true} if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * @param o element to be removed from this deque, if present * @return {@code true} if the deque contained the specified element * @throws NullPointerException if the specified element is null */ @Override public boolean removeLastOccurrence(Object o) { Objects.requireNonNull(o); for (Node<E> p = last(); p != null; p = pred(p)) { E item = p.item; if (item != null && o.equals(item) && ITEM.compareAndSet(p, item, null)) { unlink(p); return true; } } return false; } /** * Returns {@code true} if this deque contains the specified element. * More formally, returns {@code true} if and only if this deque contains * at least one element {@code e} such that {@code o.equals(e)}. * * @param o element whose presence in this deque is to be tested * @return {@code true} if this deque contains the specified element */ @Override public boolean contains(Object o) { if (o != null) { for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null && o.equals(item)) return true; } } return false; } /** * Returns {@code true} if this collection contains no elements. * * @return {@code true} if this collection contains no elements */ @Override public boolean isEmpty() { return peekFirst() == null; } /** * Returns the number of elements in this deque. If this deque * contains more than {@code Integer.MAX_VALUE} elements, it * returns {@code Integer.MAX_VALUE}. * * <p>Beware that, unlike in most collections, this method is * <em>NOT</em> a constant-time operation. Because of the * asynchronous nature of these deques, determining the current * number of elements requires traversing them all to count them. * Additionally, it is possible for the size to change during * execution of this method, in which case the returned result * will be inaccurate. Thus, this method is typically not very * useful in concurrent applications. * * @return the number of elements in this deque */ @Override public int size() { restartFromHead: for (;;) { int count = 0; for (Node<E> p = first(); p != null;) { if (p.item != null) if (++count == Integer.MAX_VALUE) break; // @see Collection.size() if (p == (p = p.next)) continue restartFromHead; } return count; } } /** * Appends all of the elements in the specified collection to the end of * this deque, in the order that they are returned by the specified * collection's iterator. Attempts to {@code addAll} of a deque to * itself result in {@code IllegalArgumentException}. * * @param c the elements to be inserted into this deque * @return {@code true} if this deque changed as a result of the call * @throws NullPointerException if the specified collection or any * of its elements are null * @throws IllegalArgumentException if the collection is this deque */ @Override public boolean addAll(Collection<? extends E> c) { if (c == this) // As historically specified in AbstractQueue#addAll throw new IllegalArgumentException(); // Copy c into a private chain of Nodes Node<E> beginningOfTheEnd = null, last = null; for (E e : c) { Node<E> newNode = newNode(Objects.requireNonNull(e)); if (beginningOfTheEnd == null) beginningOfTheEnd = last = newNode; else { NEXT.set(last, newNode); PREV.set(newNode, last); last = newNode; } } if (beginningOfTheEnd == null) return false; // Atomically append the chain at the tail of this collection restartFromTail: for (;;) for (Node<E> t = tail, p = t, q;;) { if ((q = p.next) != null && (q = (p = q).next) != null) // Check for tail updates every other hop. // If p == q, we are sure to follow tail instead. p = (t != (t = tail)) ? t : q; else if (p.prev == p) // NEXT_TERMINATOR continue restartFromTail; else { // p is last node PREV.set(beginningOfTheEnd, p); // CAS piggyback if (NEXT.compareAndSet(p, null, beginningOfTheEnd)) { // Successful CAS is the linearization point // for all elements to be added to this deque. if (!TAIL.weakCompareAndSet(this, t, last)) { // Try a little harder to update tail, // since we may be adding many elements. t = tail; if (last.next == null) TAIL.weakCompareAndSet(this, t, last); } return true; } // Lost CAS race to another thread; re-read next } } } /** * Removes all of the elements from this deque. */ @Override public void clear() { while (pollFirst() != null) {} } @Override public String toString() { String[] a = null; restartFromHead: for (;;) { int charLength = 0; int size = 0; for (Node<E> p = first(); p != null;) { E item = p.item; if (item != null) { if (a == null) a = new String[4]; else if (size == a.length) a = Arrays.copyOf(a, 2 * size); String s = item.toString(); a[size++] = s; charLength += s.length(); } if (p == (p = p.next)) continue restartFromHead; } if (size == 0) return "[]"; return toString(a, size, charLength); } } private Object[] toArrayInternal(Object[] a) { Object[] x = a; restartFromHead: for (;;) { int size = 0; for (Node<E> p = first(); p != null;) { E item = p.item; if (item != null) { if (x == null) x = new Object[4]; else if (size == x.length) x = Arrays.copyOf(x, 2 * (size + 4)); x[size++] = item; } if (p == (p = p.next)) continue restartFromHead; } if (x == null) return new Object[0]; else if (a != null && size <= a.length) { if (a != x) System.arraycopy(x, 0, a, 0, size); if (size < a.length) a[size] = null; return a; } return (size == x.length) ? x : Arrays.copyOf(x, size); } } /** * Returns an array containing all of the elements in this deque, in * proper sequence (from first to last element). * * <p>The returned array will be "safe" in that no references to it are * maintained by this deque. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this deque */ @Override public Object[] toArray() { return toArrayInternal(null); } /** * Returns an array containing all of the elements in this deque, * in proper sequence (from first to last element); the runtime * type of the returned array is that of the specified array. If * the deque fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of * the specified array and the size of this deque. * * <p>If this deque fits in the specified array with room to spare * (i.e., the array has more elements than this deque), the element in * the array immediately following the end of the deque is set to * {@code null}. * * <p>Like the {@link #toArray()} method, this method acts as * bridge between array-based and collection-based APIs. Further, * this method allows precise control over the runtime type of the * output array, and may, under certain circumstances, be used to * save allocation costs. * * <p>Suppose {@code x} is a deque known to contain only strings. * The following code can be used to dump the deque into a newly * allocated array of {@code String}: * * <pre> {@code String[] y = x.toArray(new String[0]);}</pre> * * Note that {@code toArray(new Object[0])} is identical in function to * {@code toArray()}. * * @param a the array into which the elements of the deque are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this deque * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this deque * @throws NullPointerException if the specified array is null */ @Override @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { checkNotNullParamWithNullPointerException("a", a); return (T[]) toArrayInternal(a); } /** * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). * * <p>The returned iterator is * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. * * @return an iterator over the elements in this deque in proper sequence */ @Override public Iterator<E> iterator() { return new Itr(); } /** * Returns an iterator over the elements in this deque in reverse * sequential order. The elements will be returned in order from * last (tail) to first (head). * * <p>The returned iterator is * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. * * @return an iterator over the elements in this deque in reverse order */ @Override public Iterator<E> descendingIterator() { return new DescendingItr(); } // From Helpers 1.2 // http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/Helpers.java?revision=1.2 /** * Like Arrays.toString(), but caller guarantees that size > 0, * each element with index 0 <= i < size is a non-null String, * and charLength is the sum of the lengths of the input Strings. */ private static String toString(Object[] a, int size, int charLength) { // assert a != null; // assert size > 0; // Copy each string into a perfectly sized char[] // Length of [ , , , ] == 2 * size final char[] chars = new char[charLength + 2 * size]; chars[0] = '['; int j = 1; for (int i = 0; i < size; i++) { if (i > 0) { chars[j++] = ','; chars[j++] = ' '; } String s = (String) a[i]; int len = s.length(); s.getChars(0, len, chars, j); j += len; } chars[j] = ']'; // assert j == chars.length - 1; return new String(chars); } private abstract class AbstractItr implements Iterator<E> { /** * Next node to return item for. */ private Node<E> nextNode; /** * nextItem holds on to item fields because once we claim * that an element exists in hasNext(), we must return it in * the following next() call even if it was in the process of * being removed when hasNext() was called. */ private E nextItem; /** * Node returned by most recent call to next. Needed by remove. * Reset to null if this element is deleted by a call to remove. */ private Node<E> lastRet; abstract Node<E> startNode(); abstract Node<E> nextNode(Node<E> p); AbstractItr() { advance(); } /** * Sets nextNode and nextItem to next valid node, or to null * if no such. */ private void advance() { lastRet = nextNode; Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode); for (;; p = nextNode(p)) { if (p == null) { // might be at active end or TERMINATOR node; both are OK nextNode = null; nextItem = null; break; } E item = p.item; if (item != null) { nextNode = p; nextItem = item; break; } } } @Override public boolean hasNext() { return nextItem != null; } @Override public E next() { E item = nextItem; if (item == null) throw new NoSuchElementException(); advance(); return item; } @Override public void remove() { Node<E> l = lastRet; if (l == null) throw new IllegalStateException(); l.item = null; unlink(l); lastRet = null; } } /** * Forward iterator */ private class Itr extends AbstractItr { Itr() {} @Override Node<E> startNode() { return first(); } @Override Node<E> nextNode(Node<E> p) { return succ( p ); } } /** * Descending iterator */ private class DescendingItr extends AbstractItr { DescendingItr() {} @Override Node<E> startNode() { return last(); } @Override Node<E> nextNode(Node<E> p) { return pred( p ); } } /** A customized variant of Spliterators.IteratorSpliterator */ final class CLDSpliterator implements Spliterator<E> { static final int MAX_BATCH = 1 << 25; // max batch array size; Node<E> current; // current node; null until initialized int batch; // batch size for splits boolean exhausted; // true when no more nodes @Override public Spliterator<E> trySplit() { Node<E> p, q; if ((p = current()) == null || (q = p.next) == null) return null; int i = 0, n = batch = Math.min(batch + 1, MAX_BATCH); Object[] a = null; do { final E e; if ((e = p.item) != null) { if (a == null) a = new Object[n]; a[i++] = e; } if (p == (p = q)) p = first(); } while (p != null && (q = p.next) != null && i < n); setCurrent(p); return (i == 0) ? null : Spliterators.spliterator(a, 0, i, (Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.CONCURRENT)); } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); Node<E> p; if ((p = current()) != null) { current = null; exhausted = true; do { E e = p.item; if (e != null) action.accept(e); if (p == (p = p.next)) p = first(); } while (p != null); } } @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); Node<E> p; if ((p = current()) != null) { E e; do { e = p.item; if (p == (p = p.next)) p = first(); } while (e == null && p != null); setCurrent(p); if (e != null) { action.accept(e); return true; } } return false; } private void setCurrent(Node<E> p) { if ((current = p) == null) exhausted = true; } private Node<E> current() { Node<E> p; if ((p = current) == null && !exhausted) setCurrent(p = first()); return p; } @Override public long estimateSize() { return Long.MAX_VALUE; } @Override public int characteristics() { return (Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.CONCURRENT); } } /** * Returns a {@link Spliterator} over the elements in this deque. * * <p>The returned spliterator is * <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. * * <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT}, * {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}. * * @implNote * The {@code Spliterator} implements {@code trySplit} to permit limited * parallelism. * * @return a {@code Spliterator} over the elements in this deque * @since 1.8 */ @Override public Spliterator<E> spliterator() { return new CLDSpliterator(); } /** * Saves this deque to a stream (that is, serializes it). * * @param s the stream * @throws java.io.IOException if an I/O error occurs * @serialData All of the elements (each an {@code E}) in * the proper order, followed by a null */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden stuff s.defaultWriteObject(); // Write out all elements in the proper order. for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null) s.writeObject(item); } // Use trailing null as sentinel s.writeObject(null); } /** * Reconstitutes this deque from a stream (that is, deserializes it). * @param s the stream * @throws ClassNotFoundException if the class of a serialized object * could not be found * @throws java.io.IOException if an I/O error occurs */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // Read in elements until trailing null sentinel found Node<E> h = null, t = null; for (Object item; (item = s.readObject()) != null; ) { @SuppressWarnings("unchecked") Node<E> newNode = newNode((E) item); if (h == null) h = t = newNode; else { NEXT.set(t, newNode); PREV.set(newNode, t); t = newNode; } } initHeadTail(h, t); } /** * @throws NullPointerException {@inheritDoc} */ @Override public boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); return bulkRemove(filter); } /** * @throws NullPointerException {@inheritDoc} */ @Override public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return bulkRemove(e -> c.contains(e)); } /** * @throws NullPointerException {@inheritDoc} */ @Override public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return bulkRemove(e -> !c.contains(e)); } /** Implementation of bulk remove methods. */ private boolean bulkRemove(Predicate<? super E> filter) { boolean removed = false; for (Node<E> p = first(), succ; p != null; p = succ) { succ = succ(p); E item = p.item; if (item != null && filter.test(item) && ITEM.compareAndSet(p, item, null)) { unlink(p); removed = true; } } return removed; } /** * @throws NullPointerException {@inheritDoc} */ @Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); for (Node<E> p = first(); p != null; p = succ(p)) { E item = p.item; if (item != null) action.accept(item); } } // VarHandle mechanics private static final VarHandle HEAD; private static final VarHandle TAIL; private static final VarHandle PREV; private static final VarHandle NEXT; private static final VarHandle ITEM; static { PREV_TERMINATOR = new Node<>(); PREV_TERMINATOR.next = PREV_TERMINATOR; NEXT_TERMINATOR = new Node<>(); NEXT_TERMINATOR.prev = NEXT_TERMINATOR; try { MethodHandles.Lookup l = MethodHandles.lookup(); HEAD = l.findVarHandle(FastConcurrentDirectDeque.class, "head", Node.class); TAIL = l.findVarHandle(FastConcurrentDirectDeque.class, "tail", Node.class); PREV = l.findVarHandle(Node.class, "prev", Node.class); NEXT = l.findVarHandle(Node.class, "next", Node.class); ITEM = l.findVarHandle(Node.class, "item", Object.class); } catch (ReflectiveOperationException e) { throw new Error(e); } } }
59,970
34.739571
147
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/concurrent/StampedLockServiceExecutor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.concurrent; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.StampedLock; import java.util.function.Supplier; import org.wildfly.clustering.ee.concurrent.ServiceExecutor; import org.wildfly.common.function.ExceptionRunnable; import org.wildfly.common.function.ExceptionSupplier; /** * {@link ServiceExecutor} implemented via a {@link StampedLock}. * @author Paul Ferraro */ public class StampedLockServiceExecutor implements ServiceExecutor { private final StampedLock lock = new StampedLock(); private final AtomicBoolean closed = new AtomicBoolean(false); @Override public void execute(Runnable executeTask) { long stamp = this.lock.tryReadLock(); if (stamp != 0L) { try { executeTask.run(); } finally { this.lock.unlock(stamp); } } } @Override public <E extends Exception> void execute(ExceptionRunnable<E> executeTask) throws E { long stamp = this.lock.tryReadLock(); if (stamp != 0L) { try { executeTask.run(); } finally { this.lock.unlock(stamp); } } } @Override public <R> Optional<R> execute(Supplier<R> executeTask) { long stamp = this.lock.tryReadLock(); if (stamp != 0L) { try { return Optional.of(executeTask.get()); } finally { this.lock.unlock(stamp); } } return Optional.empty(); } @Override public <R, E extends Exception> Optional<R> execute(ExceptionSupplier<R, E> executeTask) throws E { long stamp = this.lock.tryReadLock(); if (stamp != 0L) { try { return Optional.of(executeTask.get()); } finally { this.lock.unlock(stamp); } } return Optional.empty(); } @Override public void close(Runnable closeTask) { // Allow only one thread to close if (this.closed.compareAndSet(false, true)) { // Closing is final - we don't need the stamp this.lock.writeLock(); closeTask.run(); } } }
3,349
31.524272
103
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/retry/RetryingInvoker.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.retry; import java.time.Duration; import java.util.Arrays; import java.util.List; import org.jboss.logging.Logger; import org.wildfly.clustering.ee.Invoker; import org.wildfly.common.function.ExceptionRunnable; import org.wildfly.common.function.ExceptionSupplier; /** * A invocation strategy that invokes a given task, retrying a configurable number of times on failure using backoff sleep intervals. * @author Paul Ferraro */ public class RetryingInvoker implements Invoker { // No logger interface for this module and no reason to create one for this class only private static final Logger LOGGER = Logger.getLogger(RetryingInvoker.class); private final List<Duration> retryIntevals; public RetryingInvoker(Duration... retryIntervals) { this(Arrays.asList(retryIntervals)); } protected RetryingInvoker(List<Duration> retryIntevals) { this.retryIntevals = retryIntevals; } @Override public <R, E extends Exception> R invoke(ExceptionSupplier<R, E> task) throws E { int attempt = 0; for (Duration delay : this.retryIntevals) { if (Thread.currentThread().isInterrupted()) break; try { return task.get(); } catch (Exception e) { LOGGER.debugf(e, "Attempt #%d failed", ++attempt); } if (delay.isZero() || delay.isNegative()) { Thread.yield(); } else { try { Thread.sleep(delay.toMillis(), delay.getNano() % 1_000_000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } return task.get(); } @Override public <E extends Exception> void invoke(ExceptionRunnable<E> action) throws E { ExceptionSupplier<Void, E> adapter = new ExceptionSupplier<>() { @Override public Void get() throws E { action.run(); return null; } }; this.invoke(adapter); } }
3,155
35.275862
133
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/tx/TransactionalBatcher.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.tx; import java.util.function.Function; import jakarta.transaction.InvalidTransactionException; import jakarta.transaction.NotSupportedException; import jakarta.transaction.RollbackException; import jakarta.transaction.Synchronization; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import org.wildfly.clustering.ee.Batch; import org.wildfly.clustering.ee.BatchContext; import org.wildfly.clustering.ee.Batcher; /** * A {@link Batcher} implementation based on Infinispan's {@link org.infinispan.batch.BatchContainer}, except that its transaction reference * is stored within the returned Batch object instead of a ThreadLocal. This also allows the user to call {@link Batch#close()} from a * different thread than the one that created the {@link Batch}. In this case, however, the user must first resume the batch * via {@link #resumeBatch(TransactionBatch)}. * @author Paul Ferraro */ public class TransactionalBatcher<E extends RuntimeException> implements Batcher<TransactionBatch> { private static final BatchContext PASSIVE_BATCH_CONTEXT = () -> { // Do nothing }; private static final TransactionBatch NON_TX_BATCH = new TransactionBatch() { @Override public void close() { // No-op } @Override public void discard() { // No-op } @Override public State getState() { // A non-tx batch is always active return State.ACTIVE; } @Override public Transaction getTransaction() { return null; } @Override public TransactionBatch interpose() { return this; } }; // Used to coalesce interposed transactions private static final ThreadLocal<TransactionBatch> CURRENT_BATCH = new ThreadLocal<>(); static TransactionBatch getCurrentBatch() { return CURRENT_BATCH.get(); } static void setCurrentBatch(TransactionBatch batch) { if (batch != null) { CURRENT_BATCH.set(batch); } else { CURRENT_BATCH.remove(); } } private static final Synchronization CURRENT_BATCH_SYNCHRONIZATION = new Synchronization() { @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { setCurrentBatch(null); } }; private final TransactionManager tm; private final Function<Throwable, E> exceptionTransformer; public TransactionalBatcher(TransactionManager tm, Function<Throwable, E> exceptionTransformer) { this.tm = tm; this.exceptionTransformer = exceptionTransformer; } @Override public TransactionBatch createBatch() { if (this.tm == null) return NON_TX_BATCH; TransactionBatch batch = getCurrentBatch(); try { if ((batch != null) && (batch.getState() == Batch.State.ACTIVE)) { return batch.interpose(); } this.tm.suspend(); this.tm.begin(); Transaction tx = this.tm.getTransaction(); tx.registerSynchronization(CURRENT_BATCH_SYNCHRONIZATION); batch = new TransactionalBatch<>(tx, this.exceptionTransformer); setCurrentBatch(batch); return batch; } catch (RollbackException | SystemException | NotSupportedException e) { throw this.exceptionTransformer.apply(e); } } @Override public BatchContext resumeBatch(TransactionBatch batch) { TransactionBatch existingBatch = getCurrentBatch(); // Trivial case - nothing to suspend/resume if (batch == existingBatch) return PASSIVE_BATCH_CONTEXT; Transaction tx = (batch != null) ? batch.getTransaction() : null; // Non-tx case, just swap batch references if ((batch == null) || (tx == null)) { setCurrentBatch(batch); return () -> setCurrentBatch(existingBatch); } try { if (existingBatch != null) { Transaction existingTx = this.tm.suspend(); if (existingBatch.getTransaction() != existingTx) { throw new IllegalStateException(); } } this.tm.resume(tx); setCurrentBatch(batch); return () -> { try { this.tm.suspend(); if (existingBatch != null) { try { this.tm.resume(existingBatch.getTransaction()); } catch (InvalidTransactionException e) { throw this.exceptionTransformer.apply(e); } } } catch (SystemException e) { throw this.exceptionTransformer.apply(e); } finally { setCurrentBatch(existingBatch); } }; } catch (SystemException | InvalidTransactionException e) { throw this.exceptionTransformer.apply(e); } } @Override public TransactionBatch suspendBatch() { if (this.tm == null) return NON_TX_BATCH; TransactionBatch batch = getCurrentBatch(); if (batch != null) { try { Transaction tx = this.tm.suspend(); if (batch.getTransaction() != tx) { throw new IllegalStateException(); } } catch (SystemException e) { throw this.exceptionTransformer.apply(e); } finally { setCurrentBatch(null); } } return batch; } }
6,893
34.720207
140
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/tx/TransactionalBatch.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.tx; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.RollbackException; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; /** * Abstract {@link TransactionBatch} that associates and exposes the underlying transaction. * @author Paul Ferraro */ public class TransactionalBatch<E extends RuntimeException> implements TransactionBatch { private final Function<Throwable, E> exceptionTransformer; private final Transaction tx; private final AtomicInteger count = new AtomicInteger(0); private volatile boolean active = true; public TransactionalBatch(Transaction tx, Function<Throwable, E> exceptionTransformer) { this.tx = tx; this.exceptionTransformer = exceptionTransformer; } @Override public Transaction getTransaction() { return this.tx; } @Override public TransactionBatch interpose() { this.count.incrementAndGet(); return this; } @Override public void discard() { // Allow additional cache operations prior to close, rather than call tx.setRollbackOnly() this.active = false; } @Override public State getState() { try { switch (this.tx.getStatus()) { case Status.STATUS_ACTIVE: { if (this.active) { return State.ACTIVE; } // Otherwise fall through } case Status.STATUS_MARKED_ROLLBACK: { return State.DISCARDED; } default: { return State.CLOSED; } } } catch (SystemException e) { throw this.exceptionTransformer.apply(e); } } @Override public void close() { if (this.count.getAndDecrement() == 0) { try { switch (this.tx.getStatus()) { case Status.STATUS_ACTIVE: { if (this.active) { try { this.tx.commit(); break; } catch (RollbackException e) { throw new IllegalStateException(e); } catch (HeuristicMixedException | HeuristicRollbackException e) { throw this.exceptionTransformer.apply(e); } } // Otherwise fall through } case Status.STATUS_MARKED_ROLLBACK: { this.tx.rollback(); break; } } } catch (SystemException e) { throw this.exceptionTransformer.apply(e); } } } @Override public int hashCode() { return this.tx.hashCode(); } @Override public boolean equals(Object object) { if (!(object instanceof TransactionalBatch)) return false; TransactionalBatch<?> batch = (TransactionalBatch<?>) object; return this.tx.equals(batch.tx); } @Override public String toString() { return String.format("%s[%d]", this.tx, this.count.get()); } }
4,599
33.074074
98
java
null
wildfly-main/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/tx/TransactionBatch.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.cache.tx; import jakarta.transaction.Transaction; import org.wildfly.clustering.ee.Batch; /** * @author Paul Ferraro */ public interface TransactionBatch extends Batch { /** * Returns the transaction associated with this batch * @return a transaction */ Transaction getTransaction(); /** * Returns an interposed batch. */ TransactionBatch interpose(); }
1,459
32.181818
70
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/RemoteCacheConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod; /** * Configuration identifying a remote cache. * @author Paul Ferraro */ public interface RemoteCacheConfiguration { String getContainerName(); String getConfigurationName(); }
1,257
36
70
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/RemoteCacheProperties.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.ee.cache.CacheProperties; /** * @author Paul Ferraro */ public class RemoteCacheProperties implements CacheProperties { private final boolean transactional; public RemoteCacheProperties(RemoteCache<?, ?> cache) { this.transactional = cache.getTransactionManager() != null; } @Override public boolean isLockOnRead() { return false; } @Override public boolean isLockOnWrite() { return false; } @Override public boolean isMarshalling() { return true; } @Override public boolean isPersistent() { return true; } @Override public boolean isTransactional() { return this.transactional; } }
1,859
28.0625
70
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/RemoteCacheMap.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod; import java.util.Map; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.util.CloseableIteratorCollection; import org.infinispan.commons.util.CloseableIteratorSet; /** * Map view of a remote cache that forces return values where necessary. * @author Paul Ferraro */ public class RemoteCacheMap<K, V> implements Map<K, V> { private final RemoteCache<K, V> cache; public RemoteCacheMap(RemoteCache<K, V> cache) { this.cache = cache; } @Override public int size() { return this.cache.size(); } @Override public boolean isEmpty() { return this.cache.isEmpty(); } @Override public boolean containsKey(Object key) { return this.cache.containsKey(key); } @Override public boolean containsValue(Object value) { return this.cache.containsValue(value); } @Override public V get(Object key) { return this.cache.get(key); } @Override public V put(K key, V value) { return this.cache.withFlags(Flag.FORCE_RETURN_VALUE).put(key, value); } @Override public V remove(Object key) { return this.cache.withFlags(Flag.FORCE_RETURN_VALUE).remove(key); } @Override public void putAll(Map<? extends K, ? extends V> map) { this.cache.putAll(map); } @Override public void clear() { this.cache.clear(); } @Override public CloseableIteratorSet<K> keySet() { return this.cache.keySet(); } @Override public CloseableIteratorCollection<V> values() { return this.cache.values(); } @Override public CloseableIteratorSet<Entry<K, V>> entrySet() { return this.cache.entrySet(); } }
2,863
26.805825
77
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/HotRodConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.cache.CacheConfiguration; import org.wildfly.clustering.ee.cache.CacheProperties; import org.wildfly.clustering.ee.cache.tx.TransactionBatch; import org.wildfly.clustering.ee.hotrod.tx.HotRodBatcher; /** * @author Paul Ferraro */ public interface HotRodConfiguration extends CacheConfiguration { @Override <CK, CV> RemoteCache<CK, CV> getCache(); @Override default CacheProperties getCacheProperties() { return new RemoteCacheProperties(this.getCache()); } @Override default Batcher<TransactionBatch> getBatcher() { return new HotRodBatcher(this.getCache()); } }
1,808
35.18
70
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/RemoteCacheKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod; import java.util.Objects; import org.wildfly.clustering.ee.Key; /** * Base type for remote cache keys. * @author Paul Ferraro */ public class RemoteCacheKey<I> implements Key<I> { private I id; public RemoteCacheKey(I id) { this.id = id; } @Override public I getId() { return this.id; } @Override public int hashCode() { return Objects.hash(this.getClass(), this.id); } @Override public boolean equals(Object object) { if (object == null) { return false; } return this.getClass().equals(object.getClass()) && this.id.equals(((RemoteCacheKey<?>) object).id); } @Override public String toString() { return String.format("%s(%s)", this.getClass().getSimpleName(), this.id); } }
1,881
28.40625
108
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/RemoteCacheMutatorFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod; import java.time.Duration; import java.util.function.Function; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.ee.Mutator; import org.wildfly.clustering.ee.MutatorFactory; /** * Factory for creating a {@link Mutator} for a remote cache entry. * @author Paul Ferraro */ public class RemoteCacheMutatorFactory<K, V> implements MutatorFactory<K, V> { private final RemoteCache<K, V> cache; private final Function<V, Duration> maxIdle; public RemoteCacheMutatorFactory(RemoteCache<K, V> cache) { this(cache, null); } public RemoteCacheMutatorFactory(RemoteCache<K, V> cache, Function<V, Duration> maxIdle) { this.cache = cache; this.maxIdle = maxIdle; } @Override public Mutator createMutator(K key, V value) { return new RemoteCacheEntryMutator<>(this.cache, key, value, this.maxIdle); } }
1,962
34.690909
94
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/RemoteCacheEntryMutator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod; import java.time.Duration; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.infinispan.client.hotrod.RemoteCache; import org.wildfly.clustering.ee.Mutator; /** * Mutates a given cache entry. * @author Paul Ferraro */ public class RemoteCacheEntryMutator<K, V> implements Mutator { private final RemoteCache<K, V> cache; private final K id; private final V value; private final Function<V, Duration> maxIdle; public RemoteCacheEntryMutator(RemoteCache<K, V> cache, Map.Entry<K, V> entry) { this(cache, entry, null); } public RemoteCacheEntryMutator(RemoteCache<K, V> cache, K id, V value) { this(cache, id, value, null); } public RemoteCacheEntryMutator(RemoteCache<K, V> cache, Map.Entry<K, V> entry, Function<V, Duration> maxIdle) { this(cache, entry.getKey(), entry.getValue(), maxIdle); } public RemoteCacheEntryMutator(RemoteCache<K, V> cache, K id, V value, Function<V, Duration> maxIdle) { this.cache = cache; this.id = id; this.value = value; this.maxIdle = maxIdle; } @Override public void mutate() { Duration maxIdleDuration = (this.maxIdle != null) ? this.maxIdle.apply(this.value) : Duration.ZERO; long seconds = maxIdleDuration.getSeconds(); int nanos = maxIdleDuration.getNano(); if (nanos > 0) { seconds += 1; } this.cache.put(this.id, this.value, 0, TimeUnit.SECONDS, seconds, TimeUnit.SECONDS); } }
2,627
34.513514
115
java
null
wildfly-main/clustering/ee/hotrod/src/main/java/org/wildfly/clustering/ee/hotrod/tx/HotRodBatcher.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.hotrod.tx; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.exceptions.HotRodClientException; import org.wildfly.clustering.ee.cache.tx.TransactionalBatcher; /** * @author Paul Ferraro */ public class HotRodBatcher extends TransactionalBatcher<HotRodClientException> { public HotRodBatcher(RemoteCache<?, ?> cache) { super(cache.getTransactionManager(), HotRodClientException::new); } }
1,502
38.552632
80
java
null
wildfly-main/clustering/ee/infinispan/src/test/java/org/wildfly/clustering/ee/infinispan/InfinispanCachePropertiesTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import java.util.EnumSet; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.util.concurrent.IsolationLevel; import org.junit.Assert; import org.junit.Test; import org.wildfly.clustering.ee.cache.CacheProperties; /** * @author Paul Ferraro */ public class InfinispanCachePropertiesTestCase { @Test public void isLockOnRead() { Configuration config = new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).locking().isolationLevel(IsolationLevel.REPEATABLE_READ).build(); Assert.assertTrue(new InfinispanCacheProperties(config).isLockOnRead()); Configuration optimistic = config = new ConfigurationBuilder().read(config).transaction().lockingMode(LockingMode.OPTIMISTIC).build(); Assert.assertFalse(new InfinispanCacheProperties(optimistic).isLockOnRead()); Configuration nonTx = new ConfigurationBuilder().read(config).transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL).build(); Assert.assertFalse(new InfinispanCacheProperties(nonTx).isLockOnRead()); Configuration readCommitted = config = new ConfigurationBuilder().read(config).locking().isolationLevel(IsolationLevel.READ_COMMITTED).build(); Assert.assertFalse(new InfinispanCacheProperties(readCommitted).isLockOnRead()); } @Test public void isLockOnWrite() { Configuration config = new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build(); Assert.assertTrue(new InfinispanCacheProperties(config).isLockOnWrite()); Configuration optimistic = config = new ConfigurationBuilder().read(config).transaction().lockingMode(LockingMode.OPTIMISTIC).build(); Assert.assertFalse(new InfinispanCacheProperties(optimistic).isLockOnWrite()); Configuration nonTx = new ConfigurationBuilder().read(config).transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL).build(); Assert.assertFalse(new InfinispanCacheProperties(nonTx).isLockOnWrite()); } @SuppressWarnings("deprecation") @Test public void isMarshalling() { for (CacheMode mode : EnumSet.allOf(CacheMode.class)) { Configuration config = new ConfigurationBuilder().clustering().cacheMode(mode).build(); CacheProperties configuration = new InfinispanCacheProperties(config); if (mode.isDistributed() || mode.isReplicated() || mode.isScattered()) { Assert.assertTrue(mode.name(), configuration.isMarshalling()); } else { Assert.assertFalse(mode.name(), configuration.isMarshalling()); } } Configuration config = new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL).persistence().passivation(false).addSoftIndexFileStore().build(); Assert.assertTrue(new InfinispanCacheProperties(config).isMarshalling()); Configuration passivating = new ConfigurationBuilder().read(config).persistence().passivation(true).build(); Assert.assertTrue(new InfinispanCacheProperties(passivating).isMarshalling()); Configuration noStore = new ConfigurationBuilder().read(config).persistence().clearStores().build(); Assert.assertFalse(new InfinispanCacheProperties(noStore).isMarshalling()); } @SuppressWarnings("deprecation") @Test public void isPersistent() { for (CacheMode mode : EnumSet.allOf(CacheMode.class)) { Configuration config = new ConfigurationBuilder().clustering().cacheMode(mode).build(); CacheProperties configuration = new InfinispanCacheProperties(config); if (mode.isDistributed() || mode.isReplicated() || mode.isScattered()) { Assert.assertTrue(mode.name(), configuration.isPersistent()); } else { Assert.assertFalse(mode.name(), configuration.isPersistent()); } } Configuration config = new ConfigurationBuilder().clustering().cacheMode(CacheMode.LOCAL).persistence().passivation(false).addSoftIndexFileStore().build(); Assert.assertTrue(new InfinispanCacheProperties(config).isPersistent()); Configuration passivating = new ConfigurationBuilder().read(config).persistence().passivation(true).build(); Assert.assertFalse(new InfinispanCacheProperties(passivating).isPersistent()); Configuration noStore = new ConfigurationBuilder().read(config).persistence().clearStores().build(); Assert.assertFalse(new InfinispanCacheProperties(noStore).isPersistent()); } @Test public void isTransactional() { Configuration config = new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).build(); Assert.assertTrue(new InfinispanCacheProperties(config).isTransactional()); config = new ConfigurationBuilder().transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL).build(); Assert.assertFalse(new InfinispanCacheProperties(config).isTransactional()); } }
6,423
50.806452
221
java
null
wildfly-main/clustering/ee/infinispan/src/test/java/org/wildfly/clustering/ee/infinispan/CacheEntryMutatorTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.infinispan.AdvancedCache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.context.Flag; import org.infinispan.transaction.TransactionMode; import org.junit.Test; import org.wildfly.clustering.ee.Mutator; /** * Unit test for {@link CacheEntryMutator}. * * @author Paul Ferraro */ public class CacheEntryMutatorTestCase { @Test public void mutateTransactional() { AdvancedCache<Object, Object> cache = mock(AdvancedCache.class); Object id = new Object(); Object value = new Object(); Configuration config = new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).build(); when(cache.getCacheConfiguration()).thenReturn(config); Mutator mutator = new CacheEntryMutator<>(cache, id, value); when(cache.getAdvancedCache()).thenReturn(cache); when(cache.withFlags(Flag.IGNORE_RETURN_VALUES, Flag.FAIL_SILENTLY)).thenReturn(cache); mutator.mutate(); verify(cache).put(same(id), same(value)); mutator.mutate(); verify(cache, times(1)).put(same(id), same(value)); mutator.mutate(); verify(cache, times(1)).put(same(id), same(value)); } @Test public void mutateNonTransactional() { AdvancedCache<Object, Object> cache = mock(AdvancedCache.class); Object id = new Object(); Object value = new Object(); Configuration config = new ConfigurationBuilder().transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL).build(); when(cache.getCacheConfiguration()).thenReturn(config); Mutator mutator = new CacheEntryMutator<>(cache, id, value); when(cache.getAdvancedCache()).thenReturn(cache); when(cache.withFlags(Flag.IGNORE_RETURN_VALUES, Flag.FAIL_SILENTLY)).thenReturn(cache); mutator.mutate(); verify(cache).put(same(id), same(value)); mutator.mutate(); verify(cache, times(2)).put(same(id), same(value)); mutator.mutate(); verify(cache, times(3)).put(same(id), same(value)); } }
3,469
34.050505
131
java
null
wildfly-main/clustering/ee/infinispan/src/test/java/org/wildfly/clustering/ee/infinispan/PrimaryOwnerLocatorTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.function.Function; import org.infinispan.remoting.transport.Address; import org.junit.Test; import org.wildfly.clustering.group.Node; import org.wildfly.clustering.infinispan.distribution.KeyDistribution; import org.wildfly.clustering.server.NodeFactory; /** * @author Paul Ferraro */ public class PrimaryOwnerLocatorTestCase { @Test public void test() { KeyDistribution distribution = mock(KeyDistribution.class); NodeFactory<Address> memberFactory = mock(NodeFactory.class); Address staleAddress = mock(Address.class); Address address = mock(Address.class); Node member = mock(Node.class); Object key = new Object(); Function<Object, Node> locator = new PrimaryOwnerLocator<>(distribution, memberFactory); when(distribution.getPrimaryOwner(key)).thenReturn(staleAddress, address); when(memberFactory.createNode(staleAddress)).thenReturn(null); when(memberFactory.createNode(address)).thenReturn(member); Node result = locator.apply(key); assertSame(member, result); } }
2,301
36.129032
96
java
null
wildfly-main/clustering/ee/infinispan/src/test/java/org/wildfly/clustering/ee/infinispan/expiration/SimpleExpirationMetaDataMarshallerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.expiration; import java.io.IOException; import java.time.Duration; import java.time.Instant; import org.junit.Assert; import org.junit.Test; import org.wildfly.clustering.ee.expiration.ExpirationMetaData; import org.wildfly.clustering.marshalling.Tester; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; /** * Marshaller test for {@link SimpleExpirationMetaData}. * @author Paul Ferraro */ public class SimpleExpirationMetaDataMarshallerTestCase { @Test public void test() throws IOException { Tester<ExpirationMetaData> tester = ProtoStreamTesterFactory.INSTANCE.createTester(); tester.test(new SimpleExpirationMetaData(Duration.ofMinutes(30), Instant.EPOCH), this::assertEquals); tester.test(new SimpleExpirationMetaData(Duration.ofSeconds(600), Instant.now()), this::assertEquals); } private void assertEquals(ExpirationMetaData expected, ExpirationMetaData actual) { Assert.assertEquals(expected.getTimeout(), actual.getTimeout()); Assert.assertEquals(expected.getLastAccessTime(), actual.getLastAccessTime()); } }
2,188
39.537037
110
java
null
wildfly-main/clustering/ee/infinispan/src/test/java/org/wildfly/clustering/ee/infinispan/scheduler/CommandMarshallerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.io.IOException; import org.junit.Assert; import org.junit.Test; import org.wildfly.clustering.marshalling.MarshallingTesterFactory; import org.wildfly.clustering.marshalling.Tester; import org.wildfly.clustering.marshalling.protostream.ProtoStreamTesterFactory; /** * Unit test for marshalling scheduler commands. * @author Paul Ferraro */ public class CommandMarshallerTestCase { private final MarshallingTesterFactory factory = ProtoStreamTesterFactory.INSTANCE; @Test public void testScheduleWithLocalMetaDataCommand() throws IOException { Tester<ScheduleWithTransientMetaDataCommand<String, String>> tester = this.factory.createTester(); tester.test(new ScheduleWithTransientMetaDataCommand<>("foo"), this::assertEquals); tester.test(new ScheduleWithTransientMetaDataCommand<>("foo", "bar"), this::assertEquals); } <I, M> void assertEquals(ScheduleWithTransientMetaDataCommand<I, M> expected, ScheduleWithTransientMetaDataCommand<I, M> actual) { Assert.assertEquals(expected.getId(), actual.getId()); Assert.assertNull(actual.getMetaData()); } @Test public void testCancelCommand() throws IOException { Tester<CancelCommand<String, Object>> tester = this.factory.createTester(); tester.test(new CancelCommand<>("foo"), this::assertEquals); } <I, M> void assertEquals(CancelCommand<I, M> expected, CancelCommand<I, M> actual) { Assert.assertEquals(expected.getId(), actual.getId()); } @Test public void testScheduleWithMetaDataCommand() throws IOException { Tester<ScheduleWithMetaDataCommand<String, String>> tester = this.factory.createTester(); tester.test(new ScheduleWithMetaDataCommand<>("foo", "bar"), this::assertEquals); } <I, M> void assertEquals(ScheduleWithMetaDataCommand<I, M> expected, ScheduleWithMetaDataCommand<I, M> actual) { Assert.assertEquals(expected.getId(), actual.getId()); Assert.assertEquals(expected.getMetaData(), actual.getMetaData()); } }
3,142
39.818182
134
java
null
wildfly-main/clustering/ee/infinispan/src/test/java/org/wildfly/clustering/ee/infinispan/affinity/AffinityIdentifierFactoryTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.affinity; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.UUID; import java.util.function.Supplier; import org.infinispan.Cache; import org.infinispan.affinity.KeyAffinityService; import org.infinispan.affinity.KeyGenerator; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.remoting.transport.Address; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.wildfly.clustering.ee.Key; import org.wildfly.clustering.ee.cache.IdentifierFactory; import org.wildfly.clustering.ee.infinispan.GroupedKey; import org.wildfly.clustering.infinispan.affinity.KeyAffinityServiceFactory; /** * Unit test for {@link AffinityIdentifierFactory} * * @author Paul Ferraro */ public class AffinityIdentifierFactoryTestCase { private final Supplier<UUID> factory = mock(Supplier.class); private final KeyAffinityServiceFactory affinityFactory = mock(KeyAffinityServiceFactory.class); private final KeyAffinityService<Key<UUID>> affinity = mock(KeyAffinityService.class); private final Cache<Key<UUID>, ?> cache = mock(Cache.class); private final Address localAddress = mock(Address.class); private IdentifierFactory<UUID> subject; @Captor private ArgumentCaptor<KeyGenerator<Key<UUID>>> capturedGenerator; @Before public void init() throws Exception { EmbeddedCacheManager manager = mock(EmbeddedCacheManager.class); try (AutoCloseable test = MockitoAnnotations.openMocks(this)) { when(this.affinityFactory.createService(same(this.cache), this.capturedGenerator.capture())).thenReturn(this.affinity); when(this.cache.getCacheManager()).thenReturn(manager); when(manager.getAddress()).thenReturn(this.localAddress); this.subject = new AffinityIdentifierFactory<>(this.factory, this.cache, this.affinityFactory); KeyGenerator<Key<UUID>> generator = this.capturedGenerator.getValue(); assertSame(generator, this.subject); UUID expected = UUID.randomUUID(); when(this.factory.get()).thenReturn(expected); Key<UUID> result = generator.getKey(); assertSame(expected, result.getId()); } } @Test public void start() { this.subject.start(); verify(this.affinity).start(); verifyNoMoreInteractions(this.affinity); } @Test public void stop() { this.subject.stop(); verify(this.affinity).stop(); verifyNoMoreInteractions(this.affinity); } @Test public void createIdentifier() { UUID expected = UUID.randomUUID(); when(this.affinity.getKeyForAddress(this.localAddress)).thenReturn(new GroupedKey<>(expected)); UUID result = this.subject.get(); assertSame(expected, result); } }
4,218
34.453782
131
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/CacheEntryMutator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import org.infinispan.Cache; import org.infinispan.context.Flag; import org.wildfly.clustering.ee.Mutator; /** * Mutates a given cache entry. * @author Paul Ferraro */ public class CacheEntryMutator<K, V> implements Mutator { private final Cache<K, V> cache; private final K id; private final V value; private final AtomicBoolean mutated; public CacheEntryMutator(Cache<K, V> cache, Map.Entry<K, V> entry) { this(cache, entry.getKey(), entry.getValue()); } public CacheEntryMutator(Cache<K, V> cache, K id, V value) { this.cache = cache; this.id = id; this.value = value; this.mutated = cache.getCacheConfiguration().transaction().transactionMode().isTransactional() ? new AtomicBoolean(false) : null; } @Override public void mutate() { // We only ever have to perform a replace once within a batch if ((this.mutated == null) || this.mutated.compareAndSet(false, true)) { // Use FAIL_SILENTLY to prevent mutation from failing locally due to remote exceptions this.cache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES, Flag.FAIL_SILENTLY).put(this.id, this.value); } } }
2,362
36.507937
137
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/InfinispanCacheConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; /** * General configuration that identifies an Infinispan cache. * @author Paul Ferraro */ public interface InfinispanCacheConfiguration { String getContainerName(); String getCacheName(); }
1,273
37.606061
70
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/InfinispanCacheProperties.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import org.infinispan.configuration.cache.Configuration; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.wildfly.clustering.ee.cache.CacheProperties; /** * Eagerly calculates the properties of a cache configuration. * @author Paul Ferraro */ public class InfinispanCacheProperties implements CacheProperties { private final boolean lockOnRead; private final boolean lockOnWrite; private final boolean marshalling; private final boolean persistent; private final boolean transactional; public InfinispanCacheProperties(Configuration config) { this.transactional = config.transaction().transactionMode().isTransactional(); this.lockOnWrite = this.transactional && (config.transaction().lockingMode() == LockingMode.PESSIMISTIC); this.lockOnRead = this.lockOnWrite && (config.locking().isolationLevel() == IsolationLevel.REPEATABLE_READ); boolean clustered = config.clustering().cacheMode().needsStateTransfer(); boolean hasStore = config.persistence().usingStores(); this.marshalling = clustered || hasStore; this.persistent = clustered || (hasStore && !config.persistence().passivation()) || config.memory().isOffHeap(); } @Override public boolean isPersistent() { return this.persistent; } @Override public boolean isTransactional() { return this.transactional; } @Override public boolean isLockOnRead() { return this.lockOnRead; } @Override public boolean isLockOnWrite() { return this.lockOnWrite; } @Override public boolean isMarshalling() { return this.marshalling; } }
2,804
35.428571
120
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/InfinispanMutatorFactory.java
package org.wildfly.clustering.ee.infinispan; import org.infinispan.Cache; import org.wildfly.clustering.ee.Mutator; import org.wildfly.clustering.ee.MutatorFactory; import org.wildfly.clustering.ee.cache.CacheProperties; /** * Factory for creating {@link Mutator} objects for an Infinispan cache. * @author Paul Ferraro */ public class InfinispanMutatorFactory<K, V> implements MutatorFactory<K, V> { private final Cache<K, V> cache; private final CacheProperties properties; public InfinispanMutatorFactory(Cache<K, V> cache) { this(cache, new InfinispanCacheProperties(cache.getCacheConfiguration())); } public InfinispanMutatorFactory(Cache<K, V> cache, CacheProperties properties) { this.cache = cache; this.properties = properties; } @Override public Mutator createMutator(K key, V value) { return this.properties.isPersistent() ? new CacheEntryMutator<>(this.cache, key, value) : Mutator.PASSIVE; } }
985
30.806452
114
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/InfinispanConfiguration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import org.infinispan.Cache; import org.infinispan.context.Flag; import org.infinispan.util.concurrent.BlockingManager; import org.wildfly.clustering.ee.Batcher; import org.wildfly.clustering.ee.cache.CacheConfiguration; import org.wildfly.clustering.ee.cache.CacheProperties; import org.wildfly.clustering.ee.cache.tx.TransactionBatch; import org.wildfly.clustering.ee.infinispan.tx.InfinispanBatcher; /** * @author Paul Ferraro */ public interface InfinispanConfiguration extends CacheConfiguration { @Override <K, V> Cache<K, V> getCache(); @Override default CacheProperties getCacheProperties() { return new InfinispanCacheProperties(this.getCache().getCacheConfiguration()); } /** * Returns a cache with select-for-update semantics. * @param <K> the cache key type * @param <V> the cache value type * @return a cache with select-for-update semantics. */ default <K, V> Cache<K, V> getReadForUpdateCache() { return this.getCacheProperties().isLockOnRead() ? this.<K, V>getCache().getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK) : this.getCache(); } /** * Returns a cache with try-lock write semantic, e.g. whose write operations will return null if another transaction owns the write lock. * @param <K> the cache key type * @param <V> the cache value type * @return a cache with try-lock semantics. */ default <K, V> Cache<K, V> getTryLockCache() { return this.getCacheProperties().isLockOnWrite() ? this.<K, V>getCache().getAdvancedCache().withFlags(Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, Flag.FAIL_SILENTLY) : this.getCache(); } /** * Returns a cache with select-for-update and try-lock semantics. * @param <K> the cache key type * @param <V> the cache value type * @return a cache with try-lock and select-for-update semantics. */ default <K, V> Cache<K, V> getTryReadForUpdateCache() { return this.getCacheProperties().isLockOnRead() ? this.<K, V>getCache().getAdvancedCache().withFlags(Flag.FORCE_WRITE_LOCK, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, Flag.FAIL_SILENTLY) : this.getCache(); } /** * Returns a cache for use with write-only operations, e.g. put/remove where previous values are not needed. * @param <K> the cache key type * @param <V> the cache value type * @return a cache for use with write-only operations. */ default <K, V> Cache<K, V> getWriteOnlyCache() { return this.<K, V>getCache().getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES); } /** * Returns a cache whose write operations do not trigger cache listeners. * @param <K> the cache key type * @param <V> the cache value type * @return a cache whose write operations do not trigger cache listeners. */ default <K, V> Cache<K, V> getSilentWriteCache() { return this.<K, V>getCache().getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES, Flag.SKIP_LISTENER_NOTIFICATION); } @Override default Batcher<TransactionBatch> getBatcher() { return new InfinispanBatcher(this.getCache()); } @SuppressWarnings("deprecation") default BlockingManager getBlockingManager() { return this.getCache().getCacheManager().getGlobalComponentRegistry().getComponent(BlockingManager.class); } }
4,434
40.448598
206
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/PrimaryOwnerLocator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import java.util.function.Function; import org.infinispan.Cache; import org.infinispan.remoting.transport.Address; import org.wildfly.clustering.group.Node; import org.wildfly.clustering.infinispan.distribution.CacheKeyDistribution; import org.wildfly.clustering.infinispan.distribution.KeyDistribution; import org.wildfly.clustering.server.NodeFactory; /** * Function that returns the primary owner for a given cache key. * @author Paul Ferraro */ public class PrimaryOwnerLocator<K> implements Function<K, Node> { private final KeyDistribution distribution; private final NodeFactory<Address> memberFactory; public PrimaryOwnerLocator(Cache<? extends K, ?> cache, NodeFactory<Address> memberFactory) { this(new CacheKeyDistribution(cache), memberFactory); } PrimaryOwnerLocator(KeyDistribution distribution, NodeFactory<Address> memberFactory) { this.distribution = distribution; this.memberFactory = memberFactory; } @Override public Node apply(K key) { Node member = null; while (member == null) { Address address = this.distribution.getPrimaryOwner(key); // This has been observed to return null mid-rebalance if (address != null) { // This can return null if member has left the cluster member = this.memberFactory.createNode(address); } else { Thread.yield(); } } return member; } }
2,569
37.358209
97
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/GroupedKey.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan; import java.util.Objects; import org.wildfly.clustering.ee.Key; import org.wildfly.clustering.infinispan.distribution.KeyGroup; /** * An embedded cache key supporting group co-location. * @author Paul Ferraro */ public class GroupedKey<K> implements Key<K>, KeyGroup<K> { private final K id; public GroupedKey(K id) { this.id = id; } /** * Returns the value of this key. * @return the key value */ @Override public K getId() { return this.id; } @Override public boolean equals(Object object) { if ((object == null) || (object.getClass() != this.getClass())) return false; @SuppressWarnings("unchecked") GroupedKey<K> key = (GroupedKey<K>) object; return this.id.equals(key.id); } @Override public int hashCode() { return Objects.hash(this.getClass().getName(), this.id); } @Override public String toString() { return String.format("%s(%s)", this.getClass().getSimpleName(), this.id.toString()); } }
2,123
30.235294
92
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/expiration/ExpirationSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.expiration; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; /** * {@link SerializationContextInitializer} that registers marshallers for all marshallable objects in this package. * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class ExpirationSerializationContextInitializer extends AbstractSerializationContextInitializer { @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new SimpleExpirationMetaDataMarshaller()); } }
1,815
42.238095
115
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/expiration/SimpleExpirationMetaDataMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.expiration; import java.io.IOException; import java.time.Duration; import java.time.Instant; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; /** * ProtoStream marshaller for a {@link SimpleExpirationMetaData}. * @author Paul Ferraro */ public class SimpleExpirationMetaDataMarshaller implements ProtoStreamMarshaller<SimpleExpirationMetaData> { private static final int TIMEOUT_INDEX = 1; private static final int LAST_ACCESS_TIME_INDEX = 2; // This is the default specification timeout for web sessions private static final Duration DEFAULT_TIMEOUT = Duration.ofMinutes(30); private static final Instant DEFAULT_LAST_ACCESS_TIME = Instant.EPOCH; @Override public Class<? extends SimpleExpirationMetaData> getJavaClass() { return SimpleExpirationMetaData.class; } @Override public SimpleExpirationMetaData readFrom(ProtoStreamReader reader) throws IOException { Duration timeout = DEFAULT_TIMEOUT; Instant lastAccessTime = DEFAULT_LAST_ACCESS_TIME; while (!reader.isAtEnd()) { int tag = reader.readTag(); switch (WireType.getTagFieldNumber(tag)) { case TIMEOUT_INDEX: timeout = reader.readObject(Duration.class); break; case LAST_ACCESS_TIME_INDEX: lastAccessTime = reader.readObject(Instant.class); break; default: reader.skipField(tag); } } return new SimpleExpirationMetaData(timeout, lastAccessTime); } @Override public void writeTo(ProtoStreamWriter writer, SimpleExpirationMetaData metaData) throws IOException { Duration timeout = metaData.getTimeout(); if (!DEFAULT_TIMEOUT.equals(timeout)) { writer.writeObject(TIMEOUT_INDEX, timeout); } Instant lastAccessedTime = metaData.getLastAccessTime(); if (!DEFAULT_LAST_ACCESS_TIME.equals(lastAccessedTime)) { writer.writeObject(LAST_ACCESS_TIME_INDEX, lastAccessedTime); } } }
3,401
39.5
108
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/expiration/SimpleExpirationMetaData.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.expiration; import java.time.Duration; import java.time.Instant; import org.wildfly.clustering.ee.expiration.ExpirationMetaData; /** * Simple {@link ExpirationMetaData} implementation. * @author Paul Ferraro */ public class SimpleExpirationMetaData implements ExpirationMetaData { private final Duration timeout; private final Instant lastAccessTime; public SimpleExpirationMetaData(ExpirationMetaData metaData) { this(metaData.getTimeout(), metaData.getLastAccessTime()); } SimpleExpirationMetaData(Duration timeout, Instant lastAccessedTime) { this.timeout = timeout; this.lastAccessTime = lastAccessedTime; } @Override public Duration getTimeout() { return this.timeout; } @Override public Instant getLastAccessTime() { return this.lastAccessTime; } }
1,923
32.172414
74
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/expiration/AbstractExpirationScheduler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.expiration; import java.time.Instant; import org.wildfly.clustering.ee.Scheduler; import org.wildfly.clustering.ee.expiration.ExpirationMetaData; import org.wildfly.clustering.ee.infinispan.scheduler.AbstractCacheEntryScheduler; /** * An {@link AbstractCacheEntryScheduler} suitable for expiration. * @author Paul Ferraro * @param <I> the identifier type of the scheduled object */ public abstract class AbstractExpirationScheduler<I> extends AbstractCacheEntryScheduler<I, ExpirationMetaData> { public AbstractExpirationScheduler(Scheduler<I, Instant> scheduler) { super(scheduler, metaData -> !metaData.isImmortal() ? metaData.getLastAccessTime().plus(metaData.getTimeout()) : null); } }
1,783
41.47619
127
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/expiration/ScheduleWithExpirationMetaDataCommandFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.expiration; import java.util.function.BiFunction; import org.wildfly.clustering.ee.expiration.ExpirationMetaData; import org.wildfly.clustering.ee.infinispan.scheduler.ScheduleCommand; import org.wildfly.clustering.ee.infinispan.scheduler.ScheduleWithMetaDataCommand; /** * {@link ScheduleCommand} factory that wraps expiration metadata with a marshallable implementation. * @author Paul Ferraro * @param <I> the identifier type of the scheduled object */ public class ScheduleWithExpirationMetaDataCommandFactory<I> implements BiFunction<I, ExpirationMetaData, ScheduleCommand<I, ExpirationMetaData>> { @Override public ScheduleCommand<I, ExpirationMetaData> apply(I id, ExpirationMetaData metaData) { return new ScheduleWithMetaDataCommand<>(id, new SimpleExpirationMetaData(metaData)); } }
1,890
42.976744
147
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/CancelCommand.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import org.wildfly.clustering.dispatcher.Command; /** * Command that cancels a previously scheduled item. * @author Paul Ferraro */ public class CancelCommand<I, M> implements Command<Void, CacheEntryScheduler<I, M>> { private static final long serialVersionUID = 7990530622481705411L; private final I id; public CancelCommand(I id) { this.id = id; } I getId() { return this.id; } @Override public Void execute(CacheEntryScheduler<I, M> scheduler) { scheduler.cancel(this.id); return null; } @Override public String toString() { return String.format("%s[%s]", this.getClass().getSimpleName(), this.id); } }
1,785
31.472727
86
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/AbstractCacheEntryScheduler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.time.Duration; import java.time.Instant; import java.util.Iterator; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import org.wildfly.clustering.ee.Scheduler; import org.wildfly.clustering.ee.infinispan.GroupedKey; import org.wildfly.clustering.infinispan.distribution.Locality; /** * Abstract {@link CacheEntryScheduler} that delegates to a local scheduler. * @author Paul Ferraro */ public abstract class AbstractCacheEntryScheduler<I, M> implements CacheEntryScheduler<I, M> { private final Scheduler<I, Instant> scheduler; private final Function<M, Instant> instant; protected AbstractCacheEntryScheduler(Scheduler<I, Instant> scheduler, Function<M, Duration> duration, Predicate<Duration> skip, Function<M, Instant> basis) { this(scheduler, new AdditionFunction<>(duration, skip, basis)); } protected AbstractCacheEntryScheduler(Scheduler<I, Instant> scheduler, Function<M, Instant> instant) { this.scheduler = scheduler; this.instant = instant; } @Override public void schedule(I id, M metaData) { Instant instant = this.instant.apply(metaData); if (instant != null) { this.scheduler.schedule(id, instant); } } @Override public void cancel(I id) { this.scheduler.cancel(id); } @Override public void cancel(Locality locality) { try (Stream<I> stream = this.scheduler.stream()) { Iterator<I> entries = stream.iterator(); while (entries.hasNext()) { if (Thread.currentThread().isInterrupted()) break; I id = entries.next(); if (!locality.isLocal(new GroupedKey<>(id))) { this.scheduler.cancel(id); } } } } @Override public Stream<I> stream() { return this.scheduler.stream(); } @Override public void close() { this.scheduler.close(); } @Override public String toString() { return this.scheduler.toString(); } private static class AdditionFunction<M> implements Function<M, Instant> { private final Function<M, Duration> duration; private final Predicate<Duration> skip; private final Function<M, Instant> basis; AdditionFunction(Function<M, Duration> duration, Predicate<Duration> skip, Function<M, Instant> basis) { this.duration = duration; this.skip = skip; this.basis = basis; } @Override public Instant apply(M metaData) { Duration duration = this.duration.apply(metaData); return !this.skip.test(duration) ? this.basis.apply(metaData).plus(duration) : null; } } }
3,897
33.192982
162
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/SchedulerSerializationContextInitializer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.kohsuke.MetaInfServices; import org.wildfly.clustering.marshalling.protostream.AbstractSerializationContextInitializer; import org.wildfly.clustering.marshalling.protostream.FunctionalScalarMarshaller; import org.wildfly.clustering.marshalling.protostream.Scalar; import org.wildfly.clustering.marshalling.protostream.ValueMarshaller; /** * @author Paul Ferraro */ @MetaInfServices(SerializationContextInitializer.class) public class SchedulerSerializationContextInitializer extends AbstractSerializationContextInitializer { @Override public void registerMarshallers(SerializationContext context) { context.registerMarshaller(new FunctionalScalarMarshaller<>(CancelCommand.class, Scalar.ANY, CancelCommand::getId, CancelCommand::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(ContainsCommand.class, Scalar.ANY, ContainsCommand::getId, ContainsCommand::new)); context.registerMarshaller(new FunctionalScalarMarshaller<>(ScheduleWithTransientMetaDataCommand.class, Scalar.ANY, ScheduleWithTransientMetaDataCommand::getId, ScheduleWithTransientMetaDataCommand::new)); context.registerMarshaller(new ScheduleWithMetaDataCommandMarshaller<>()); context.registerMarshaller(new ValueMarshaller<>(new EntriesCommand<>())); } }
2,510
51.3125
213
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/ScheduleWithMetaDataCommandMarshaller.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.io.IOException; import org.infinispan.protostream.descriptors.WireType; import org.wildfly.clustering.marshalling.protostream.ProtoStreamMarshaller; import org.wildfly.clustering.marshalling.protostream.ProtoStreamReader; import org.wildfly.clustering.marshalling.protostream.ProtoStreamWriter; /** * ProtoStream marshaller for a {@link ScheduleWithMetaDataCommand}. * @author Paul Ferraro */ public class ScheduleWithMetaDataCommandMarshaller<I, M> implements ProtoStreamMarshaller<ScheduleWithMetaDataCommand<I, M>> { private static final byte ID_INDEX = 1; private static final byte META_DATA_INDEX = 2; @SuppressWarnings("unchecked") @Override public Class<? extends ScheduleWithMetaDataCommand<I, M>> getJavaClass() { return (Class<ScheduleWithMetaDataCommand<I, M>>) (Class<?>) ScheduleWithMetaDataCommand.class; } @SuppressWarnings("unchecked") @Override public ScheduleWithMetaDataCommand<I, M> readFrom(ProtoStreamReader reader) throws IOException { I id = null; M metaData = null; while (!reader.isAtEnd()) { int tag = reader.readTag(); switch (WireType.getTagFieldNumber(tag)) { case ID_INDEX: id = (I) reader.readAny(); break; case META_DATA_INDEX: metaData = (M) reader.readAny(); break; default: reader.skipField(tag); } } return new ScheduleWithMetaDataCommand<>(id, metaData); } @Override public void writeTo(ProtoStreamWriter writer, ScheduleWithMetaDataCommand<I, M> command) throws IOException { I id = command.getId(); if (id != null) { writer.writeAny(ID_INDEX, id); } M metaData = command.getMetaData(); if (metaData != null) { writer.writeAny(META_DATA_INDEX, metaData); } } }
3,058
37.2375
126
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/PrimaryOwnerScheduler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.time.Duration; import java.util.Collection; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; import org.wildfly.clustering.dispatcher.Command; import org.wildfly.clustering.dispatcher.CommandDispatcher; import org.wildfly.clustering.dispatcher.CommandDispatcherException; import org.wildfly.clustering.ee.Invoker; import org.wildfly.clustering.ee.Scheduler; import org.wildfly.clustering.ee.cache.retry.RetryingInvoker; import org.wildfly.clustering.ee.infinispan.logging.Logger; import org.wildfly.clustering.group.Node; import org.wildfly.clustering.server.dispatcher.CommandDispatcherFactory; import org.wildfly.common.function.ExceptionSupplier; /** * Scheduler decorator that schedules/cancels a given object on the primary owner. * @author Paul Ferraro */ public class PrimaryOwnerScheduler<I, K, M> implements Scheduler<I, M>, Function<CompletionStage<Collection<I>>, Stream<I>> { private static final Invoker INVOKER = new RetryingInvoker(Duration.ZERO, Duration.ofMillis(10), Duration.ofMillis(100)); private final Function<K, Node> primaryOwnerLocator; private final Function<I, K> keyFactory; private final CommandDispatcher<CacheEntryScheduler<I, M>> dispatcher; private final BiFunction<I, M, ScheduleCommand<I, M>> scheduleCommandFactory; public <C, L> PrimaryOwnerScheduler(CommandDispatcherFactory dispatcherFactory, String name, CacheEntryScheduler<I, M> scheduler, Function<K, Node> primaryOwnerLocator, Function<I, K> keyFactory) { this(dispatcherFactory, name, scheduler, primaryOwnerLocator, keyFactory, ScheduleWithTransientMetaDataCommand::new); } public <C, L> PrimaryOwnerScheduler(CommandDispatcherFactory dispatcherFactory, String name, CacheEntryScheduler<I, M> scheduler, Function<K, Node> primaryOwnerLocator, Function<I, K> keyFactory, BiFunction<I, M, ScheduleCommand<I, M>> scheduleCommandFactory) { this.dispatcher = dispatcherFactory.createCommandDispatcher(name, scheduler, keyFactory.apply(null).getClass().getClassLoader()); this.primaryOwnerLocator = primaryOwnerLocator; this.keyFactory = keyFactory; this.scheduleCommandFactory = scheduleCommandFactory; } @Override public void schedule(I id, M metaData) { try { this.executeOnPrimaryOwner(id, this.scheduleCommandFactory.apply(id, metaData)); } catch (CommandDispatcherException e) { Logger.ROOT_LOGGER.failedToSchedule(e, id); } } @Override public void cancel(I id) { try { this.executeOnPrimaryOwner(id, new CancelCommand<>(id)).toCompletableFuture().join(); } catch (CommandDispatcherException | CompletionException e) { Logger.ROOT_LOGGER.failedToCancel(e, id); } catch (CancellationException e) { // Ignore } } @Override public boolean contains(I id) { try { return this.executeOnPrimaryOwner(id, new ContainsCommand<>(id)).toCompletableFuture().join(); } catch (CommandDispatcherException | CompletionException e) { Logger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e); return false; } catch (CancellationException e) { return false; } } private <R> CompletionStage<R> executeOnPrimaryOwner(I id, Command<R, CacheEntryScheduler<I, M>> command) throws CommandDispatcherException { K key = this.keyFactory.apply(id); Function<K, Node> primaryOwnerLocator = this.primaryOwnerLocator; CommandDispatcher<CacheEntryScheduler<I, M>> dispatcher = this.dispatcher; ExceptionSupplier<CompletionStage<R>, CommandDispatcherException> action = new ExceptionSupplier<>() { @Override public CompletionStage<R> get() throws CommandDispatcherException { Node node = primaryOwnerLocator.apply(key); Logger.ROOT_LOGGER.tracef("Executing command %s on %s", command, node); // This should only go remote following a failover return dispatcher.executeOnMember(command, node); } }; return INVOKER.invoke(action); } @Override public Stream<I> stream() { try { Map<Node, CompletionStage<Collection<I>>> results = this.dispatcher.executeOnGroup(new EntriesCommand<>()); return results.isEmpty() ? Stream.empty() : results.values().stream().map(this).flatMap(Function.identity()).distinct(); } catch (CommandDispatcherException e) { return Stream.empty(); } } @Override public Stream<I> apply(CompletionStage<Collection<I>> stage) { try { return stage.toCompletableFuture().join().stream(); } catch (CompletionException e) { Logger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e); return Stream.empty(); } catch (CancellationException e) { return Stream.empty(); } } @Override public void close() { this.dispatcher.close(); this.dispatcher.getContext().close(); } }
6,421
43.289655
265
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/ScheduleLocalEntriesTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.util.Iterator; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.context.Flag; import org.wildfly.clustering.ee.Key; import org.wildfly.clustering.infinispan.distribution.Locality; /** * A task which schedules newly owned entries. * @author Paul Ferraro * @param <I> identifier type * @param <M> the expiration metadata type * @param <K> cache key type */ public class ScheduleLocalEntriesTask<I, M, K extends Key<I>> implements BiConsumer<Locality, Locality> { private final Cache<K, Object> cache; private final Predicate<Map.Entry<? super K, ? super Object>> filter; private final CacheEntryScheduler<I, M> scheduler; public ScheduleLocalEntriesTask(Cache<K, Object> cache, Predicate<Map.Entry<? super K, ? super Object>> filter, CacheEntryScheduler<I, M> scheduler) { this.cache = cache; this.filter = filter; this.scheduler = scheduler; } @Override public void accept(Locality oldLocality, Locality newLocality) { // Iterate over local entries, including any cache stores to include entries that may be passivated/invalidated try (Stream<Map.Entry<K, Object>> stream = this.cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).entrySet().stream().filter(this.filter)) { Iterator<Map.Entry<K, Object>> entries = stream.iterator(); while (entries.hasNext()) { if (Thread.currentThread().isInterrupted()) break; K key = entries.next().getKey(); // If we are the new primary owner of this bean then schedule expiration of this bean locally if (!oldLocality.isLocal(key) && newLocality.isLocal(key)) { this.scheduler.schedule(key.getId()); } } } } }
3,004
41.928571
156
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/EntriesCommand.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.util.Collection; import java.util.stream.Collectors; import org.wildfly.clustering.dispatcher.Command; /** * @author Paul Ferraro */ public class EntriesCommand<I, M> implements Command<Collection<I>, CacheEntryScheduler<I, M>> { private static final long serialVersionUID = -7918056022234250133L; @Override public Collection<I> execute(CacheEntryScheduler<I, M> scheduler) throws Exception { return scheduler.stream().collect(Collectors.toList()); } @Override public String toString() { return this.getClass().getSimpleName(); } }
1,675
35.434783
96
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/CacheEntryScheduler.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import org.wildfly.clustering.ee.Scheduler; import org.wildfly.clustering.infinispan.distribution.Locality; /** * A task scheduler. * @author Paul Ferraro */ public interface CacheEntryScheduler<I, M> extends Scheduler<I, M> { /** * Schedules a cache entry with the specified identifier. * This method will generally delegate to {@link #schedule(Object, Object)} after performing a cache lookup. * @param id the identifier of the object to be scheduled */ void schedule(I id); /** * Cancels any previous scheduled tasks for entries which are no longer local to the current node * @param locality the cache locality */ void cancel(Locality locality); }
1,789
37.913043
112
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/SchedulerTopologyChangeListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.util.Collections; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.infinispan.Cache; import org.infinispan.distribution.ch.ConsistentHash; import org.infinispan.distribution.ch.KeyPartitioner; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.TopologyChanged; import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent; import org.infinispan.remoting.transport.Address; import org.infinispan.util.concurrent.BlockingManager; import org.wildfly.clustering.context.DefaultExecutorService; import org.wildfly.clustering.context.DefaultThreadFactory; import org.wildfly.clustering.ee.Key; import org.wildfly.clustering.infinispan.distribution.ConsistentHashLocality; import org.wildfly.clustering.infinispan.distribution.Locality; import org.wildfly.clustering.infinispan.listener.ListenerRegistrar; import org.wildfly.clustering.infinispan.listener.ListenerRegistration; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author Paul Ferraro */ @Listener public class SchedulerTopologyChangeListener<I, K extends Key<I>, V> implements ListenerRegistrar { private final Cache<K, V> cache; private final ExecutorService executor = Executors.newSingleThreadExecutor(new DefaultThreadFactory(SchedulerTopologyChangeListener.class)); private final AtomicReference<Future<?>> scheduleTaskFuture = new AtomicReference<>(); private final Consumer<Locality> cancelTask; private final BiConsumer<Locality, Locality> scheduleTask; private final KeyPartitioner partitioner; private final BlockingManager blocking; public SchedulerTopologyChangeListener(Cache<K, V> cache, CacheEntryScheduler<I, ?> scheduler, BiConsumer<Locality, Locality> scheduleTask) { this(cache, scheduler::cancel, scheduleTask); } @SuppressWarnings("deprecation") public SchedulerTopologyChangeListener(Cache<K, V> cache, Consumer<Locality> cancelTask, BiConsumer<Locality, Locality> scheduleTask) { this.cache = cache; this.cancelTask = cancelTask; this.scheduleTask = scheduleTask; this.blocking = this.cache.getCacheManager().getGlobalComponentRegistry().getComponent(BlockingManager.class); this.partitioner = this.cache.getAdvancedCache().getComponentRegistry().getLocalComponent(KeyPartitioner.class); } @Override public ListenerRegistration register() { this.cache.addListener(this); return () -> { this.cache.removeListener(this); WildFlySecurityManager.doUnchecked(this.executor, DefaultExecutorService.SHUTDOWN_NOW_ACTION); try { this.executor.awaitTermination(this.cache.getCacheConfiguration().transaction().cacheStopTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }; } @TopologyChanged public CompletionStage<Void> topologyChanged(TopologyChangedEvent<K, V> event) { Cache<K, V> cache = event.getCache(); Address address = cache.getCacheManager().getAddress(); ConsistentHash oldHash = event.getWriteConsistentHashAtStart(); Set<Integer> oldSegments = oldHash.getMembers().contains(address) ? oldHash.getPrimarySegmentsForOwner(address) : Collections.emptySet(); ConsistentHash newHash = event.getWriteConsistentHashAtEnd(); Set<Integer> newSegments = newHash.getMembers().contains(address) ? newHash.getPrimarySegmentsForOwner(address) : Collections.emptySet(); if (event.isPre()) { // If there are segments that we no longer own, then run cancellation task if (!newSegments.containsAll(oldSegments)) { Future<?> future = this.scheduleTaskFuture.getAndSet(null); if (future != null) { future.cancel(true); } return this.blocking.runBlocking(() -> this.cancelTask.accept(new ConsistentHashLocality(this.partitioner, newHash, address)), this.getClass().getName()); } } else { // If we have newly owned segments, then run schedule task if (!oldSegments.containsAll(newSegments)) { Locality oldLocality = new ConsistentHashLocality(this.partitioner, oldHash, address); Locality newLocality = new ConsistentHashLocality(this.partitioner, newHash, address); try { Future<?> future = this.scheduleTaskFuture.getAndSet(this.executor.submit(() -> this.scheduleTask.accept(oldLocality, newLocality))); if (future != null) { future.cancel(true); } } catch (RejectedExecutionException e) { // Executor was shutdown } } } return CompletableFuture.completedStage(null); } }
6,457
48.29771
170
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/ScheduleWithTransientMetaDataCommand.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; /** * Command that scheduled an item. * @author Paul Ferraro */ public class ScheduleWithTransientMetaDataCommand<I, M> implements ScheduleCommand<I, M> { private static final long serialVersionUID = 6254782388444864112L; private final I id; private final transient M metaData; public ScheduleWithTransientMetaDataCommand(I id, M metaData) { this.id = id; this.metaData = metaData; } ScheduleWithTransientMetaDataCommand(I id) { this(id, null); } @Override public I getId() { return this.id; } @Override public M getMetaData() { return this.metaData; } @Override public String toString() { return String.format("%s[%s]", this.getClass().getSimpleName(), this.id); } }
1,870
30.711864
90
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/ContainsCommand.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import org.wildfly.clustering.dispatcher.Command; /** * @author Paul Ferraro */ public class ContainsCommand<I, M> implements Command<Boolean, CacheEntryScheduler<I, M>> { private static final long serialVersionUID = 7221762541453484399L; private final I id; ContainsCommand(I id) { this.id = id; } @Override public Boolean execute(CacheEntryScheduler<I, M> scheduler) throws Exception { return scheduler.contains(this.id); } I getId() { return this.id; } @Override public String toString() { return String.format("%s[%s]", this.getClass().getSimpleName(), this.id); } }
1,740
31.849057
91
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/ScheduleWithMetaDataCommand.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; /** * Command that schedules an item, where its meta data is persisted. * @author Paul Ferraro */ public class ScheduleWithMetaDataCommand<I, M> implements ScheduleCommand<I, M> { private static final long serialVersionUID = 2116021502509126945L; private final I id; private final M metaData; public ScheduleWithMetaDataCommand(I id, M metaData) { this.id = id; this.metaData = metaData; } @Override public I getId() { return this.id; } @Override public M getMetaData() { return this.metaData; } @Override public String toString() { return String.format("%s[%s]", this.getClass().getSimpleName(), this.id); } }
1,796
31.672727
81
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/ScheduleCommand.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import org.wildfly.clustering.dispatcher.Command; /** * Command that scheduled an element. * @author Paul Ferraro */ public interface ScheduleCommand<I, M> extends Command<Void, CacheEntryScheduler<I, M>> { /** * Returns the identifier of the element to be scheduled. * @return the identifier of the element to be scheduled. */ I getId(); /** * Returns the meta data of the element to be scheduled. * @return the meta data of the element to be scheduled. */ M getMetaData(); @Override default Void execute(CacheEntryScheduler<I, M> scheduler) throws Exception { I id = this.getId(); M metaData = this.getMetaData(); if (metaData != null) { scheduler.schedule(id, metaData); } else { scheduler.schedule(id); } return null; } }
1,944
33.122807
89
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/scheduler/ScheduleLocalKeysTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.scheduler; import java.util.Iterator; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Stream; import org.infinispan.Cache; import org.infinispan.context.Flag; import org.wildfly.clustering.ee.Key; import org.wildfly.clustering.infinispan.distribution.Locality; /** * A task which schedules newly owned keys. * @author Paul Ferraro * @param <I> identifier type * @param <K> cache key type */ public class ScheduleLocalKeysTask<I, K extends Key<I>> implements BiConsumer<Locality, Locality> { private final Cache<K, ?> cache; private final Predicate<? super K> filter; private final Consumer<I> scheduleTask; public ScheduleLocalKeysTask(Cache<K, ?> cache, Predicate<? super K> filter, CacheEntryScheduler<I, ?> scheduler) { this(cache, filter, scheduler::schedule); } public ScheduleLocalKeysTask(Cache<K, ?> cache, Predicate<? super K> filter, Consumer<I> scheduleTask) { this.cache = cache; this.filter = filter; this.scheduleTask = scheduleTask; } @Override public void accept(Locality oldLocality, Locality newLocality) { // Iterate over local keys, including any cache stores to include entries that may be passivated/invalidated try (Stream<K> stream = this.cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).keySet().stream().filter(this.filter)) { Iterator<K> keys = stream.iterator(); while (keys.hasNext()) { if (Thread.currentThread().isInterrupted()) break; K key = keys.next(); // If we are the new primary owner of this entry then schedule it locally if (!oldLocality.isLocal(key) && newLocality.isLocal(key)) { this.scheduleTask.accept(key.getId()); } } } } }
2,979
40.388889
135
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/logging/Logger.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.logging; import static org.jboss.logging.Logger.Level.INFO; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * Logger for the org.wildfly.clustering.ee.infinispan module. * @author Paul Ferraro */ @MessageLogger(projectCode = "WFLYCLEEINF", length = 4) public interface Logger extends BasicLogger { String ROOT_LOGGER_CATEGORY = "org.wildfly.clustering.ee.infinispan"; Logger ROOT_LOGGER = org.jboss.logging.Logger.getMessageLogger(Logger.class, ROOT_LOGGER_CATEGORY); @LogMessage(level = INFO) @Message(id = 1, value = "Failed to cancel %s on primary owner.") void failedToCancel(@Cause Throwable cause, Object id); @LogMessage(level = INFO) @Message(id = 2, value = "Failed to schedule %s on primary owner.") void failedToSchedule(@Cause Throwable cause, Object id); }
2,064
40.3
103
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/retry/RetryingInvoker.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.retry; import java.time.Duration; import java.util.LinkedList; import java.util.List; import org.infinispan.Cache; import org.infinispan.configuration.cache.Configuration; /** * Retrying invoker whose retry intervals are auto-generated based an Infinispan cache configuration. * @author Paul Ferraro */ public class RetryingInvoker extends org.wildfly.clustering.ee.cache.retry.RetryingInvoker { public RetryingInvoker(Cache<?, ?> cache) { super(calculateRetryIntervals(cache.getCacheConfiguration())); } private static List<Duration> calculateRetryIntervals(Configuration config) { long timeout = config.locking().lockAcquisitionTimeout(); List<Duration> intervals = new LinkedList<>(); // Generate exponential back-off intervals for (long interval = timeout; interval > 1; interval /= 10) { intervals.add(0, Duration.ofMillis(interval)); } intervals.add(0, Duration.ZERO); return intervals; } }
2,066
38
101
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/tx/InfinispanBatcher.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.tx; import org.infinispan.Cache; import org.infinispan.commons.CacheException; import org.wildfly.clustering.ee.cache.tx.TransactionalBatcher; /** * @author Paul Ferraro */ public class InfinispanBatcher extends TransactionalBatcher<CacheException> { public InfinispanBatcher(Cache<?, ?> cache) { super(cache.getAdvancedCache().getTransactionManager(), CacheException::new); } }
1,469
37.684211
85
java
null
wildfly-main/clustering/ee/infinispan/src/main/java/org/wildfly/clustering/ee/infinispan/affinity/AffinityIdentifierFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.clustering.ee.infinispan.affinity; import java.util.function.Supplier; import org.infinispan.Cache; import org.infinispan.affinity.KeyAffinityService; import org.infinispan.affinity.KeyGenerator; import org.infinispan.remoting.transport.Address; import org.wildfly.clustering.ee.Key; import org.wildfly.clustering.ee.cache.IdentifierFactory; import org.wildfly.clustering.ee.infinispan.GroupedKey; import org.wildfly.clustering.infinispan.affinity.KeyAffinityServiceFactory; /** * An {@link IdentifierFactory} that uses a {@link KeyAffinityService} to pre-generate locally hashing identifiers from a supplier. * @author Paul Ferraro * @param <I> the identifier type */ public class AffinityIdentifierFactory<I> implements IdentifierFactory<I>, KeyGenerator<Key<I>> { private final Supplier<I> factory; private final KeyAffinityService<? extends Key<I>> affinity; private final Address localAddress; public AffinityIdentifierFactory(Supplier<I> factory, Cache<? extends Key<I>, ?> cache, KeyAffinityServiceFactory affinityFactory) { this.factory = factory; this.affinity = affinityFactory.createService(cache, this); this.localAddress = cache.getCacheManager().getAddress(); } @Override public I get() { return this.affinity.getKeyForAddress(this.localAddress).getId(); } @Override public Key<I> getKey() { return new GroupedKey<>(this.factory.get()); } @Override public void start() { this.affinity.start(); } @Override public void stop() { this.affinity.stop(); } }
2,647
35.777778
136
java
null
wildfly-main/testsuite/layers-expansion/src/test/java/org/jboss/as/test/layers/expansion/LayersTestCase.java
/* * Copyright 2023 Red Hat, Inc. and/or its affiliates * and other 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.jboss.as.test.layers.expansion; import org.jboss.as.test.shared.LayersTestBase; public class LayersTestCase extends LayersTestBase { // Currently we get all functionality from the superclass; this class is just so surefire has something to run // in this testsuite module }
973
37.96
114
java
null
wildfly-main/testsuite/preview/basic/src/test/java/org/wildfly/test/preview/util/TestsuiteModuleTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022 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.test.preview.util; import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; /** * Non-functional test only used to validate the pom setup of this testsuite module. */ @RunWith(Arquillian.class) @RunAsClient public class TestsuiteModuleTestCase { @Deployment(name = "empty") public static JavaArchive getDeployment() { JavaArchive archive = ShrinkWrap.create(JavaArchive.class, TestsuiteModuleTestCase.class.getSimpleName() + ".jar"); // meaningless content just to put something in the jar archive.addAsManifestResource(createPermissionsXmlAsset(new RuntimePermission("getenv.*")), "permissions.xml"); return archive; } @Test public void fakeTest() { Assume.assumeTrue("Not a real test", false); } }
1,888
36.039216
123
java
null
wildfly-main/testsuite/preview/basic/src/test/java/org/wildfly/test/preview/hibernate/search/coordination/SearchBean.java
/* * * * JBoss, Home of Professional Open Source. * * Copyright $year 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.test.preview.hibernate.search.coordination; import jakarta.enterprise.context.ApplicationScoped; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.transaction.Transactional; import org.hibernate.search.mapper.orm.Search; import java.util.List; @ApplicationScoped @Transactional public class SearchBean { @PersistenceContext EntityManager em; @SuppressWarnings("unchecked") public List<String> findAgentNames() { return em.createNativeQuery("select name from HSEARCH_AGENT") .getResultList(); } public void create(String text) { IndexedEntity entity = new IndexedEntity(); entity.text = text; em.persist(entity); } public List<IndexedEntity> search(String keyword) { return Search.session(em).search(IndexedEntity.class) .where(f -> f.match().field("text").matching(keyword)) .fetchAllHits(); } }
1,761
30.464286
78
java
null
wildfly-main/testsuite/preview/basic/src/test/java/org/wildfly/test/preview/hibernate/search/coordination/HibernateSearchOutboxPollingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.test.preview.hibernate.search.coordination; import jakarta.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.shared.TimeoutUtil; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.descriptor.api.Descriptors; import org.jboss.shrinkwrap.descriptor.api.persistence20.PersistenceDescriptor; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; /** * Test the ability for applications to use outbox-polling coordination, * provided they add the appropriate module dependency, * because that feature is still considered incubating and thus not included in WildFly "standard" (only in "preview"). * * This test relies on a Lucene backend because it simpler to set up (no need for an Elasticsearch container), * but users would generally rely on an Elasticsearch backend (because they have multiple instances of their application, * and thus can't just rely on the filesystem for index storage). */ @RunWith(Arquillian.class) public class HibernateSearchOutboxPollingTestCase { @BeforeClass public static void securityManagerNotSupportedInHibernateSearch() { AssumeTestGroupUtil.assumeSecurityManagerDisabled(); } @Deployment public static Archive<?> createTestArchive() { // TODO maybe just use managed=false and deploy in the @BeforeClass / undeploy in an @AfterClass if (AssumeTestGroupUtil.isSecurityManagerEnabled()) { return AssumeTestGroupUtil.emptyWar(HibernateSearchOutboxPollingTestCase.class.getSimpleName()); } return ShrinkWrap.create(WebArchive.class, HibernateSearchOutboxPollingTestCase.class.getSimpleName() + ".war") .addClass(HibernateSearchOutboxPollingTestCase.class) .addClasses(SearchBean.class, IndexedEntity.class, TimeoutUtil.class) .addAsResource(persistenceXml(), "META-INF/persistence.xml") .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); } private static Asset persistenceXml() { String persistenceXml = Descriptors.create(PersistenceDescriptor.class) .version("2.0") .createPersistenceUnit() .name("primary") .jtaDataSource("java:jboss/datasources/ExampleDS") .getOrCreateProperties() .createProperty().name("hibernate.hbm2ddl.auto").value("create-drop").up() .createProperty().name("hibernate.search.schema_management.strategy").value("drop-and-create-and-drop").up() .createProperty().name("hibernate.search.backend.type").value("lucene").up() .createProperty().name("hibernate.search.backend.lucene_version").value("LUCENE_CURRENT").up() .createProperty().name("hibernate.search.backend.directory.type").value("local-heap").up() .createProperty().name("hibernate.search.coordination.strategy").value("outbox-polling").up() .up().up() .exportAsString(); return new StringAsset(persistenceXml); } @Inject private SearchBean searchBean; @Test public void test() throws InterruptedException { // Check that we ARE using outbox-polling coordination awaitAssertion(() -> assertEquals(1, searchBean.findAgentNames().size())); // Check that indexing through the outbox works correctly assertEquals(0, searchBean.search("mytoken").size()); searchBean.create("This is MYToken"); awaitAssertion(() -> assertEquals(1, searchBean.search("mytoken").size())); } private static void awaitAssertion(Runnable assertion) throws InterruptedException { long end = System.currentTimeMillis() + TimeoutUtil.adjust(5000); AssertionError lastError; do { try { assertion.run(); return; // The assertion passed } catch (AssertionError e) { lastError = e; } Thread.sleep(100); } while (System.currentTimeMillis() < end); throw lastError; } }
5,594
43.76
124
java
null
wildfly-main/testsuite/preview/basic/src/test/java/org/wildfly/test/preview/hibernate/search/coordination/IndexedEntity.java
/* * * * JBoss, Home of Professional Open Source. * * Copyright $year 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.test.preview.hibernate.search.coordination; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.FullTextField; import org.hibernate.search.mapper.pojo.mapping.definition.annotation.Indexed; @Entity @Indexed public class IndexedEntity { @Id @GeneratedValue Long id; @FullTextField String text; }
1,227
28.95122
84
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/CliUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import java.io.File; import java.util.Objects; /** * CLI helper methods. * * @author Josef Cacek */ public class CliUtils { /** * Escapes given path String for CLI. * * @param path path string to escape (must be not-<code>null</code>) * @return escaped path */ public static String escapePath(String path) { return Objects.requireNonNull(path, "Path to escape can't be null.").replace("\\", "\\\\"); } /** * Returns escaped absolute path of given File instance. * * @param file instance to get the path from (must be not-<code>null</code>) * @return escaped absolute path */ public static String asAbsolutePath(File file) { return escapePath(Objects.requireNonNull(file, "File can't be null.").getAbsolutePath()); } }
1,873
33.703704
99
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/SnapshotRestoreSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import java.util.HashMap; import java.util.Map; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; /** * ServerSetupTask that takes a snapshot when the test starts, and then restores it at the end * <p> * If this setup task is in use it should be the first setup task in the task list, as otherwise the snapshot * will have changes from the previous setup task. * <p> * It can either be used standalone or via inheritance. */ public class SnapshotRestoreSetupTask implements ServerSetupTask { /** * This is a map rather than just a field to allow this to be used in multi server test suites */ private final Map<String, AutoCloseable> snapshots = new HashMap<>(); @Override public final void setup(ManagementClient managementClient, String containerId) throws Exception { snapshots.put(containerId, ServerSnapshot.takeSnapshot(managementClient)); doSetup(managementClient, containerId); } protected void doSetup(ManagementClient client, String containerId) throws Exception { } @Override public final void tearDown(ManagementClient managementClient, String containerId) throws Exception { AutoCloseable snapshot = snapshots.remove(containerId); if (snapshot != null) { snapshot.close(); } nonManagementCleanUp(); } protected void nonManagementCleanUp() throws Exception { } }
2,520
37.19697
109
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/SecurityManagerFailure.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import org.junit.Assume; /** * Utility class to disable tests failing when Security Manager is enabled. * * Important note: this should be used only in cases when tests are failing due to a thirdparty issues which are * unlikely to get fixed, e.g. WFLY-6192. * * @author Ivo Studensky */ public final class SecurityManagerFailure { /** * This method can be used to disable tests that are failing when being run under Security Manager. * * The purpose to calling this method (as opposed to providing additional permissions which might hide the * actual problem permanently) is to be able to enable or disable the test based on the presence * of the {@code jboss.test.enableTestsFailingUnderSM} system property. * * To run tests disabled by this method, you must add {@code -Djboss.test.enableTestsFailingUnderSM} argument * to the JVM running the tests. * * @param message an optional description about disabling this test (e.g. it can contain a WFLY issue). */ public static void thisTestIsFailingUnderSM(String message) { final SecurityManager sm = System.getSecurityManager(); final boolean securityManagerEnabled = System.getProperty("security.manager") != null; // either System.getSecurityManager is not null or system property 'security.manager' is set (in cases of RunAsClient) if (sm != null || securityManagerEnabled) { final boolean enableTest = System.getProperty("jboss.test.enableTestsFailingUnderSM") != null; Assume.assumeTrue(message, enableTest); } } /** * @see #thisTestIsFailingUnderSM(String) */ public static void thisTestIsFailingUnderSM() { thisTestIsFailingUnderSM(""); } }
2,829
41.238806
126
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/ResourceListingUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.jboss.logging.Logger; import org.jboss.modules.ModuleClassLoader; import org.jboss.modules.Resource; /** * @author: rhatlapa@redhat.com */ public class ResourceListingUtils { private static final Logger log = Logger.getLogger(ResourceListingUtils.class); /** * Lists resources in deployment using provided API for iterating resources * * @param classLoader the deployment class loader * @param rootDir directory which should be considered as root * @param recursive if true also a recursive resources are taken into account, otherwise only resources in rootDir are considered * @return list of resources returned by the API for iterating over deployment resources */ public static List<String> listResources(ModuleClassLoader classLoader, String rootDir, boolean recursive) { List<String> resourceList = new ArrayList<>(); Iterator<Resource> it = classLoader.iterateResources(rootDir, recursive); while (it.hasNext()) { resourceList.add(it.next().getName()); } return resourceList; } /** * translates path to class in package notation to standard path notation with addition of .class suffix * * @param clazz class in package notation * @return path representation of class */ public static String classToPath(Class clazz) { return clazz.getName().replaceAll("\\.", "/") + ".class"; } /** * Filters resources in collection using specified parameters * * @param resources collection to be filtered * @param rootDir what is the root directory of resources which should be taken into account * @param removeRecursive if recursive resources should be removed or not (true means recursive resources are removed, false means that they are preserved) */ public static void filterResources(Collection<String> resources, String rootDir, boolean removeRecursive) { String rootDirPrefix = ""; if (rootDir.startsWith("/")) { rootDirPrefix = rootDir.substring(1); } Iterator<String> it = resources.iterator(); while (it.hasNext()) { String resource = it.next(); if (resource.startsWith(rootDirPrefix)) { // the rootDir needs to be removed from name for deciding if it is an recursive resource or not if (removeRecursive) { String resourceWithoutPrefix = resource.substring(rootDirPrefix.length()); if (resourceWithoutPrefix.startsWith("/")) { resourceWithoutPrefix = resourceWithoutPrefix.substring(1); } log.trace("Original resource to check = " + resource); log.trace("Resource without its rootDir = " + resourceWithoutPrefix); if (resourceWithoutPrefix.contains("/")) { it.remove(); } } } else { it.remove(); } } } }
4,265
39.628571
159
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/LayersTestBase.java
/* * * * JBoss, Home of Professional Open Source. * * Copyright 2023 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.jboss.as.test.shared; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.jboss.as.test.layers.LayersTest; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public class LayersTestBase { // Packages that are provisioned by the test-standalone-reference installation // but not used in the test-all-layers installation. // This is the expected set of not provisioned modules when all layers are provisioned. private static final String[] NOT_USED_COMMON = { // not used "ibm.jdk", "javax.api", "javax.sql.api", "javax.xml.stream.api", "sun.jdk", "sun.scripting", // test-all-layers installation is non-ha and does not include layers that provide jgroups "org.jboss.as.clustering.jgroups", // TODO we need to add an agroal layer "org.wildfly.extension.datasources-agroal", "io.agroal", // Legacy subsystems for which we will not provide layers "org.wildfly.extension.picketlink", "org.jboss.as.jsr77", "org.keycloak.keycloak-adapter-subsystem", "org.jboss.as.security", // end legacy subsystems ^^^ // TODO nothing references this "org.wildfly.security.http.sfbasic", // TODO move eclipse link support to an external feature pack "org.eclipse.persistence", // RA not associated with any layer "org.jboss.genericjms", // Appclient support is not provided by a layer "org.jboss.as.appclient", "org.jboss.metadata.appclient", // TODO WFLY-16576 -- cruft? "org.bouncycastle", // This was brought in as part an RFE, WFLY-10632 & WFLY-10636. While the module is currently marked as private, // for now we should keep this module. "org.jboss.resteasy.resteasy-rxjava2", "org.jboss.resteasy.resteasy-tracing-api", // TODO these implement SPIs from RESTEasy or JBoss WS but I don't know how they integrate // as there is no ref to them in any module.xml nor any in WF java code. // Perhaps via deployment descriptor? In any case, no layer provides them "org.wildfly.security.jakarta.client.resteasy", "org.wildfly.security.jakarta.client.webservices", // This is added in the jaxrs subsystem to deployments if the MP config capability is met. The package is // added in the microprofile-rest-client as well. "org.jboss.resteasy.microprofile.config", // Alternative messaging protocols besides the std Artemis core protocol // Use of these depends on an attribute value setting "org.apache.activemq.artemis.protocol.amqp", "org.apache.qpid.proton", "org.apache.activemq.artemis.protocol.hornetq", "org.apache.activemq.artemis.protocol.stomp", // Legacy client not associated with any layer "org.hornetq.client", // TODO we need to add an rts layer "org.wildfly.extension.rts", "org.jboss.narayana.rts", // TODO we need to add an xts layer "org.jboss.as.xts", // TODO we need to add the elytron-oidc-client layer to the config "org.wildfly.extension.elytron-oidc-client", "org.wildfly.security.elytron-http-oidc", "org.wildfly.security.elytron-jose-jwk", "org.wildfly.security.elytron-jose-util", // TODO WFLY-16586 microprofile-reactive-streams-operators layer should provision this "org.wildfly.reactive.dep.jts", // TODO should an undertow layer specify this? "org.wildfly.event.logger", // TODO test-all-layers uses microprofile-opentracing instead of opentelemetry "org.wildfly.extension.opentelemetry", "org.wildfly.extension.opentelemetry-api", "io.opentelemetry.exporter", "io.opentelemetry.sdk", "io.opentelemetry.proto", "io.opentelemetry.otlp", "io.opentelemetry.trace", // Micrometer is not included in standard configs "io.micrometer", "org.wildfly.extension.micrometer", "org.wildfly.micrometer.deployment", "com.squareup.okhttp3", "org.jetbrains.kotlin.kotlin-stdlib", "com.google.protobuf", // Unreferenced Infinispan modules "org.infinispan.cdi.common", "org.infinispan.cdi.embedded", "org.infinispan.cdi.remote", "org.infinispan.counter", "org.infinispan.lock", "org.infinispan.query", "org.infinispan.query.core", // JGroups external protocols - AWS "org.jgroups.aws", "software.amazon.awssdk.s3", // MicroProfile "org.wildfly.extension.microprofile.metrics-smallrye", "org.wildfly.extension.microprofile.opentracing-smallrye", }; private static final String[] NOT_USED; // Packages that are not referenced from the module graph but needed. // This is the expected set of un-referenced modules found when scanning // the default configuration. private static final String[] NOT_REFERENCED_COMMON = { // injected by ee "org.eclipse.yasson", // injected by ee "org.wildfly.naming", // Injected by jaxrs "org.jboss.resteasy.resteasy-json-binding-provider", // The console ui content is not part of the kernel nor is it provided by an extension "org.jboss.as.console", // tooling "org.jboss.as.domain-add-user", // injected by server in UndertowHttpManagementService "org.jboss.as.domain-http-error-context", // injected by jsf "org.jboss.as.jsf-injection", // Brought by galleon FP config "org.jboss.as.product", // Brought by galleon FP config "org.jboss.as.standalone", // injected by logging "org.jboss.logging.jul-to-slf4j-stub", "org.jboss.resteasy.resteasy-client-microprofile", // Webservices tooling "org.jboss.ws.tools.common", "org.jboss.ws.tools.wsconsume", "org.jboss.ws.tools.wsprovide", "gnu.getopt", // Elytron tooling "org.wildfly.security.elytron-tool", // bootable jar runtime "org.wildfly.bootable-jar", // Extension not included in the default config "org.wildfly.extension.clustering.singleton", // Extension not included in the default config "org.wildfly.extension.microprofile.health-smallrye", "org.eclipse.microprofile.health.api", "io.smallrye.health", // Extension not included in the default config "org.wildfly.extension.microprofile.lra-coordinator", "org.wildfly.extension.microprofile.lra-participant", "org.jboss.narayana.rts.lra-coordinator", "org.jboss.narayana.rts.lra-participant", "org.eclipse.microprofile.lra.api", // Extension not included in the default config "org.wildfly.extension.microprofile.openapi-smallrye", "org.eclipse.microprofile.openapi.api", "io.smallrye.openapi", "com.fasterxml.jackson.dataformat.jackson-dataformat-yaml", // Extension not included in the default config "org.wildfly.extension.microprofile.reactive-messaging-smallrye", // Extension not included in the default config "org.wildfly.extension.microprofile.telemetry", // Extension not included in the default config "org.wildfly.extension.microprofile.reactive-streams-operators-smallrye", "org.wildfly.reactive.mutiny.reactive-streams-operators.cdi-provider", "io.vertx.client", // Dynamically added by ee-security and mp-jwt-smallrye DUPs but not referenced by subsystems. "org.wildfly.security.jakarta.security", // injected by sar "org.jboss.as.system-jmx", // Loaded reflectively by the jboss fork impl of jakarta.xml.soap.FactoryFinder "org.jboss.ws.saaj-impl", // TODO just a testsuite utility https://wildfly.zulipchat.com/#narrow/stream/174184-wildfly-developers/topic/org.2Ejboss.2Ews.2Ecxf.2Ests.20module "org.jboss.ws.cxf.sts", }; private static final String[] NOT_REFERENCED; /** * A HashMap to configure a banned module. * They key is the banned module name, the value is an optional List with the installation names that are allowed to * provision the banned module. This installations will be ignored. * * Notice the allowed installation names does not distinguish between different parent names, e.g test-all-layers here means * allowing root/test-all-layers and servletRoot/test-all-layers. */ private static final HashMap<String, List<String>> BANNED_MODULES_CONF = new HashMap<String, List<String>>(){{ put("org.jboss.as.security", Arrays.asList("test-all-layers-jpa-distributed", "test-all-layers", "legacy-security", "test-standalone-reference")); }}; static { if (AssumeTestGroupUtil.isWildFlyPreview()) { NOT_USED = ArrayUtils.addAll( NOT_USED_COMMON, // WFP standard config uses Micrometer instead of WF Metrics "org.wildfly.extension.metrics", // MP Fault Tolerance has a dependency on MP Metrics "io.smallrye.fault-tolerance", "org.eclipse.microprofile.fault-tolerance.api", "org.wildfly.extension.microprofile.fault-tolerance-smallrye", "org.wildfly.microprofile.fault-tolerance-smallrye.deployment", // Used by Hibernate Search but only in preview TODO this doesn't seem right; NOT_REFERENCED should suffice "org.hibernate.search.mapper.orm.coordination.outboxpolling" ); NOT_REFERENCED = ArrayUtils.addAll( NOT_REFERENCED_COMMON, "org.wildfly.extension.metrics", // Used by the hibernate search that's injected by jpa "org.hibernate.search.mapper.orm.coordination.outboxpolling" ); } else { NOT_USED = ArrayUtils.addAll( NOT_USED_COMMON, // Messaging broker not included in the messaging-activemq layer "org.jboss.xnio.netty.netty-xnio-transport", // No patching modules in layers "org.jboss.as.patching", "org.jboss.as.patching.cli", // Misc alternative variants of JPA things that we don't provide via layers "org.jboss.as.jpa.hibernate:4", "org.hibernate:5.0", "org.hibernate.jipijapa-hibernate5", "org.jboss.as.jpa.openjpa", "org.apache.openjpa", // TODO WFLY-16583 -- cruft "javax.management.j2ee.api", // Used by outboxpolling TODO this doesn't seem right "org.apache.avro" ); NOT_REFERENCED = ArrayUtils.addAll( NOT_REFERENCED_COMMON, // Standard configs don't include various MP subsystems "org.wildfly.extension.microprofile.fault-tolerance-smallrye", "io.jaegertracing", "io.netty.netty-codec-dns", "io.netty.netty-codec-http2", "io.netty.netty-resolver-dns", "io.reactivex.rxjava2.rxjava", "io.smallrye.common.vertx-context", "io.smallrye.reactive.messaging", "io.smallrye.reactive.messaging.connector", "io.smallrye.reactive.messaging.connector.kafka", "io.smallrye.reactive.messaging.connector.kafka.api", "io.smallrye.reactive.mutiny", "io.smallrye.reactive.mutiny.reactive-streams-operators", "io.smallrye.reactive.mutiny.vertx-core", "io.smallrye.reactive.mutiny.vertx-kafka-client", "io.smallrye.reactive.mutiny.vertx-runtime", "io.vertx.client.kafka", "io.vertx.core", "org.apache.kafka.client", "org.eclipse.microprofile.reactive-messaging.api", "org.eclipse.microprofile.reactive-streams-operators.api", "org.eclipse.microprofile.reactive-streams-operators.core", "org.wildfly.reactive.messaging.common", "org.wildfly.reactive.messaging.config", "org.wildfly.reactive.messaging.kafka", // injected by logging "org.apache.logging.log4j.api", // injected by logging "org.jboss.logmanager.log4j2", // "org.jboss.as.product:wildfly-web", // injected by ee "javax.json.bind.api", // injected by jpa "org.hibernate.search.orm", "org.hibernate.search.backend.elasticsearch", "org.hibernate.search.backend.lucene", // Used by the hibernate search that's injected by jpa "org.elasticsearch.client.rest-client", "com.google.code.gson", "com.carrotsearch.hppc", "org.apache.lucene", "org.apache.avro", // Brought by galleon ServerRootResourceDefinition "wildflyee.api" ); } } public static String root; public static String defaultConfigsRoot; @BeforeClass public static void setUp() { root = System.getProperty("layers.install.root"); defaultConfigsRoot = System.getProperty("std.default.install.root"); } @AfterClass public static void cleanUp() { Boolean delete = Boolean.getBoolean("layers.delete.installations"); if(delete) { File[] installations = new File(root).listFiles(File::isDirectory); for(File f : installations) { LayersTest.recursiveDelete(f.toPath()); } installations = new File(defaultConfigsRoot).listFiles(File::isDirectory); for(File f : installations) { LayersTest.recursiveDelete(f.toPath()); } } } @Test public void test() throws Exception { LayersTest.test(root, new HashSet<>(Arrays.asList(NOT_REFERENCED)), new HashSet<>(Arrays.asList(NOT_USED))); } @Test public void checkBannedModules() throws Exception { final HashMap<String, String> results = LayersTest.checkBannedModules(root, BANNED_MODULES_CONF); Assert.assertTrue("The following banned modules were provisioned " + results.toString(), results.isEmpty()); } @Test public void testDefaultConfigs() throws Exception { LayersTest.testExecution(defaultConfigsRoot); } }
16,810
47.031429
159
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/ManagementServerSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.function.Function; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandFormatException; import org.jboss.as.cli.batch.Batch; import org.jboss.as.cli.batch.BatchManager; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.test.integration.management.util.CLITestUtil; import org.jboss.dmr.ModelNode; /** * {@link ServerSetupTask} that runs a list of batchable management operations on a set of containers. * @author Paul Ferraro */ public class ManagementServerSetupTask implements ServerSetupTask { public interface ContainerSetConfiguration { /** * Returns the configuration for the specified container, or the default configuration. * @param container a container identifier * @return a container configuration */ ContainerConfiguration getContainerConfiguration(String container); } public interface ContainerConfiguration { /** * Returns the setup script for a container. * @return a list of CLI command batches */ List<List<String>> getSetupScript(); /** * Returns the tear-down script for a container. * @return a list of CLI command batches */ List<List<String>> getTearDownScript(); } public interface Builder<C> { /** * Builds this configuration. * @return the built configuration. */ C build(); } public interface ContainerSetConfigurationBuilder extends Builder<ContainerSetConfiguration> { /** * Adds a set of contains with the same configuration. * @param containers a set of container identifiers * @param configuration a container configuration * @return a reference to this builder */ ContainerSetConfigurationBuilder addContainers(Set<String> containers, ContainerConfiguration configuration); /** * Adds a container configuration. * @param container a container identifier * @param configuration a container configuration * @return a reference to this builder */ default ContainerSetConfigurationBuilder addContainer(String container, ContainerConfiguration configuration) { return this.addContainers(Set.of(container), configuration); } /** * Adds a container configuration. * @param container a container identifier * @param configuration a container configuration * @return a reference to this builder */ ContainerSetConfigurationBuilder defaultContainer(ContainerConfiguration configuration); } public interface ContainerConfigurationBuilder extends Builder<ContainerConfiguration> { /** * Defines a script to run during test setup. * @param script a list of CLI batches * @return a reference to this builder */ ContainerConfigurationBuilder setupScript(List<List<String>> script); /** * Defines a script to run during test tear-down. * @param script a list of CLI batches * @return a reference to this builder */ ContainerConfigurationBuilder tearDownScript(List<List<String>> script); } public interface CommandSet<B> { /** * Adds the specified command to the associated set. * @param command a CLI command * @return a reference to this builder */ B add(String command); /** * Adds the specified parameterized command to the associated set. * @param command a CLI command * @return a reference to this builder */ default B add(String pattern, Object... params) { return this.add(String.format(Locale.ROOT, pattern, params)); } } public interface ScriptBuilder extends Builder<List<List<String>>>, CommandSet<ScriptBuilder> { /** * Starts a batch of operations. * @return a reference to the batch builder. */ BatchBuilder startBatch(); } public interface BatchBuilder extends CommandSet<BatchBuilder> { /** * Ends a batch of operations. * @return a reference to the script builder. */ ScriptBuilder endBatch(); } /** * Create a new builder for a set of container configurations. * @return a new builder */ public static ContainerSetConfigurationBuilder createContainerSetConfigurationBuilder() { return new ContainerSetConfigurationBuilder() { private final Map<String, ContainerConfiguration> containers = new HashMap<>(); private ContainerConfiguration defaultContainer = null; @Override public ContainerSetConfigurationBuilder addContainers(Set<String> containers, ContainerConfiguration configuration) { for (String container : containers) { this.containers.put(container, configuration); } return this; } @Override public ContainerSetConfigurationBuilder defaultContainer(ContainerConfiguration configuration) { this.defaultContainer = configuration; return this; } @Override public ContainerSetConfiguration build() { Map<String, ContainerConfiguration> containers = this.containers; ContainerConfiguration defaultConfig = this.defaultContainer; return new ContainerSetConfiguration() { @Override public ContainerConfiguration getContainerConfiguration(String container) { return containers.getOrDefault(container, defaultConfig); } }; } }; } /** * Create a new builder for a container configuration. * @return a new builder */ public static ContainerConfigurationBuilder createContainerConfigurationBuilder() { return new ContainerConfigurationBuilder() { private List<List<String>> setupScript = List.of(); private List<List<String>> tearDownScript = List.of(); @Override public ContainerConfigurationBuilder setupScript(List<List<String>> batches) { this.setupScript = batches; return this; } @Override public ContainerConfigurationBuilder tearDownScript(List<List<String>> batches) { this.tearDownScript = batches; return this; } @Override public ContainerConfiguration build() { List<List<String>> setupScript = Collections.unmodifiableList(this.setupScript); List<List<String>> tearDownScript = Collections.unmodifiableList(this.tearDownScript); return new ContainerConfiguration() { @Override public List<List<String>> getSetupScript() { return setupScript; } @Override public List<List<String>> getTearDownScript() { return tearDownScript; } }; } }; } /** * Create a new builder for a script. * @return a new builder */ public static ScriptBuilder createScriptBuilder() { return new ScriptBuilder() { private List<List<String>> batches = new LinkedList<>(); @Override public List<List<String>> build() { return Collections.unmodifiableList(this.batches); } @Override public ScriptBuilder add(String command) { this.batches.add(List.of(command)); return this; } @Override public BatchBuilder startBatch() { ScriptBuilder builder = this; List<String> batch = new LinkedList<>(); this.batches.add(batch); return new BatchBuilder() { @Override public BatchBuilder add(String command) { batch.add(command); return this; } @Override public ScriptBuilder endBatch() { return builder; } }; } }; } private final ContainerSetConfiguration config; public ManagementServerSetupTask(ContainerSetConfiguration config) { this.config = config; } public ManagementServerSetupTask(ContainerConfiguration defaultConfig) { this(createContainerSetConfigurationBuilder().defaultContainer(defaultConfig).build()); } public ManagementServerSetupTask(String container, ContainerConfiguration config) { this(createContainerSetConfigurationBuilder().addContainer(container, config).build()); } public ManagementServerSetupTask(Set<String> containers, ContainerConfiguration config) { this(createContainerSetConfigurationBuilder().addContainers(containers, config).build()); } @Override public void setup(ManagementClient client, String containerId) throws Exception { this.configure(client, containerId, ContainerConfiguration::getSetupScript); } @Override public void tearDown(ManagementClient client, String containerId) throws Exception { this.configure(client, containerId, ContainerConfiguration::getTearDownScript); } private void configure(ManagementClient client, String containerId, Function<ContainerConfiguration, List<List<String>>> script) throws Exception { ContainerConfiguration config = this.config.getContainerConfiguration(containerId); if (config != null) { List<List<String>> batches = script.apply(config); if (!batches.isEmpty()) { CommandContext context = CLITestUtil.getCommandContext(); context.connectController(); for (List<String> batch : batches) { if (!batch.isEmpty()) { ModelNode model = createCommandModel(context, batch); ModelNode result = client.getControllerClient().execute(model); if (result.get(ClientConstants.OUTCOME).asString().equals(ClientConstants.FAILED)) { throw new RuntimeException(model.toJSONString(true) + ": " + result.get(ClientConstants.FAILURE_DESCRIPTION).toString()); } } } ServerReload.reloadIfRequired(client); } } } private static ModelNode createCommandModel(CommandContext context, List<String> commands) throws CommandFormatException { if (commands.size() == 1) { // Single commands do not need a batch return context.buildRequest(commands.get(0)); } BatchManager manager = context.getBatchManager(); manager.activateNewBatch(); Batch batch = manager.getActiveBatch(); for (String command : commands) { batch.add(context.toBatchedCommand(command)); } return batch.toRequest(); } }
12,882
36.669591
151
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/RetryTaskExecutor.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; /** * * @author Dominik Pospisil <dpospisi@redhat.com> */ public class RetryTaskExecutor<T> { private static final long DEFAULT_RETRY_DELAY = 1000; private static final int DEFAULT_RETRY_COUNT = 60; private Callable<T> task; public final T retryTask(Callable<T> task) throws TimeoutException { return retryTask(task, DEFAULT_RETRY_COUNT, DEFAULT_RETRY_DELAY); } public final T retryTask(Callable<T> task, int retryCount, long retryDelay) throws TimeoutException { while(retryCount > 0) { try { return task.call(); } catch (Exception e) { } retryCount --; try { Thread.sleep(retryDelay); } catch (InterruptedException ioe) {} } throw new TimeoutException(); } }
1,978
32.542373
105
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/SnapshotRestoreArchiveAppender.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import org.jboss.arquillian.container.test.spi.client.deployment.CachedAuxilliaryArchiveAppender; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; class SnapshotRestoreArchiveAppender extends CachedAuxilliaryArchiveAppender { @Override protected Archive<?> buildArchive() { return ShrinkWrap .create(JavaArchive.class, "wildfly-snapshot-restore.jar") .addClasses(ServerReload.class, ServerSnapshot.class, SnapshotRestoreSetupTask.class); } }
1,631
45.628571
102
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/CLIServerSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import static org.jboss.as.test.shared.ManagementServerSetupTask.createContainerConfigurationBuilder; import static org.jboss.as.test.shared.ManagementServerSetupTask.createScriptBuilder; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Stream; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.test.shared.ManagementServerSetupTask.CommandSet; import org.jboss.as.test.shared.ManagementServerSetupTask.ContainerConfiguration; import org.jboss.as.test.shared.ManagementServerSetupTask.ContainerConfigurationBuilder; import org.jboss.as.test.shared.ManagementServerSetupTask.ScriptBuilder; /** * Implementation of {@link ServerSetupTask} which runs provided CLI commands. Since the API is based around class instances, the extending * class implementations need to configure the {@link CLIServerSetupTask#builder}. * * @author Radoslav Husar * @deprecated Use {@link ManagementServerSetupTask} instead */ @Deprecated public class CLIServerSetupTask implements ServerSetupTask { protected final Builder builder = new Builder(); @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { new ManagementServerSetupTask(containerId, this.createContainerConfiguration(containerId, ContainerConfigurationBuilder::setupScript, NodeBuilder::getSetupCommands)).setup(managementClient, containerId); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { new ManagementServerSetupTask(containerId, this.createContainerConfiguration(containerId, ContainerConfigurationBuilder::tearDownScript, NodeBuilder::getTearDownCommands)).tearDown(managementClient, containerId); } private ContainerConfiguration createContainerConfiguration(String containerId, BiFunction<ContainerConfigurationBuilder, List<List<String>>, ContainerConfigurationBuilder> scriptFunction, Function<NodeBuilder, List<String>> batch) { ContainerConfigurationBuilder containerBuilder = createContainerConfigurationBuilder(); NodeBuilder builder = this.builder.configuration.get(containerId); if (builder != null) { ScriptBuilder scriptBuilder = createScriptBuilder(); CommandSet<?> commands = (builder.isBatched()) ? scriptBuilder.startBatch() : scriptBuilder; for (String command : batch.apply(builder)) { commands.add(command); } scriptFunction.apply(containerBuilder, scriptBuilder.build()); } return containerBuilder.build(); } public static class Builder { private final Map<String, NodeBuilder> configuration = new HashMap<>(); /** * Configure commands to be run for a specific node. Multiple calls to this method can be made to add more commands. * * @param node node to run setup and teardown commands on */ public NodeBuilder node(String node) { if (configuration.containsKey(node)) { return configuration.get(node); } NodeBuilder nodeBuilder = new NodeBuilder(this); configuration.put(node, nodeBuilder); return nodeBuilder; } /** * Configure commands to be run for a group of nodes. Cannot be called multiple times on nodes that already have some configuration * defined. Use {@link Builder#node(String)} for node-specific overrides. * * @param nodes nodes to run setup and teardown commands on */ public NodeBuilder node(String... nodes) { if (Stream.of(nodes).anyMatch(configuration::containsKey)) { throw new IllegalStateException("Node-specific overrides need to be done for per node."); } NodeBuilder nodeBuilder = new NodeBuilder(this); Stream.of(nodes).forEach(n -> this.configuration.put(n, nodeBuilder)); return nodeBuilder; } } public static class NodeBuilder { private final Builder parentBuilder; private final List<String> setupCommands = new LinkedList<>(); private final List<String> teardownCommands = new LinkedList<>(); private boolean batch = true; NodeBuilder(Builder parentBuilder) { this.parentBuilder = parentBuilder; } List<String> getSetupCommands() { return this.setupCommands; } List<String> getTearDownCommands() { return this.teardownCommands; } boolean isBatched() { return this.batch; } /** * Adds a single command to be run in setup phase. */ public NodeBuilder setup(String setupCommand) { setupCommands.add(setupCommand); return this; } /** * Adds a formatted single command to be run in setup phase. */ public NodeBuilder setup(String formatSetupCommand, Object... formatArguments) { return setup(String.format(formatSetupCommand, formatArguments)); } /** * Adds a single command to be run in teardown phase. */ public NodeBuilder teardown(String teardownCommand) { teardownCommands.add(teardownCommand); return this; } /** * Adds a single formatted command to be run in teardown phase. */ public NodeBuilder teardown(String formatTeardownCommand, Object... formatArguments) { return teardown(String.format(formatTeardownCommand, formatArguments)); } /** * Configure whether the commands should be run in a batch. Default configuration is to batch. */ public NodeBuilder batch(boolean batch) { this.batch = batch; return this; } /** * Configure whether to reload the server after setup if it's in a 'reload-required' state. */ public NodeBuilder reloadOnSetup(boolean reloadOnSetup) { return this; } /** * Configure whether to reload the server on teardown if it's in a 'reload-required' state. */ public NodeBuilder reloadOnTearDown(boolean reloadOnTearDown) { return this; } /** * Returns a reference to the parent builder to be used for chaining. */ public Builder parent() { return parentBuilder; } } }
7,816
39.293814
237
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/CdiUtils.java
/* * Copyright 2022 Red Hat, Inc. * * 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.jboss.as.test.shared; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.StringAsset; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public class CdiUtils { /** * Creates a {@code beans.xml} file which uses a {@code bean-discovery-mode} of "all". * * @return a {@code beans.xml} asset */ public static Asset createBeansXml() { return new StringAsset("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<beans xmlns=\"https://jakarta.ee/xml/ns/jakartaee\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd\"\n" + " version=\"3.0\" bean-discovery-mode=\"all\">\n" + "</beans>"); } }
1,517
36.02439
137
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/ServerSnapshot.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import static org.junit.Assert.fail; import java.io.File; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; /** * Class that can be used to take a restore server snapshots */ public class ServerSnapshot { /** * Takes a snapshot of the current state of the server. * * Returns a AutoCloseable that can be used to restore the server state * @param client The client * @return A closeable that can be used to restore the server */ public static AutoCloseable takeSnapshot(ManagementClient client) { try { ModelNode node = new ModelNode(); node.get(ModelDescriptionConstants.OP).set("take-snapshot"); ModelNode result = client.getControllerClient().execute(node); if (!"success".equals(result.get(ClientConstants.OUTCOME).asString())) { fail("Reload operation didn't finish successfully: " + result.asString()); } String snapshot = result.get(ModelDescriptionConstants.RESULT).asString(); final String fileName = snapshot.contains(File.separator) ? snapshot.substring(snapshot.lastIndexOf(File.separator) + 1) : snapshot; return new AutoCloseable() { @Override public void close() throws Exception { ServerReload.executeReloadAndWaitForCompletion(client, fileName); ModelNode node = new ModelNode(); node.get(ModelDescriptionConstants.OP).set("write-config"); ModelNode result = client.getControllerClient().execute(node); if (!"success".equals(result.get(ClientConstants.OUTCOME).asString())) { fail("Failed to write config after restoring from snapshot " + result.asString()); } } }; } catch (Exception e) { throw new RuntimeException("Failed to take snapshot", e); } } }
3,197
43.416667
144
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/PropertiesValueResolver.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import java.io.File; import java.util.Properties; /** * Parses a string and replaces any references to system properties or environment variables in the string * * @author Jaikiran Pai (copied from JBoss DMR project) * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public class PropertiesValueResolver { private static final int INITIAL = 0; private static final int GOT_DOLLAR = 1; private static final int GOT_OPEN_BRACE = 2; private static final int RESOLVED = 3; private static final int DEFAULT = 4; /** * Replace properties of the form: * <code>${<i>&lt;[env.]name&gt;[</i>,<i>&lt;[env.]name2&gt;[</i>,<i>&lt;[env.]name3&gt;...]][</i>:<i>&lt;default&gt;]</i>}</code> * * @param value - either a system property or environment variable reference * @return the value of the system property or environment variable referenced if * it exists */ public static String replaceProperties(final String value) { return replaceProperties(value, System.getProperties()); } /** * Replace properties of the form: * <code>${<i>&lt;[env.]name&gt;[</i>,<i>&lt;[env.]name2&gt;[</i>,<i>&lt;[env.]name3&gt;...]][</i>:<i>&lt;default&gt;]</i>}</code> * * @param value - either a system property or environment variable reference * @return the value of the system property or environment variable referenced if * it exists */ public static String replaceProperties(final String value, final Properties properties) { final StringBuilder builder = new StringBuilder(); final int len = value.length(); int state = INITIAL; int start = -1; int nameStart = -1; String resolvedValue = null; for (int i = 0; i < len; i = value.offsetByCodePoints(i, 1)) { final int ch = value.codePointAt(i); switch (state) { case INITIAL: { switch (ch) { case '$': { state = GOT_DOLLAR; continue; } default: { builder.appendCodePoint(ch); continue; } } // not reachable } case GOT_DOLLAR: { switch (ch) { case '$': { builder.appendCodePoint(ch); state = INITIAL; continue; } case '{': { start = i + 1; nameStart = start; state = GOT_OPEN_BRACE; continue; } default: { // invalid; emit and resume builder.append('$').appendCodePoint(ch); state = INITIAL; continue; } } // not reachable } case GOT_OPEN_BRACE: { switch (ch) { case ':': case '}': case ',': { final String name = value.substring(nameStart, i).trim(); if ("/".equals(name)) { builder.append(File.separator); state = ch == '}' ? INITIAL : RESOLVED; continue; } else if (":".equals(name)) { builder.append(File.pathSeparator); state = ch == '}' ? INITIAL : RESOLVED; continue; } // First check for system property, then env variable String val = (String) properties.get(name); if (val == null && name.startsWith("env.")) val = System.getenv(name.substring(4)); if (val != null) { builder.append(val); resolvedValue = val; state = ch == '}' ? INITIAL : RESOLVED; continue; } else if (ch == ',') { nameStart = i + 1; continue; } else if (ch == ':') { start = i + 1; state = DEFAULT; continue; } else { throw new IllegalStateException("Failed to resolve expression: " + value.substring(start - 2, i + 1)); } } default: { continue; } } // not reachable } case RESOLVED: { if (ch == '}') { state = INITIAL; } continue; } case DEFAULT: { if (ch == '}') { state = INITIAL; builder.append(value, start, i); } continue; } default: throw new IllegalStateException("Unexpected char seen: " + ch); } } switch (state) { case GOT_DOLLAR: { builder.append('$'); break; } case DEFAULT: { builder.append(value.substring(start - 2)); break; } case GOT_OPEN_BRACE: { // We had a reference that was not resolved, throw ISE if (resolvedValue == null) throw new IllegalStateException("Incomplete expression: " + builder.toString()); break; } } return builder.toString(); } }
7,512
39.610811
134
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/TestLogHandlerSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.shared.util.LoggingUtil; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; /** * Used to search for strings in logs, it adds a handler so the search is done on a small file * @author tmiyar * */ public abstract class TestLogHandlerSetupTask implements ServerSetupTask { private final Logger LOGGER = Logger.getLogger(TestLogHandlerSetupTask.class); private final Deque<ModelNode> removeOps = new ArrayDeque<>(); @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { final Operations.CompositeOperationBuilder builder = Operations.CompositeOperationBuilder.create(); //add handler final ModelNode handlerAddress = Operations.createAddress(SUBSYSTEM, "logging", "file-handler", getHandlerName()); ModelNode addTestLogOp = Operations.createAddOperation(handlerAddress); addTestLogOp.get("level").set(getLevel()); addTestLogOp.get("append").set("true"); addTestLogOp.get("encoding").set("UTF-8"); ModelNode file = new ModelNode(); file.get("relative-to").set("jboss.server.log.dir"); file.get("path").set(getLogFileName()); addTestLogOp.get("file").set(file); addTestLogOp.get("formatter").set("%-5p [%c] (%t) %s%e%n"); builder.addStep(addTestLogOp); removeOps.add(Operations.createRemoveOperation(handlerAddress)); //add category with new handler Collection<String> categories = getCategories(); if (categories == null || categories.isEmpty()) { LOGGER.warn("getCategories() returned empty collection."); return; } for (String category : categories) { if (category == null || category.isEmpty()) { LOGGER.warn("Empty category name provided."); continue; } final ModelNode loggerAddress = Operations.createAddress(SUBSYSTEM, "logging", "logger", category); ModelNode op = Operations.createAddOperation(loggerAddress); op.get("level").set(getLevel()); op.get("handlers").add(getHandlerName()); builder.addStep(op); removeOps.addFirst(Operations.createRemoveOperation(loggerAddress)); } applyUpdate(managementClient.getControllerClient(), builder.build(), false); } @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { Path logPath = LoggingUtil.getLogPath(managementClient, "file-handler", getHandlerName()); // Remove the loggers and handler final Operations.CompositeOperationBuilder builder = Operations.CompositeOperationBuilder.create(); ModelNode removeOp; while ((removeOp = removeOps.pollFirst()) != null) { builder.addStep(removeOp); } applyUpdate(managementClient.getControllerClient(), builder.build(), false); // remove file, note this needs to be done after the operations have been executed as we need to ensure that // no FD's are open. This can be an issue on Windows. Files.deleteIfExists(logPath); } public abstract Collection<String> getCategories(); public abstract String getLevel(); public abstract String getHandlerName(); public abstract String getLogFileName(); protected void applyUpdate(final ModelControllerClient client, ModelNode update, boolean allowFailure) throws IOException { applyUpdate(client, Operation.Factory.create(update), allowFailure); } private void applyUpdate(final ModelControllerClient client, Operation update, boolean allowFailure) throws IOException { ModelNode result = client.execute(update); if (!Operations.isSuccessfulOutcome(result)) { if (allowFailure) { LOGGER.tracef("Failed to configure logger: %s", Operations.getFailureDescription(result).asString()); } else { throw new RuntimeException("Failed to configure logger: " + Operations.getFailureDescription(result).asString()); } } else { LOGGER.trace(Operations.readResult(result).asString()); } } }
5,843
44.302326
129
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/SnapshotRestoreLoadableExtension.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender; import org.jboss.arquillian.core.spi.LoadableExtension; public class SnapshotRestoreLoadableExtension implements LoadableExtension { @Override public void register(ExtensionBuilder extensionBuilder) { extensionBuilder.service(AuxiliaryArchiveAppender.class, SnapshotRestoreArchiveAppender.class); } }
1,464
44.78125
103
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/IntermittentFailure.java
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import org.junit.Assume; /** * Utility class to disable (effectively @Ignore) intermittently failing tests unless explicitly enabled via a System property. * * @author <a href="http://jmesnil.net/">Jeff Mesnil</a> (c) 2015 Red Hat inc. */ public final class IntermittentFailure { /** * This method can be used to disable tests that are failing intermittently. * * The purpose to calling this method (as opposed to annotating tests with {@code @Ignore}) is to * be able to enable or disable the test based on the presence of the {@code jboss.test.enableIntermittentFailingTests} * System property. * * To run tests disabled by this method, you must add {@code -Djboss.test.enableIntermittentFailingTests} argument * to the JVM running the tests. * * @param message reason for disabling this test, typically specifying a tracking WFLY issue */ public static void thisTestIsFailingIntermittently(String message) { boolean enableTest = System.getProperty("jboss.test.enableIntermittentFailingTests") != null; Assume.assumeTrue(message, enableTest); } }
2,198
41.288462
127
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/ServerReload.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 2110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.READ_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS; import static org.junit.Assert.fail; import java.io.IOException; import java.net.UnknownHostException; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.dmr.ModelNode; import org.jboss.logging.Logger; import org.junit.Assert; import org.xnio.IoUtils; /** * Utilities for correctly reloading a server process. * @author Stuart Douglas */ public class ServerReload { private static final Logger log = Logger.getLogger(ServerReload.class); /** Default time in ms to wait for a server process to return to started state following a reload */ public static final int TIMEOUT = 100000; /** * @deprecated Use {@link #executeReloadAndWaitForCompletion(ManagementClient)} which will allow completion * waiting to check on the correct address for reload completion if the server is not using the * default management address or port */ @Deprecated public static void executeReloadAndWaitForCompletion(ModelControllerClient client) { executeReloadAndWaitForCompletion(client, TIMEOUT, false, null, -1, null); } /** * @deprecated Use {@link #executeReloadAndWaitForCompletion(ManagementClient String)} which will allow completion * waiting to check on the correct address for reload completion if the server is not using the * default management address or port */ @Deprecated public static void executeReloadAndWaitForCompletion(ModelControllerClient client, String serverConfig) { executeReloadAndWaitForCompletion(client, TIMEOUT, false, null, -1, serverConfig); } /** * @deprecated Use {@link #executeReloadAndWaitForCompletion(ManagementClient boolean)} which will allow completion * waiting to check on the correct address for reload completion if the server is not using the * default management address or port */ @Deprecated public static void executeReloadAndWaitForCompletion(ModelControllerClient client, boolean adminOnly) { executeReloadAndWaitForCompletion(client, TIMEOUT, adminOnly, null, -1, null); } /** * @deprecated Use {@link #executeReloadAndWaitForCompletion(ManagementClient int)} which will allow completion * waiting to check on the correct address for reload completion if the server is not using the * default management address or port */ @Deprecated public static void executeReloadAndWaitForCompletion(ModelControllerClient client, int timeout) { executeReloadAndWaitForCompletion(client, timeout, false, null, -1, null); } /** * Reload the server and wait for it to reach running state. Reloaded server will not be in admin-only mode. * * @param managementClient client to use to execute the reload and to provide host and port information for * reconnecting to wait for completion of the reload */ public static void executeReloadAndWaitForCompletion(ManagementClient managementClient) { executeReloadAndWaitForCompletion(managementClient.getControllerClient(), TIMEOUT, false, managementClient.getMgmtAddress(), managementClient.getMgmtPort(), null); } /** * Reload the server and wait for it to reach running state, instructing the server to use the configuration file * with the given name once it reloads. Reloaded server will not be in admin-only mode. * * @param managementClient client to use to execute the reload and to provide host and port information for * * reconnecting to wait for completion of the reload * @param serverConfig the configuration file the server should use following reload. May be {@code null} in which * case the server will use the same configuration file it used before the reload. */ public static void executeReloadAndWaitForCompletion(ManagementClient managementClient, String serverConfig) { executeReloadAndWaitForCompletion(managementClient.getControllerClient(), TIMEOUT, false, managementClient.getMgmtAddress(), managementClient.getMgmtPort(), serverConfig); } /** * Reload the server and wait for it to reach running state, optionally reloading into admin-only mode. * @param managementClient client to use to execute the reload and to provide host and port information for * reconnecting to wait for completion of the reload * @param adminOnly {@code} true if the server should be in admin-only mode following the reload */ public static void executeReloadAndWaitForCompletion(ManagementClient managementClient, boolean adminOnly) { executeReloadAndWaitForCompletion(managementClient.getControllerClient(), TIMEOUT, adminOnly, managementClient.getMgmtAddress(), managementClient.getMgmtPort(), null); } /** * Reload the server and wait for it to reach running state. Reloaded server will not be in admin-only mode. * * @param managementClient client to use to execute the reload and to provide host and port information for * * reconnecting to wait for completion of the reload * @param timeout time in ms to wait for a server process to return to running state following the reload */ public static void executeReloadAndWaitForCompletion(ManagementClient managementClient, int timeout) { executeReloadAndWaitForCompletion(managementClient.getControllerClient(), timeout, false, managementClient.getMgmtAddress(), managementClient.getMgmtPort(), null); } /** * * @param client client to use to instruct the server to reload * @param timeout time in ms to wait for a server process to return to running state following the reload * @param adminOnly if {@code true}, the server will be reloaded in admin-only mode * @param serverAddress if {@code null}, use {@code TestSuiteEnvironment.getServerAddress()} to create the ModelControllerClient * @param serverPort if {@code -1}, use {@code TestSuiteEnvironment.getServerPort()} to create the ModelControllerClient */ public static void executeReloadAndWaitForCompletion(ModelControllerClient client, int timeout, boolean adminOnly, String serverAddress, int serverPort) { executeReloadAndWaitForCompletion(client, timeout, adminOnly, serverAddress, serverPort, null); } /** * * @param client client to use to instruct the server to reload * @param timeout time in ms to wait for a server process to return to running state following the reload * @param adminOnly if {@code true}, the server will be reloaded in admin-only mode * @param serverAddress if {@code null}, use {@code TestSuiteEnvironment.getServerAddress()} to create the ModelControllerClient * @param serverPort if {@code -1}, use {@code TestSuiteEnvironment.getServerPort()} to create the ModelControllerClient */ public static void executeReloadAndWaitForCompletion(ModelControllerClient client, int timeout, boolean adminOnly, String serverAddress, int serverPort, String serverConfig) { executeReloadAndWaitForCompletion(client, timeout, adminOnly, false, serverAddress, serverPort, serverConfig); } /** * * @param client client to use to instruct the server to reload * @param timeout time in ms to wait for a server process to return to running state following the reload * @param adminOnly if {@code true}, the server will be reloaded in admin-only mode * @param startSuspended if {@code true}, the service will be reloaded in suspended state * @param serverAddress if {@code null}, use {@code TestSuiteEnvironment.getServerAddress()} to create the ModelControllerClient * @param serverPort if {@code -1}, use {@code TestSuiteEnvironment.getServerPort()} to create the ModelControllerClient */ public static void executeReloadAndWaitForCompletion(ModelControllerClient client, int timeout, boolean adminOnly, boolean startSuspended, String serverAddress, int serverPort, String serverConfig) { executeReload(client, adminOnly, startSuspended, serverConfig); waitForLiveServerToReload(timeout, serverAddress != null ? serverAddress : TestSuiteEnvironment.getServerAddress(), serverPort != -1 ? serverPort : TestSuiteEnvironment.getServerPort()); } private static void executeReload(ModelControllerClient client, boolean adminOnly, String serverConfig) { executeReload(client, adminOnly, false, serverConfig); } private static void executeReload(ModelControllerClient client, boolean adminOnly, boolean startSuspended, String serverConfig) { ModelNode operation = new ModelNode(); operation.get(OP_ADDR).setEmptyList(); operation.get(OP).set("reload"); if (adminOnly) { operation.get("admin-only").set(adminOnly); } if (startSuspended) { operation.get("start-mode").set("suspend"); } if(serverConfig != null) { operation.get("server-config").set(serverConfig); } try { ModelNode result = client.execute(operation); if (!"success".equals(result.get(ClientConstants.OUTCOME).asString())) { fail("Reload operation didn't finish successfully: " + result.asString()); } } catch(IOException e) { final Throwable cause = e.getCause(); if (!(cause instanceof ExecutionException) && !(cause instanceof CancellationException)) { throw new RuntimeException(e); } // else ignore, this might happen if the channel gets closed before we got the response } } private static void waitForLiveServerToReload(int timeout, String serverAddress, int serverPort) { int adjustedTimeout = TimeoutUtil.adjust(timeout); long start = System.currentTimeMillis(); ModelNode operation = new ModelNode(); operation.get(OP_ADDR).setEmptyList(); operation.get(OP).set(READ_ATTRIBUTE_OPERATION); operation.get(NAME).set("server-state"); while (System.currentTimeMillis() - start < adjustedTimeout) { //do the sleep before we check, as the attribute state may not change instantly //also reload generally takes longer than 100ms anyway try { Thread.sleep(100); } catch (InterruptedException e) { } try { ModelControllerClient liveClient = ModelControllerClient.Factory.create( serverAddress, serverPort); try { ModelNode result = liveClient.execute(operation); if ("running" .equals(result.get(RESULT).asString())) { log.debugf("Server %s:%d was reloaded in %d milliseconds", serverAddress, serverPort, System.currentTimeMillis() - start); return; } } catch (IOException e) { // ignore } finally { IoUtils.safeClose(liveClient); } } catch (UnknownHostException e) { throw new RuntimeException(e); } } fail("Live Server did not reload in the imparted time of " + adjustedTimeout + "(" + timeout + ") milliseconds"); } /** * Gets the current value of the server root resource's {@code server-state} attribute. * @param managementClient client to use to read the state * @return the server state. Will not be {@code null}. * @throws IOException if there is an IO problem reading the state */ public static String getContainerRunningState(ManagementClient managementClient) throws IOException { return getContainerRunningState(managementClient.getControllerClient()); } /** * Gets the current value of the server root resource's {@code server-state} attribute. * @param modelControllerClient client to use to read the state * @return the server state. Will not be {@code null}. * @throws IOException if there is an IO problem reading the state */ public static String getContainerRunningState(ModelControllerClient modelControllerClient) throws IOException { ModelNode operation = new ModelNode(); operation.get(OP_ADDR).setEmptyList(); operation.get(OP).set(READ_ATTRIBUTE_OPERATION); operation.get(NAME).set("server-state"); ModelNode rsp = modelControllerClient.execute(operation); return SUCCESS.equals(rsp.get(OUTCOME).asString()) ? rsp.get(RESULT).asString() : FAILED; } /** * Checks if the container status is "reload-required" and if it's the case executes reload and waits for completion. * Otherwise * * @deprecated Use {@link #reloadIfRequired(ManagementClient)} which will allow completion waiting to check on * the correct address for reload completion if the server is not using the default management * address or port */ @Deprecated public static void reloadIfRequired(final ModelControllerClient controllerClient) throws Exception { String runningState = getContainerRunningState(controllerClient); if ("reload-required".equalsIgnoreCase(runningState)) { log.trace("Server reload is required. The reload will be executed."); executeReloadAndWaitForCompletion(controllerClient); } else { log.debugf("Server reload is not required; server-state is %s", runningState); Assert.assertEquals("Server state 'running' is expected", "running", runningState); } } /** * Check if the server is in reload-required state and if it is, execute {@link #executeReloadAndWaitForCompletion(ManagementClient)}. * * @param managementClient client to use to execute the reload and to provide host and port information for * * reconnecting to wait for completion of the reload * @throws Exception if a failure occurs when checking if reload is required. */ public static void reloadIfRequired(final ManagementClient managementClient) throws Exception { String runningState = getContainerRunningState(managementClient); if ("reload-required".equalsIgnoreCase(runningState)) { log.trace("Server reload is required. The reload will be executed."); executeReloadAndWaitForCompletion(managementClient); } else { log.debugf("Server reload is not required; server-state is %s", runningState); Assert.assertEquals("Server state 'running' is expected", "running", runningState); } } /** * {@link ServerSetupTask} that calls {@link #reloadIfRequired(ManagementClient)} in the {@code setup} method */ public static class BeforeSetupTask implements ServerSetupTask { public static final BeforeSetupTask INSTANCE = new BeforeSetupTask(); /** * Calls {@link #reloadIfRequired(ManagementClient)}. * * {@inheritDoc} */ @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { reloadIfRequired(managementClient); } /** A no-op */ @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { } } /** * {@link ServerSetupTask} that calls {@link #reloadIfRequired(ManagementClient)} in the {@code tearDown} method */ public static class AfterSetupTask implements ServerSetupTask { public static final AfterSetupTask INSTANCE = new AfterSetupTask(); /** A no-op */ @Override public void setup(ManagementClient managementClient, String containerId) throws Exception { } /** * Calls {@link #reloadIfRequired(ManagementClient)}. * * {@inheritDoc} */ @Override public void tearDown(ManagementClient managementClient, String containerId) throws Exception { reloadIfRequired(managementClient); } } }
18,563
49.583106
203
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/ModuleUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; import jakarta.enterprise.inject.spi.Extension; import org.jboss.as.test.module.util.TestModule; import org.jboss.shrinkwrap.api.spec.JavaArchive; public class ModuleUtils { private static final String[] EE_DEPENDENCIES = new String[] {"javax.enterprise.api", "javax.inject.api", "javax.servlet.api", "javax.servlet.jsp.api"}; public static TestModule createTestModuleWithEEDependencies(String moduleName) { TestModule testModule = new TestModule("test." + moduleName, EE_DEPENDENCIES); return testModule; } public static final TestModule.ClassCallback ENTERPRISE_INJECT = new TestModule.ClassCallback() { @Override public void classesAdded(JavaArchive jar, List<Class<?>> classes) { List<Class<Extension>> extensions = new ArrayList<Class<Extension>>(1); for (Class<?> clazz : classes) { if (Extension.class.isAssignableFrom(clazz)) { extensions.add((Class<Extension>) clazz); } } if (!extensions.isEmpty()) { Class<Extension>[] a = (Class<Extension>[]) Array.newInstance(Extension.class.getClass(), 0); jar.addAsServiceProvider(Extension.class, extensions.toArray(a)); } } }; }
2,431
40.931034
156
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/categories/RequiresTransformedClass.java
/* * Copyright 2022 Red Hat, Inc. * * 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.jboss.as.test.shared.categories; /** * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ public interface RequiresTransformedClass { }
765
30.916667
75
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/util/ClientInterceptorUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.util; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.as.test.shared.integration.ejb.security.Util; /** * Util class which is used for remote lookups in client-side interceptor related tests. * * @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc. */ public class ClientInterceptorUtil { public ClientInterceptorUtil() { // empty } public static <T> T lookupStatelessRemote(String archiveName, Class<? extends T> beanType, Class<T> remoteInterface) throws NamingException { final Hashtable<String, String> props = new Hashtable<>(); props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context ctx = new InitialContext(props); String ejbLookup = Util.createRemoteEjbJndiContext( "", archiveName, "", beanType.getSimpleName(), remoteInterface.getName(), false); return remoteInterface.cast(ctx.lookup(ejbLookup)); } }
2,123
39.075472
145
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/util/AssumeTestGroupUtil.java
package org.jboss.as.test.shared.util; import static org.junit.Assume.assumeTrue; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.function.Supplier; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AssumptionViolatedException; import org.testcontainers.DockerClientFactory; /** * Helper methods which help to skip tests for functionality which is not yet fully working or where the test is not * expected to work in certain execution environments. Put the call of the method directly into * the failing test method, or if you want to skip whole test class, then put the method call into method annotated with * {@link org.junit.BeforeClass}. * <p> * Methods whose names begin with 'assume' throw {@link AssumptionViolatedException} if the described assumption is not * met; otherwise they return normally. Other methods and constants in this class are meant for related use cases. * </p> * * @author Josef Cacek * @author Brian Stansberry */ public class AssumeTestGroupUtil { /** * An empty deployment archive that can be returned from an @Deployment method if the normal deployment * returned from the method cannot be successfully deployed under certain conditions. Arquillian will deploy * managed deployments <strong>before executing any @BeforeClass method</strong>, so if a @BeforeClass * method conditionally disables running the tests with an AssumptionViolatedException, the deployment will * still get deployed and may fail the test. So have it deploy this instead so your @BeforeClass gets called. * <p> * This is private so it can be lazy initialized when needed, in case this class is used for other reasons * in-container where Shrinkwrap is not available. * </p> */ private static JavaArchive EMPTY_JAR; /** Same as {@link #EMPTY_JAR} but is a {@link WebArchive}. */ private static WebArchive EMPTY_WAR; /** Same as {@link #EMPTY_JAR} but is an {@link EnterpriseArchive}. */ private static EnterpriseArchive EMPTY_EAR; /** * Creates an empty (except for a manifest) JavaArchive with the name {@code empty.jar}. * @return the archive */ public static JavaArchive emptyJar() { if (EMPTY_JAR == null) { EMPTY_JAR = emptyJar("empty"); } return EMPTY_JAR; } /** * Creates an empty (except for a manifest) JavaArchive with the given name. * @param name the jar name. Can end with the '.jar' extension, but if not it will be added * @return the archive */ public static JavaArchive emptyJar(String name) { String jarName = name.endsWith(".jar") ? name : name + ".jar"; return ShrinkWrap.create(JavaArchive.class, jarName) .addManifest(); } /** * Creates an empty (except for a manifest) WebArchive with the name {@code empty.war}. * @return the archive */ public static WebArchive emptyWar() { if (EMPTY_WAR == null) { EMPTY_WAR = emptyWar("empty"); } return EMPTY_WAR; } /** * Creates an empty (except for a manifest) WebArchive with the given name. * @param name the jar name. Can end with the '.war' extension, but if not it will be added * @return the archive */ public static WebArchive emptyWar(String name) { String warName = name.endsWith(".war") ? name : name + ".war"; return ShrinkWrap.create(WebArchive.class, warName) .addManifest(); } /** * Creates an empty (except for a manifest) EnterpriseArchive with the name {@code empty.ear}. * @return the archive */ public static EnterpriseArchive emptyEar() { if (EMPTY_EAR == null) { EMPTY_EAR = emptyEar("empty"); } return EMPTY_EAR; } /** * Creates an empty (except for a manifest) EnterpriseArchive with the given name. * @param name the jar name. Can end with the '.ear' extension, but if not it will be added * @return the archive */ public static EnterpriseArchive emptyEar(String name) { String earName = name.endsWith(".ear") ? name : name + ".ear"; return ShrinkWrap.create(EnterpriseArchive.class, earName) .addManifest(); } /** * Assume for tests that fail when the security manager is enabled. This should be used sparingly and issues should * be filed for failing tests so a proper fix can be done. * <p> * Note that this checks the {@code security.manager} system property and <strong>not</strong> that the * {@link System#getSecurityManager()} is {@code null}. The property is checked so that the assumption check can be * done in a {@link org.junit.Before @Before} or {@link org.junit.BeforeClass @BeforeClass} method. * </p> * * @throws AssumptionViolatedException if the security manager is enabled */ public static void assumeSecurityManagerDisabled() { assumeCondition("Tests failing if the security manager is enabled.", AssumeTestGroupUtil::isSecurityManagerDisabled); } /** * Check if the JDK Security Manager is <strong>enabled/strong>. * <p> * Note that this checks the {@code security.manager} system property and <strong>not</strong> that the * {@link System#getSecurityManager()} is not {@code null}. The property is checked so that the assumption check can be * done in a {@link org.junit.Before @Before} or {@link org.junit.BeforeClass @BeforeClass} method. * </p> * * @return {@code true} if the {@code security.manager} system property is null. */ public static boolean isSecurityManagerEnabled() { return !isSecurityManagerDisabled(); } /** * Check if the JDK Security Manager is <strong>disabled</strong>. * <p> * Note that this checks the {@code security.manager} system property and <strong>not</strong> that the * {@link System#getSecurityManager()} is {@code null}. The property is checked so that the assumption check can be * done in a {@link org.junit.Before @Before} or {@link org.junit.BeforeClass @BeforeClass} method. * </p> * * @return {@code true} if the {@code security.manager} system property is null. */ public static boolean isSecurityManagerDisabled() { return System.getProperty("security.manager") == null; } /** * Assume for tests that fail when the security manager is enabled or the JDK version is prior to a given version * <p> * Note that this checks the {@code security.manager} system property and <strong>not</strong> that the * {@link System#getSecurityManager()} is {@code null}. The property is checked so that the assumption check can be * done in a {@link org.junit.Before @Before} or {@link org.junit.BeforeClass @BeforeClass} method. * </p> * * @param javaSpecificationVersion the JDK specification version * * @throws AssumptionViolatedException if the security manager is enabled or the JDK version is greater than or equal to {@code javaSpecificationVersion} */ public static void assumeSecurityManagerDisabledOrAssumeJDKVersionBefore(int javaSpecificationVersion) { assumeCondition("Tests failing if the security manager is enabled and JDK in use is after " + javaSpecificationVersion + ".", () -> (isSecurityManagerDisabled() || isJDKVersionBefore(javaSpecificationVersion))); } /** * Assume for tests that fail when the JVM version is too low. This should be used sparingly. * * @param javaSpecificationVersion the JDK specification version. Use 8 for JDK 8. Must be 8 or higher. * * @throws AssumptionViolatedException if the JDK version is less than or equal to {@code javaSpecificationVersion} */ public static void assumeJDKVersionAfter(int javaSpecificationVersion) { assert javaSpecificationVersion >= 11; // we only support 11 or later assumeCondition("Tests failing if the JDK in use is before " + javaSpecificationVersion + ".", () -> isJDKVersionAfter(javaSpecificationVersion)); } /** * Assume for tests that fail when the JVM version is too high. This should be used sparingly. * * @param javaSpecificationVersion the JDK specification version. Must be 9 or higher. * * @throws AssumptionViolatedException if the JDK version is greater than or equal to {@code javaSpecificationVersion} */ public static void assumeJDKVersionBefore(int javaSpecificationVersion) { assert javaSpecificationVersion > 11; // we only support 11 or later so no reason to call this for 11 assumeCondition("Tests failing if the JDK in use is after " + javaSpecificationVersion + ".", () -> isJDKVersionBefore(javaSpecificationVersion)); } /** * Check if the current JDK specification version is greater than the given value. * * @param javaSpecificationVersion the JDK specification version. Use 8 for JDK 8. */ public static boolean isJDKVersionAfter(int javaSpecificationVersion) { return getJavaSpecificationVersion() > javaSpecificationVersion; } /** * Check if the current JDK specification version is less than the given value. * * @param javaSpecificationVersion the JDK specification version. Use 8 for JDK 8. */ public static boolean isJDKVersionBefore(int javaSpecificationVersion) { return getJavaSpecificationVersion() < javaSpecificationVersion; } /** * Assume for test failures when running against a full distribution. * Full distributions are available from build/dist modules. It skips tests in case * {@code '-Dtestsuite.default.build.project.prefix'} Maven argument is used with * a non empty value, e.g. testsuite.default.build.project.prefix=ee- which means we * are using ee-build/ee-dist modules as the source where to find the server under test. * * @throws AssumptionViolatedException if property {@code testsuite.default.build.project.prefix} is set to a non-empty value */ public static void assumeFullDistribution() { assumeCondition("Tests requiring full distribution are disabled", AssumeTestGroupUtil::isFullDistribution); } /** * Checks whether tests are running against a full distribution. * Full distributions are available from build/dist modules. It skips tests in case * {@code '-Dtestsuite.default.build.project.prefix'} Maven argument is used with * a non empty value, e.g. testsuite.default.build.project.prefix=ee- which means we * are using ee-build/ee-dist modules as the source where to find the server under test. * * @throws {@code true} of system property {@code testsuite.default.build.project.prefix} has a non-empty value */ public static boolean isFullDistribution() { return System.getProperty("testsuite.default.build.project.prefix", "").equals(""); } /** * Assume for tests that require a docker installation. * * @throws AssumptionViolatedException if a docker client cannot be initialized */ public static void assumeDockerAvailable() { assumeCondition("Docker is not available.", AssumeTestGroupUtil::isDockerAvailable); } /** * Checks whether a docker installation is available. * * @throws AssumptionViolatedException if a docker client cannot be initialized */ public static boolean isDockerAvailable() { try { DockerClientFactory.instance().client(); return true; } catch (Throwable ex) { return false; } } /** * Assume for tests that should not run against a WildFly Preview installation. * * @throws AssumptionViolatedException if one of the system properties that indicates WildFly Preview is being tested is set */ public static void assumeNotWildFlyPreview() { assumeCondition("Some tests are disabled on WildFly Preview", () -> !isWildFlyPreview()); } public static void assumeWildFlyPreview() { assumeCondition("Some tests require WildFly Preview", AssumeTestGroupUtil::isWildFlyPreview); } public static boolean isWildFlyPreview() { return System.getProperty("ts.ee9") != null || System.getProperty("ts.bootable.ee9") != null; } private static int getJavaSpecificationVersion() { final String versionString = System.getProperty("java.specification.version"); return Integer.parseInt(versionString); } private static void assumeCondition(final String message, final Supplier<Boolean> assumeTrueCondition) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { assumeTrue(message, assumeTrueCondition.get()); return null; } }); } }
13,266
43.820946
157
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/util/LoggingUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.util; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Predicate; import java.util.stream.Stream; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.dmr.ModelNode; /** * Utility class for logging repetitive tasks * @author tmiyar * */ public class LoggingUtil { /** * Will return the full log path for the handler in the name parameter, * to be used when using @RunAsClient annotation * Depending on how you run it you might need some permissions: * new PropertyPermission("node0", "read"), * new RemotingPermission("connect"), * new SocketPermission(Utils.getDefaultHost(true), "accept,connect,listen,resolve"), * new RuntimePermission("getClassLoader") * @param managementClient * @param name of handler * @param handlerType i.e. periodic-rotating-file-handler * @return * @throws Exception */ public static Path getLogPath(ManagementClient managementClient, String handlerType, String name) throws Exception { final ModelNode address = Operations.createAddress("subsystem", "logging", handlerType, name); final ModelNode op = Operations.createOperation("resolve-path", address); final ModelNode result = managementClient.getControllerClient().execute(op); if (!Operations.isSuccessfulOutcome(result)) { throw new Exception("Can't get log file"); } return Paths.get(Operations.readResult(result).asString()); } /** * Will return the full log path for the given log file relative to the the jboss.server.log.dir. * Meant for use by test code that runs in the server VM. Tests that use this should add * the following permission to allow the call to succeed in a testsuite run with the security manager enabled: * new PropertyPermission("jboss.server.log.dir", "read") * * @param logFile name of the log file, relative to the server log directory * @return the path */ public static Path getInServerLogPath(String logFile) { return Paths.get(System.getProperty("jboss.server.log.dir")).resolve(logFile); } @SafeVarargs public static boolean hasLogMessage(String logFileName, String logMessage, Predicate<String>... filters) throws Exception { Path logPath = LoggingUtil.getInServerLogPath(logFileName); return isMessageInLogFile(logPath, logMessage, 0, filters); } @SafeVarargs public static boolean hasLogMessage(ManagementClient managementClient, String handlerName, String logMessage, Predicate<String>... filters) throws Exception { Path logPath = LoggingUtil.getLogPath(managementClient, "file-handler", handlerName); return isMessageInLogFile(logPath, logMessage, 0, filters); } @SafeVarargs public static boolean hasLogMessage(ManagementClient managementClient, String handlerName, String logMessage, long offset, Predicate<String>... filters) throws Exception { Path logPath = LoggingUtil.getLogPath(managementClient, "file-handler", handlerName); return isMessageInLogFile(logPath, logMessage, offset, filters); } @SafeVarargs private static boolean isMessageInLogFile(Path logPath, String logMessage, long offset, Predicate<String>... filters) throws Exception{ boolean found = false; try (BufferedReader fileReader = Files.newBufferedReader(logPath, StandardCharsets.UTF_8)) { String line = ""; long count = 0; while ((line = fileReader.readLine()) != null) { if (count++ < offset) { continue; } if (line.contains(logMessage)) { found = true; for (int i = 0; found && filters != null && i < filters.length; i++) { found = filters[i].test(line); } if (found) { break; } } } } return found; } /** * Helper method to dump the contents of a log to stdout. * @param logFileName the name of the log file */ public static void dumpTestLog(String logFileName) throws IOException { Path logPath = LoggingUtil.getInServerLogPath(logFileName); dumpTestLog(logPath); } /** * Helper method to dump the contents of a log to stdout. * @param managementClient client to use the name of the log file used by a handler * @param handlerName name of the handler that writes to the file */ public static void dumpTestLog(ManagementClient managementClient, String handlerName) throws Exception { Path logPath = LoggingUtil.getLogPath(managementClient, "file-handler", handlerName); dumpTestLog(logPath); } private static void dumpTestLog(Path logPath) throws IOException { try (BufferedReader fileReader = Files.newBufferedReader(logPath, StandardCharsets.UTF_8)) { String line = ""; while ((line = fileReader.readLine()) != null) { System.out.println(line); } } } public static long countLines(Path logPath) throws Exception { try(Stream<String> lines = Files.lines(logPath)) { return lines.count(); } } }
6,620
39.87037
175
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/interceptor/clientside/InterceptorModule.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.interceptor.clientside; import java.net.URL; import org.jboss.as.test.module.util.TestModule; /** * A simple POJO representing a structure needed for setting up a global interceptor. * * @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc. */ public class InterceptorModule { private Class interceptorClass; private String moduleName; private String moduleXmlName; private URL moduleXmlPath; private String jarName; private TestModule testModule; /** * @param interceptorClass - class with interceptor implementation. * @param moduleName - name of interceptor module. * @param moduleXmlName - module XML filename, e.g. module.xml * @param moduleXmlPath - module XML URL * @param jarName - name of interceptor target JAR archive. */ public InterceptorModule(Class interceptorClass, String moduleName, String moduleXmlName, URL moduleXmlPath, String jarName) { this.interceptorClass = interceptorClass; this.moduleName = moduleName; this.moduleXmlName = moduleXmlName; this.moduleXmlPath = moduleXmlPath; this.jarName = jarName; } public Class getInterceptorClass() { return interceptorClass; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getModuleXmlName() { return moduleXmlName; } public URL getModuleXmlPath() { return moduleXmlPath; } public String getJarName() { return jarName; } public TestModule getTestModule() { return testModule; } public void setTestModule(TestModule testModule) { this.testModule = testModule; } }
2,885
31.795455
130
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/interceptor/clientside/AbstractClientInterceptorsSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.interceptor.clientside; import static org.jboss.as.controller.client.helpers.ClientConstants.NAME; import static org.jboss.as.controller.client.helpers.ClientConstants.OP; import static org.jboss.as.controller.client.helpers.ClientConstants.OP_ADDR; import static org.jboss.as.controller.client.helpers.ClientConstants.SUBSYSTEM; import static org.jboss.as.controller.client.helpers.ClientConstants.UNDEFINE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.client.helpers.ClientConstants.VALUE; import static org.jboss.as.controller.client.helpers.ClientConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODULE; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.module.util.TestModule; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * An abstract setup task for setting up and removing client-side interceptors. * Packs them into $JBOSS_HOME/modules folder, modifies Enterprise Beans 3 subsystem 'client-interceptors' attribute. * * @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc. */ public abstract class AbstractClientInterceptorsSetupTask { public static final String DEPLOYMENT_NAME_SERVER = "server"; public static final String DEPLOYMENT_NAME_CLIENT = "client"; public static final String TARGER_CONTAINER_SERVER = "multinode-server"; public static final String TARGER_CONTAINER_CLIENT = "multinode-client"; public static class SetupTask implements ServerSetupTask, InterceptorsSetupTask { private List<InterceptorModule> interceptorModules; public SetupTask() { this.interceptorModules = getModules(); } @Override public List<InterceptorModule> getModules() { // overriden in subclasses return new ArrayList<>(); } /** * Pack a sample interceptor to module and place to $JBOSS_HOME/modules directory */ @Override public void packModule(InterceptorModule module) throws Exception { URL url = module.getModuleXmlPath(); if (url == null) { throw new IllegalStateException("Could not find " + module.getModuleXmlName()); } File moduleXmlFile = new File(url.toURI()); module.setTestModule(new TestModule(module.getModuleName(), moduleXmlFile)); JavaArchive jar = module.getTestModule().addResource(module.getJarName()); jar.addClass(module.getInterceptorClass()); module.getTestModule().create(true); } /** * /subsystem=ejb3:write-attribute(name=client-interceptors,value=[{module=moduleName,class=className}]) */ @Override public void modifyClientInterceptors(List<InterceptorModule> interceptorModules, ManagementClient managementClient) throws Exception { final ModelNode op = new ModelNode(); op.get(OP_ADDR).set(SUBSYSTEM, "ejb3"); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(NAME).set("client-interceptors"); final ModelNode value = new ModelNode(); for (InterceptorModule module : interceptorModules) { ModelNode node = new ModelNode(); node.get(MODULE).set(module.getModuleName()); node.get("class").set(module.getInterceptorClass().getName()); value.add(node); } op.get(VALUE).set(value); managementClient.getControllerClient().execute(op); } @Override public void revertClientInterceptors(ManagementClient managementClient) throws Exception { final ModelNode op = new ModelNode(); op.get(OP_ADDR).set(SUBSYSTEM, "ejb3"); op.get(OP).set(UNDEFINE_ATTRIBUTE_OPERATION); op.get(NAME).set("client-interceptors"); final ModelNode operationResult = managementClient.getControllerClient().execute(op); // check whether the operation was successful assertTrue(Operations.isSuccessfulOutcome(operationResult)); } @Override public void setup(ManagementClient managementClient, String s) throws Exception { if(s.equals("multinode-client")) { for (InterceptorModule module : interceptorModules) { packModule(module); } modifyClientInterceptors(interceptorModules, managementClient); // reload in order to apply server-interceptors changes ServerReload.executeReloadAndWaitForCompletion(managementClient); } } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { if(s.equals("multinode-client")) { for (InterceptorModule module: interceptorModules) { module.getTestModule().remove(); } revertClientInterceptors(managementClient); // reload in order to apply server-interceptors changes ServerReload.executeReloadAndWaitForCompletion(managementClient); } } } }
6,676
43.218543
142
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/interceptor/clientside/InterceptorsSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.interceptor.clientside; import java.util.List; import org.jboss.as.arquillian.container.ManagementClient; public interface InterceptorsSetupTask { void packModule(InterceptorModule module) throws Exception; List<InterceptorModule> getModules(); void modifyClientInterceptors(List<InterceptorModule> interceptorModules, ManagementClient managementClient) throws Exception; void revertClientInterceptors(ManagementClient managementClient) throws Exception; }
1,548
39.763158
130
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/ejb/security/CallbackHandler.java
package org.jboss.as.test.shared.integration.ejb.security; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.RealmCallback; /** * @author Stuart Douglas */ public class CallbackHandler implements javax.security.auth.callback.CallbackHandler{ @Override public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException { for(final Callback current : callbacks) { if(current instanceof NameCallback) { ((NameCallback) current).setName("$local"); } else if(current instanceof RealmCallback) { ((RealmCallback) current).setText(((RealmCallback) current).getDefaultText()); } } } }
875
34.04
101
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/ejb/security/PermissionUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.ejb.security; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FilePermission; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.Permission; import java.util.Arrays; import java.util.Iterator; import nu.xom.Attribute; import nu.xom.Document; import nu.xom.Element; import nu.xom.Serializer; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.asset.StringAsset; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class PermissionUtils { public static Asset createPermissionsXmlAsset(Permission... permissions) { final Element permissionsElement = new Element("permissions"); permissionsElement.setNamespaceURI("http://xmlns.jcp.org/xml/ns/javaee"); permissionsElement.addAttribute(new Attribute("version", "7")); for (Permission permission : permissions) { final Element permissionElement = new Element("permission"); final Element classNameElement = new Element("class-name"); final Element nameElement = new Element("name"); classNameElement.appendChild(permission.getClass().getName()); nameElement.appendChild(permission.getName()); permissionElement.appendChild(classNameElement); permissionElement.appendChild(nameElement); final String actions = permission.getActions(); if (actions != null && ! actions.isEmpty()) { final Element actionsElement = new Element("actions"); actionsElement.appendChild(actions); permissionElement.appendChild(actionsElement); } permissionsElement.appendChild(permissionElement); } Document document = new Document(permissionsElement); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { final NiceSerializer serializer = new NiceSerializer(stream); serializer.setIndent(4); serializer.setLineSeparator("\n"); serializer.write(document); serializer.flush(); return new StringAsset(stream.toString("UTF-8")); } catch (IOException e) { throw new IllegalStateException("Generating permissions.xml failed", e); } } /** * Creates a new {@link FilePermission} with the base path of the system property {@code jboss.inst}. * * @param action the actions required * @param paths the relative parts of the path * * @return the new file permission * * @see FilePermission * @see #createFilePermission(String, String, Iterable) */ public static FilePermission createFilePermission(final String action, final String... paths) { return createFilePermission(action, "jboss.inst", Arrays.asList(paths)); } /** * Creates a new {@link FilePermission}. * <p> * The paths are iterated with a {@link File#separatorChar} be placed after each path portion. The * {@code sysPropKey} is used to resolve the base directory which the {@code paths} will be appended to. * </p> * <p> * The base path is validated and must exist as well as be a directory. The path is converted to an * {@linkplain Path#toAbsolutePath() absolute} path as well as {@linkplain Path#normalize() normalized}. * </p> * <pre> * {@code * // The following produces the absolute path of target/wildfly/standalone/tmp/example/* * createFilePermission("read", "jboss.inst", Arrays.asList("standalone", "tmp", "example", "*")); * * // The following produces the absolute path of target/wildfly/standalone/data/- * createFilePermission("read", "jboss.inst", Arrays.asList("standalone", "data", "-")); * * // The following produces the absolute path of target/wildfly/standalone/data/example * createFilePermission("read", "jboss.inst", Arrays.asList("standalone", "data", "example")); * } * </pre> * * @param action the actions required * @param sysPropKey the system property key to resolve the base directory * @param paths the relative parts of the path to be appended to the base directory * * @return the new file permission * * @see FilePermission */ public static FilePermission createFilePermission(final String action, final String sysPropKey, final Iterable<String> paths) { final String prop = System.getProperty(sysPropKey); if (prop == null) { throw new IllegalArgumentException(String.format("Could not find the system property %s", sysPropKey)); } final Path base = Paths.get(prop); if (Files.notExists(base)) { throw new RuntimeException(String.format("The system property %s resolved to %s which does not exist.", sysPropKey, base)); } if (!Files.isDirectory(base)) { throw new RuntimeException(String.format("The system property %s resolved to %s which is not a directory.", sysPropKey, base)); } final StringBuilder path = new StringBuilder(256) .append(base.toAbsolutePath().normalize()) .append(File.separatorChar); final Iterator<String> iter = paths.iterator(); while (iter.hasNext()) { path.append(iter.next()); if (iter.hasNext()) { path.append(File.separatorChar); } } return new FilePermission(path.toString(), action); } static class NiceSerializer extends Serializer { public NiceSerializer(OutputStream out) throws UnsupportedEncodingException { super(out, "UTF-8"); } protected void writeXMLDeclaration() throws IOException { super.writeXMLDeclaration(); super.breakLine(); } } }
7,114
41.35119
139
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/ejb/security/Util.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.ejb.security; import static org.junit.Assert.assertTrue; import java.util.Properties; import java.util.concurrent.Callable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.ejb.EJBAccessException; import jakarta.ejb.EJBException; import org.wildfly.security.auth.server.SecurityDomain; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.evidence.PasswordGuessEvidence; /** * Holder for couple of utility methods used while testing EJB3 security. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class Util { /** * Creates JNDI context string based on given parameters. * See details at https://docs.jboss.org/author/display/AS71/EJB+invocations+from+a+remote+client+using+JNDI * * @param appName - typically the ear name without the .ear * - could be empty string when deploying just jar with EJBs * @param moduleName - jar file name without trailing .jar * @param distinctName - AS7 allows each deployment to have an (optional) distinct name * - could be empty string when not specified * @param beanName - The EJB name which by default is the simple class name of the bean implementation class * @param viewClassName - the remote view is fully qualified class name of @Remote EJB interface * @param isStateful - if the bean is stateful set to true * * @return - JNDI context string to use in your client JNDI lookup */ public static String createRemoteEjbJndiContext( String appName, String moduleName, String distinctName, String beanName, String viewClassName, boolean isStateful) { return "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName + (isStateful ? "?stateful" : ""); } /** * Helper to create InitialContext with necessary properties. * * @return new InitialContext. * @throws NamingException */ public static Context createNamingContext() throws NamingException { final Properties jndiProps = new Properties(); jndiProps.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); return new InitialContext(jndiProps); } /** * Switch the user's identity using Elytron. * * @param username the new username * @param password the new password * @param callable the callable task to execute under the new identity * @param <T> the result type of the callable task * @return the result of the callable task * @throws Exception if an error occurs while switching the user's identity or if an error occurs while executing the callable task */ public static <T> T switchIdentity(final String username, final String password, final Callable<T> callable) throws Exception { return switchIdentity(username, password, callable, false); } /** * Switch the user's identity using Elytron. * * @param username the new username * @param password the new password * @param callable the callable task to execute under the new identity * @param classLoader the class loader to use when checking for a security domain association * @param <T> the result type of the callable task * @return the result of the callable task * @throws Exception if an error occurs while switching the user's identity or if an error occurs while executing the callable task */ public static <T> T switchIdentity(final String username, final String password, final Callable<T> callable, final ClassLoader classLoader) throws Exception { return switchIdentity(username, password, callable, false, classLoader); } /** * Switch the user's identity using Elytron. * * @param username the new username * @param password the new password * @param callable the callable task to execute under the new identity * @param validateException whether or not to validate an exception thrown by the callable task * @param useClientLoginModule {@code true} if {@link ClientLoginModule} should be used for legacy security, * {@code false} if {@link SecurityClientFactory} should be used for legacy security instead * @param <T> the result type of the callable task * @return the result of the callable task * @throws Exception if an error occurs while switching the user's identity or if an error occurs while executing the callable task */ public static <T> T switchIdentity(final String username, final String password, final Callable<T> callable, boolean validateException) throws Exception { return switchIdentity(username, password, callable, validateException, null); } /** * Switch the user's identity using Elytron. * * @param username the new username * @param password the new password * @param callable the callable task to execute under the new identity * @param validateException whether or not to validate an exception thrown by the callable task * {@code false} if {@link SecurityClientFactory} should be used for legacy security instead * @param classLoader the class loader to use when checking for a security domain association * @param <T> the result type of the callable task * @return the result of the callable task * @throws Exception if an error occurs while switching the user's identity or if an error occurs while executing the callable task */ public static <T> T switchIdentity(final String username, final String password, final Callable<T> callable, boolean validateException, final ClassLoader classLoader) throws Exception { boolean initialAuthSucceeded = false; try { if (username != null && password != null) { final SecurityDomain securityDomain; if (classLoader != null) { final ClassLoader current = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); securityDomain = SecurityDomain.getCurrent(); } finally { Thread.currentThread().setContextClassLoader(current); } } else { securityDomain = SecurityDomain.getCurrent(); } if (securityDomain != null) { // elytron is enabled, use the new way to switch the identity final SecurityIdentity securityIdentity = securityDomain.authenticate(username, new PasswordGuessEvidence(password.toCharArray())); initialAuthSucceeded = true; return securityIdentity.runAs(callable); } else { // legacy security is enabled, use the ClientLoginModule or SecurityClientFactory to switch the identity throw new IllegalStateException("Legacy security is no longer supported."); } } return callable.call(); } catch (Exception e) { if (validateException) { validateException(e, initialAuthSucceeded); } else { throw e; } } return null; } private static void validateException(final Exception e, final boolean initialAuthSucceeded) { if (SecurityDomain.getCurrent() != null) { if (initialAuthSucceeded) { assertTrue("Expected EJBException due to bad password not thrown.", e instanceof EJBException && e.getCause() instanceof SecurityException); } else { assertTrue("Expected SecurityException due to bad password not thrown.", e instanceof SecurityException); } } else { assertTrue("Expected EJBAccessException due to bad password not thrown. (EJB 3.1 FR 17.6.9)", e instanceof EJBAccessException); } } /** * Switch the user's identity using Elytron. * * @param username the new username * @param password the new password * @param callable the callable task to execute under the new identity * @param <T> the result type of the callable task * @return the result of the callable task * @throws Exception if an error occurs while switching the user's identity or if an error occurs while executing the callable task */ public static <T> T switchIdentitySCF(final String username, final String password, final Callable<T> callable) throws Exception { return switchIdentity(username, password, callable, false); } }
9,969
46.703349
189
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/ejb/interceptor/serverside/AbstractServerInterceptorsSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.ejb.interceptor.serverside; import static org.jboss.as.controller.client.helpers.ClientConstants.NAME; import static org.jboss.as.controller.client.helpers.ClientConstants.OP; import static org.jboss.as.controller.client.helpers.ClientConstants.OP_ADDR; import static org.jboss.as.controller.client.helpers.ClientConstants.SUBSYSTEM; import static org.jboss.as.controller.client.helpers.ClientConstants.UNDEFINE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.client.helpers.ClientConstants.VALUE; import static org.jboss.as.controller.client.helpers.ClientConstants.WRITE_ATTRIBUTE_OPERATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODULE; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jboss.as.arquillian.api.ServerSetupTask; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.test.module.util.TestModule; import org.jboss.as.test.shared.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * An abstract setup task for setting up and removing server-side interceptors. * Packs them into $JBOSS_HOME/modules folder, modifies EJB3 subsystem 'server-interceptors' attribute. * * @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc. */ public abstract class AbstractServerInterceptorsSetupTask { public static class SetupTask implements ServerSetupTask, InterceptorsSetupTask { private List<InterceptorModule> interceptorModules; public SetupTask() { this.interceptorModules = getModules(); } @Override public List<InterceptorModule> getModules() { // overriden in subclasses return new ArrayList<>(); } /** * Pack a sample interceptor to module and place to $JBOSS_HOME/modules directory */ @Override public void packModule(InterceptorModule module) throws Exception { URL url = module.getModuleXmlPath(); if (url == null) { throw new IllegalStateException("Could not find " + module.getModuleXmlName()); } File moduleXmlFile = new File(url.toURI()); module.setTestModule(new TestModule(module.getModuleName(), moduleXmlFile)); JavaArchive jar = module.getTestModule().addResource(module.getJarName()); jar.addClass(module.getInterceptorClass()); module.getTestModule().create(true); } /** * /subsystem=ejb3:write-attribute(name=server-interceptors,value=[{module=moduleName,class=className}]) */ @Override public void modifyServerInterceptors(List<InterceptorModule> interceptorModules, ManagementClient managementClient) throws Exception { final ModelNode op = new ModelNode(); op.get(OP_ADDR).set(SUBSYSTEM, "ejb3"); op.get(OP).set(WRITE_ATTRIBUTE_OPERATION); op.get(NAME).set("server-interceptors"); final ModelNode value = new ModelNode(); for (InterceptorModule module : interceptorModules) { ModelNode node = new ModelNode(); node.get(MODULE).set(module.getModuleName()); node.get("class").set(module.getInterceptorClass().getName()); value.add(node); } op.get(VALUE).set(value); managementClient.getControllerClient().execute(op); } @Override public void revertServerInterceptors(ManagementClient managementClient) throws Exception { final ModelNode op = new ModelNode(); op.get(OP_ADDR).set(SUBSYSTEM, "ejb3"); op.get(OP).set(UNDEFINE_ATTRIBUTE_OPERATION); op.get(NAME).set("server-interceptors"); final ModelNode operationResult = managementClient.getControllerClient().execute(op); // check whether the operation was successful assertTrue(Operations.isSuccessfulOutcome(operationResult)); } @Override public void setup(ManagementClient managementClient, String s) throws Exception { for (InterceptorModule module : interceptorModules) { packModule(module); } modifyServerInterceptors(interceptorModules, managementClient); // reload in order to apply server-interceptors changes ServerReload.executeReloadAndWaitForCompletion(managementClient); } @Override public void tearDown(ManagementClient managementClient, String s) throws Exception { for (InterceptorModule module: interceptorModules) { module.getTestModule().remove(); } revertServerInterceptors(managementClient); // reload in order to apply server-interceptors changes ServerReload.executeReloadAndWaitForCompletion(managementClient); } } }
6,208
43.035461
142
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/ejb/interceptor/serverside/InterceptorModule.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.ejb.interceptor.serverside; import java.net.URL; import org.jboss.as.test.module.util.TestModule; /** * A simple POJO representing a structure needed for setting up a global interceptor. * * @author <a href="mailto:szhantem@redhat.com">Sultan Zhantemirov</a> (c) 2019 Red Hat, inc. */ public class InterceptorModule { private Class interceptorClass; private String moduleName; private String moduleXmlName; private URL moduleXmlPath; private String jarName; private TestModule testModule; /** * @param interceptorClass - class with interceptor implementation. * @param moduleName - name of interceptor module. * @param moduleXmlName - module XML filename, e.g. module.xml * @param moduleXmlPath - module XML URL * @param jarName - name of interceptor target JAR archive. */ public InterceptorModule(Class interceptorClass, String moduleName, String moduleXmlName, URL moduleXmlPath, String jarName) { this.interceptorClass = interceptorClass; this.moduleName = moduleName; this.moduleXmlName = moduleXmlName; this.moduleXmlPath = moduleXmlPath; this.jarName = jarName; } public Class getInterceptorClass() { return interceptorClass; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getModuleXmlName() { return moduleXmlName; } public URL getModuleXmlPath() { return moduleXmlPath; } public String getJarName() { return jarName; } public TestModule getTestModule() { return testModule; } public void setTestModule(TestModule testModule) { this.testModule = testModule; } }
2,889
31.840909
130
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/shared/integration/ejb/interceptor/serverside/InterceptorsSetupTask.java
/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.shared.integration.ejb.interceptor.serverside; import java.util.List; import org.jboss.as.arquillian.container.ManagementClient; public interface InterceptorsSetupTask { void packModule(InterceptorModule module) throws Exception; List<InterceptorModule> getModules(); void modifyServerInterceptors(List<InterceptorModule> interceptorModules, ManagementClient managementClient) throws Exception; void revertServerInterceptors(ManagementClient managementClient) throws Exception; }
1,552
39.868421
130
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/XidsPersister.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.transactions; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import javax.transaction.xa.Xid; import org.jboss.logging.Logger; /** * An utility class which is capable to persist {@link TestXAResource} {@link Xid} records * to the file under <code>jboss.server.data.dir</code>. * This capability is needed when server crash with recovery is tested. */ class XidsPersister { private static final Logger log = Logger.getLogger(XidsPersister.class); private String fileToPersit; XidsPersister(String fileToPersit) { this.fileToPersit = fileToPersit; } synchronized void writeToDisk(Collection<Xid> xidsToSave) { Path logFile = getLogFile(); FileOutputStream fos = null; try { fos = new FileOutputStream(logFile.toFile()); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(xidsToSave); log.debugf("Xids %s were written as the new state of the file %s", xidsToSave, logFile); } catch (IOException ioe) { log.errorf(ioe, "Cannot write xids %s to persistent file %s", xidsToSave, logFile); } finally { try { if (fos != null) fos.close(); } catch (IOException ioe) { log.debugf(ioe,"Cannot close FileOutputStream for file %s", logFile); } } } @SuppressWarnings("unchecked") synchronized Collection<Xid> recoverFromDisk() { Path logFile = getLogFile(); if (!logFile.toFile().exists()) { log.debugf("There is no file %s with recovery data for the test XAResource, no data for recovery", logFile); return new ArrayList<>(); } log.debugf("There is found file %s for transaction recovery of the test XAResource", logFile); FileInputStream fis = null; try { fis = new FileInputStream(logFile.toFile()); ObjectInputStream ois = new ObjectInputStream(fis); Collection<Xid> xids = (Collection<Xid>) ois.readObject(); log.infof("Number of xids for recovery is %d.%nContent: %s", xids.size(), xids); return xids; } catch (Exception e) { log.errorf(e, "Cannot load recovery data for test XAResource from file %s", logFile); return new ArrayList<>(); } finally { try { if (fis != null) fis.close(); } catch (IOException ioe) { log.debugf(ioe,"Cannot close FileInputStrem for file %s", logFile); } } } private Path getLogFile() { try { File dataDir = new File(System.getProperty("jboss.server.data.dir")); dataDir.mkdirs(); return dataDir.toPath().resolve(this.fileToPersit); } catch (InvalidPathException e) { throw new IllegalStateException("Cannot resolve path of recovery file " + this.fileToPersit + " for storing test XAResource data persistently"); } } }
4,373
38.763636
120
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/PersistentTestXAResource.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.transactions; import java.util.Collection; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.jboss.logging.Logger; /** * <p> * Enhancement of the {@link TestXAResource} which saves prepared {@link Xid} to file system. * and delete it from the file on call <code>commit/rollback/forget</code>. * </p> * <p> * Such a {@link Xid} may be reported back to Narayana during periodic recovery when {@link XAResource#recover(int)} * is called. * </p> */ public class PersistentTestXAResource extends TestXAResource implements XAResource { private static final Logger log = Logger.getLogger(PersistentTestXAResource.class); private XidsPersister xidsPersister = new XidsPersister(PersistentTestXAResource.class.getSimpleName()); public PersistentTestXAResource() { super(); } public PersistentTestXAResource(TransactionCheckerSingleton checker) { super(checker); } public PersistentTestXAResource(TestAction testAction) { super(testAction); } public PersistentTestXAResource(TestAction testAction, TransactionCheckerSingleton checker) { super(testAction, checker); } @Override public int prepare(Xid xid) throws XAException { int prepareResult = super.prepare(xid); xidsPersister.writeToDisk(super.getPreparedXids()); log.debugf("Prepared xid [%s] was persisted", xid); return prepareResult; } @Override public void commit(Xid xid, boolean onePhase) throws XAException { super.commit(xid, onePhase); xidsPersister.writeToDisk(super.getPreparedXids()); } @Override public void rollback(Xid xid) throws XAException { super.rollback(xid); xidsPersister.writeToDisk(super.getPreparedXids()); } @Override public void forget(Xid xid) throws XAException { super.forget(xid); xidsPersister.writeToDisk(super.getPreparedXids()); } @Override public Xid[] recover(int flag) throws XAException { Collection<Xid> recoveredXids = xidsPersister.recoverFromDisk(); log.debugf("Recover call with flag %d returned %s", recoveredXids); return recoveredXids.toArray(new Xid[]{}); } }
3,352
34.294737
116
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/TestXAResource.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.transactions; import java.util.ArrayList; import java.util.List; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import org.jboss.logging.Logger; /** * Test {@link XAResource} class. * * @author Ondra Chaloupka <ochaloup@redhat.com> */ public class TestXAResource implements XAResource { private static Logger log = Logger.getLogger(TestXAResource.class); public enum TestAction { NONE, PREPARE_THROW_XAER_RMERR, PREPARE_THROW_XAER_RMFAIL, PREPARE_THROW_UNKNOWN_XA_EXCEPTION, PREPARE_CRASH_VM, COMMIT_THROW_XAER_RMERR, COMMIT_THROW_XAER_RMFAIL, COMMIT_THROW_XA_RBROLLBACK, COMMIT_THROW_UNKNOWN_XA_EXCEPTION, COMMIT_CRASH_VM, } // prepared xids are shared over all the TestXAResource instances in the JVM // used for the recovery purposes as the XAResourceRecoveryHelper works with a different instance // of the XAResource than the one which is used during 2PC processing private static final List<Xid> preparedXids = new ArrayList<>(); private TransactionCheckerSingleton checker; private int transactionTimeout; protected TestAction testAction; public TestXAResource(TransactionCheckerSingleton checker) { this(TestAction.NONE, checker); } public TestXAResource() { this(TestAction.NONE); } public TestXAResource(TestAction testAction) { // the checker singleton can't be used to check processing as it's not injected as a bean this(testAction, new TransactionCheckerSingleton()); } public TestXAResource(TestAction testAction, TransactionCheckerSingleton checker) { log.debugf("created %s with testAction %s and checker %s", this.getClass().getName(), testAction, checker); this.checker = checker; this.testAction = testAction; } @Override public int prepare(Xid xid) throws XAException { log.debugf("prepare xid: [%s], test action: %s", xid, testAction); checker.addPrepare(); switch (testAction) { case PREPARE_THROW_XAER_RMERR: throw new XAException(XAException.XAER_RMERR); case PREPARE_THROW_XAER_RMFAIL: throw new XAException(XAException.XAER_RMFAIL); case PREPARE_THROW_UNKNOWN_XA_EXCEPTION: throw new XAException(null); case PREPARE_CRASH_VM: Runtime.getRuntime().halt(0); case NONE: default: preparedXids.add(xid); return XAResource.XA_OK; } } @Override public void commit(Xid xid, boolean onePhase) throws XAException { log.debugf("commit xid:[%s], %s one phase, test action: %s", xid, onePhase ? "with" : "without", testAction); checker.addCommit(); switch (testAction) { case COMMIT_THROW_XAER_RMERR: throw new XAException(XAException.XAER_RMERR); case COMMIT_THROW_XAER_RMFAIL: throw new XAException(XAException.XAER_RMFAIL); case COMMIT_THROW_XA_RBROLLBACK: throw new XAException(XAException.XA_RBROLLBACK); case COMMIT_THROW_UNKNOWN_XA_EXCEPTION: throw new XAException(null); case COMMIT_CRASH_VM: Runtime.getRuntime().halt(0); case NONE: default: preparedXids.remove(xid); } } @Override public void rollback(Xid xid) throws XAException { log.debugf("rollback xid: [%s]", xid); checker.addRollback(); preparedXids.remove(xid); } @Override public void end(Xid xid, int flags) throws XAException { log.debugf("end xid:[%s], flag: %s", xid, flags); } @Override public void forget(Xid xid) throws XAException { log.debugf("forget xid:[%s]", xid); preparedXids.remove(xid); } @Override public int getTransactionTimeout() throws XAException { log.debugf("getTransactionTimeout: returning timeout: %s", transactionTimeout); return transactionTimeout; } @Override public boolean isSameRM(XAResource xares) throws XAException { log.debugf("isSameRM returning false to xares: %s", xares); return false; } @Override public Xid[] recover(int flag) throws XAException { log.debugf("recover with flags: %s", flag); return preparedXids.toArray(new Xid[0]); } @Override public boolean setTransactionTimeout(int seconds) throws XAException { log.debugf("setTransactionTimeout: setting timeout: %s", seconds); this.transactionTimeout = seconds; return true; } @Override public void start(Xid xid, int flags) throws XAException { log.debugf("start xid: [%s], flags: %s", xid, flags); } public List<Xid> getPreparedXids() { return preparedXids; } }
6,036
34.098837
138
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/TransactionCheckerSingletonRemote.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.transactions; import java.util.Collection; import jakarta.ejb.Remote; /** * Interface used as remote point to {@link TransactionCheckerSingleton} class * that is used for verification of test workflow. * * @author Ondra Chaloupka <ochaloup@redhat.com> */ @Remote public interface TransactionCheckerSingletonRemote { int getCommitted(); void addCommit(); void resetCommitted(); int getPrepared(); void addPrepare(); void resetPrepared(); int getRolledback(); void addRollback(); void resetRolledback(); boolean isSynchronizedBefore(); int countSynchronizedBefore(); void setSynchronizedBefore(); void resetSynchronizedBefore(); boolean isSynchronizedAfter(); int countSynchronizedAfter(); int countSynchronizedAfterCommitted(); int countSynchronizedAfterRolledBack(); void setSynchronizedAfter(boolean isCommit); void resetSynchronizedAfter(); boolean isSynchronizedBegin(); int countSynchronizedBegin(); void setSynchronizedBegin(); void resetSynchronizedBegin(); void addMessage(String msg); Collection<String> getMessages(); void resetMessages(); void resetAll(); }
2,250
33.630769
78
java
null
wildfly-main/testsuite/shared/src/main/java/org/jboss/as/test/integration/transactions/TxTestUtil.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.transactions; import javax.transaction.xa.XAResource; import jakarta.transaction.RollbackException; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import jakarta.transaction.TransactionSynchronizationRegistry; import org.jboss.as.test.shared.TimeoutUtil; import org.junit.Assert; /** * Transaction util class which works with transaction like * getting state, enlisting xa resource, adding synchronization... * * @author Ondra Chaloupka <ochaloup@redhat.com> */ public final class TxTestUtil { public static final int timeoutWaitTime_ms = 2500; private TxTestUtil() { // no instance here } public static TestXAResource enlistTestXAResource(TransactionManager tm, TransactionCheckerSingleton checker) { try { return enlistTestXAResource(tm.getTransaction(), checker); } catch (SystemException se) { throw new RuntimeException(String.format("Can't obtain transaction for transaction manager '%s' " + "to enlist %s", tm, TestXAResource.class.getName()), se); } } public static TestXAResource enlistTestXAResource(Transaction txn, TransactionCheckerSingleton checker) { TestXAResource xaResource = new TestXAResource(checker); try { txn.enlistResource(xaResource); } catch (IllegalStateException | RollbackException | SystemException e) { throw new RuntimeException("Can't enlist test xa resource '" + xaResource + "'", e); } return xaResource; } public static void enlistTestXAResource(Transaction txn, XAResource xaResource) { try { txn.enlistResource(xaResource); } catch (IllegalStateException | RollbackException | SystemException e) { throw new RuntimeException("Can't enlist test xa resource '" + xaResource + "'", e); } } public static void addSynchronization(TransactionManager tm, TransactionCheckerSingletonRemote checker) { try { addSynchronization(tm.getTransaction(), checker); } catch (SystemException se) { throw new RuntimeException(String.format("Can't obtain transaction for transaction manager '%s' " + "to enlist add test synchronization '%s'"), se); } } public static void addSynchronization(Transaction txn, TransactionCheckerSingletonRemote checker) { TestSynchronization synchro = new TestSynchronization(checker); try { txn.registerSynchronization(synchro); } catch (IllegalStateException | RollbackException | SystemException e) { throw new RuntimeException("Can't register synchronization '" + synchro + "' to txn '" + txn + "'", e); } } public static void addSynchronization(TransactionSynchronizationRegistry registry, TransactionCheckerSingletonRemote checker) { TestSynchronization synchro = new TestSynchronization(checker); try { registry.registerInterposedSynchronization(synchro); } catch (IllegalStateException e) { throw new RuntimeException("Can't register synchronization '" + synchro + "' to synchro registry '" + registry+ "'", e); } } public static void waitForTimeout(TransactionManager tm) throws SystemException, InterruptedException { // waiting for timeout long startTime = System.currentTimeMillis(); while(System.currentTimeMillis() - startTime < TimeoutUtil.adjust(timeoutWaitTime_ms) && tm.getStatus() == Status.STATUS_ACTIVE) { Thread.sleep(200); } } public static void checkTransactionExists(TransactionManager tm, boolean isExpectTransaction) { try { Transaction tx = tm.getTransaction(); if(!isExpectTransaction && tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) { Assert.fail("We do not expect transaction would be active - we haven't activated it in BMT bean"); } else if (isExpectTransaction && (tx == null || tx.getStatus() != Status.STATUS_ACTIVE)) { Assert.fail("We do expect tranaction would be active - we have alredy activated it in BMT bean"); } } catch (SystemException e) { throw new RuntimeException("Cannot get the current transaction from injected TransationManager!", e); } } public static String getStatusAsString(int statusCode) { switch(statusCode) { case Status.STATUS_ACTIVE: return "STATUS_ACTIVE"; case Status.STATUS_MARKED_ROLLBACK: return "STATUS_MARKED_ROLLBACK"; case Status.STATUS_PREPARED: return "STATUS_PREPARED"; case Status.STATUS_COMMITTED: return "STATUS_COMMITTED"; case Status.STATUS_ROLLEDBACK: return "STATUS_ROLLEDBACK"; case Status.STATUS_UNKNOWN: return "STATUS_UNKNOWN"; case Status.STATUS_NO_TRANSACTION: return "STATUS_NO_TRANSACTION"; case Status.STATUS_PREPARING: return "STATUS_PREPARING"; case Status.STATUS_COMMITTING: return "STATUS_COMMITTING"; case Status.STATUS_ROLLING_BACK: return "STATUS_ROLLING_BACK"; default: throw new IllegalStateException("Can't determine status code " + statusCode + " as transaction status code defined under " + Status.class.getName()); } } }
6,591
45.097902
138
java