diff options
author | 2016-09-13 11:40:12 +0800 | |
---|---|---|
committer | 2016-09-13 11:41:53 +0800 | |
commit | b731e2f1dd0972409b136aebc7b463dd72c9cfad (patch) | |
tree | 5107d7d80c19ad8076c2c97c2b5ef8d1cf3ab903 /framework/src/onos/utils/misc/src/main/java/org/onlab/util | |
parent | ee93993458266114c29271a481ef9ce7ce621b2a (diff) |
ONOSFW-171
O/S-SFC-ONOS scenario documentation
Change-Id: I51ae1cf736ea24ab6680f8edca1b2bf5dd598365
Signed-off-by: CNlucius <lukai1@huawei.com>
Diffstat (limited to 'framework/src/onos/utils/misc/src/main/java/org/onlab/util')
28 files changed, 0 insertions, 3370 deletions
diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/AbstractAccumulator.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/AbstractAccumulator.java deleted file mode 100644 index 500f8d60..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/AbstractAccumulator.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import com.google.common.collect.Lists; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Base implementation of an item accumulator. It allows triggering based on - * item inter-arrival time threshold, maximum batch life threshold and maximum - * batch size. - */ -public abstract class AbstractAccumulator<T> implements Accumulator<T> { - - private Logger log = LoggerFactory.getLogger(AbstractAccumulator.class); - - private final Timer timer; - private final int maxItems; - private final int maxBatchMillis; - private final int maxIdleMillis; - - private volatile TimerTask idleTask = new ProcessorTask(); - private volatile TimerTask maxTask = new ProcessorTask(); - - private List<T> items = Lists.newArrayList(); - - /** - * Creates an item accumulator capable of triggering on the specified - * thresholds. - * - * @param timer timer to use for scheduling check-points - * @param maxItems maximum number of items to accumulate before - * processing is triggered - * @param maxBatchMillis maximum number of millis allowed since the first - * item before processing is triggered - * @param maxIdleMillis maximum number millis between items before - * processing is triggered - */ - protected AbstractAccumulator(Timer timer, int maxItems, - int maxBatchMillis, int maxIdleMillis) { - this.timer = checkNotNull(timer, "Timer cannot be null"); - - checkArgument(maxItems > 1, "Maximum number of items must be > 1"); - checkArgument(maxBatchMillis > 0, "Maximum millis must be positive"); - checkArgument(maxIdleMillis > 0, "Maximum idle millis must be positive"); - - this.maxItems = maxItems; - this.maxBatchMillis = maxBatchMillis; - this.maxIdleMillis = maxIdleMillis; - } - - @Override - public synchronized void add(T item) { - idleTask = cancelIfActive(idleTask); - items.add(checkNotNull(item, "Item cannot be null")); - - // Did we hit the max item threshold? - if (items.size() >= maxItems) { - maxTask = cancelIfActive(maxTask); - scheduleNow(); - } else { - // Otherwise, schedule idle task and if this is a first item - // also schedule the max batch age task. - idleTask = schedule(maxIdleMillis); - if (items.size() == 1) { - maxTask = schedule(maxBatchMillis); - } - } - } - - /** - * Finalizes the current batch, if ready, and schedules a new processor - * in the immediate future. - */ - private void scheduleNow() { - if (isReady()) { - TimerTask task = new ProcessorTask(finalizeCurrentBatch()); - timer.schedule(task, 1); - } - } - - /** - * Schedules a new processor task given number of millis in the future. - * Batch finalization is deferred to time of execution. - */ - private TimerTask schedule(int millis) { - TimerTask task = new ProcessorTask(); - timer.schedule(task, millis); - return task; - } - - /** - * Cancels the specified task if it is active. - */ - private TimerTask cancelIfActive(TimerTask task) { - if (task != null) { - task.cancel(); - } - return task; - } - - // Task for triggering processing of accumulated items - private class ProcessorTask extends TimerTask { - - private final List<T> items; - - // Creates a new processor task with deferred batch finalization. - ProcessorTask() { - this.items = null; - } - - // Creates a new processor task with pre-emptive batch finalization. - ProcessorTask(List<T> items) { - this.items = items; - } - - @Override - public void run() { - synchronized (AbstractAccumulator.this) { - idleTask = cancelIfActive(idleTask); - } - if (isReady()) { - try { - synchronized (AbstractAccumulator.this) { - maxTask = cancelIfActive(maxTask); - } - List<T> batch = items != null ? items : finalizeCurrentBatch(); - if (!batch.isEmpty()) { - processItems(batch); - } - } catch (Exception e) { - log.warn("Unable to process batch due to", e); - } - } else { - synchronized (AbstractAccumulator.this) { - idleTask = schedule(maxIdleMillis); - } - } - } - } - - // Demotes and returns the current batch of items and promotes a new one. - private synchronized List<T> finalizeCurrentBatch() { - List<T> toBeProcessed = items; - items = Lists.newArrayList(); - return toBeProcessed; - } - - @Override - public boolean isReady() { - return true; - } - - /** - * Returns the backing timer. - * - * @return backing timer - */ - public Timer timer() { - return timer; - } - - /** - * Returns the maximum number of items allowed to accumulate before - * processing is triggered. - * - * @return max number of items - */ - public int maxItems() { - return maxItems; - } - - /** - * Returns the maximum number of millis allowed to expire since the first - * item before processing is triggered. - * - * @return max number of millis a batch is allowed to last - */ - public int maxBatchMillis() { - return maxBatchMillis; - } - - /** - * Returns the maximum number of millis allowed to expire since the last - * item arrival before processing is triggered. - * - * @return max number of millis since the last item - */ - public int maxIdleMillis() { - return maxIdleMillis; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Accumulator.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Accumulator.java deleted file mode 100644 index 20b7a481..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Accumulator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.List; - -/** - * Abstraction of an accumulator capable of collecting items and at some - * point in time triggers processing of all previously accumulated items. - * - * @param <T> item type - */ -public interface Accumulator<T> { - - /** - * Adds an item to the current batch. This operation may, or may not - * trigger processing of the current batch of items. - * - * @param item item to be added to the current batch - */ - void add(T item); - - /** - * Processes the specified list of accumulated items. - * - * @param items list of accumulated items - */ - void processItems(List<T> items); - - /** - * Indicates whether the accumulator is ready to process items. - * - * @return true if ready to process - */ - boolean isReady(); -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Bandwidth.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Bandwidth.java deleted file mode 100644 index 60806568..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Bandwidth.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import com.google.common.collect.ComparisonChain; - -import java.util.Objects; - -/** - * Representation of bandwidth. - * Use the static factory method corresponding to the unit (like Kbps) you desire on instantiation. - */ -public final class Bandwidth implements RichComparable<Bandwidth> { - - private final double bps; - - /** - * Creates a new instance with given bandwidth. - * - * @param bps bandwidth value to be assigned - */ - private Bandwidth(double bps) { - this.bps = bps; - } - - // Constructor for serialization - private Bandwidth() { - this.bps = 0; - } - - /** - * Creates a new instance with given bandwidth. - * - * @param v bandwidth value - * @param unit {@link DataRateUnit} of {@code v} - * @return {@link Bandwidth} instance with given bandwidth - */ - public static Bandwidth of(double v, DataRateUnit unit) { - return new Bandwidth(unit.toBitsPerSecond(v)); - } - - /** - * Creates a new instance with given bandwidth in bps. - * - * @param bps bandwidth value to be assigned - * @return {@link Bandwidth} instance with given bandwidth - */ - public static Bandwidth bps(double bps) { - return new Bandwidth(bps); - } - - /** - * Creates a new instance with given bandwidth in Kbps. - * - * @param kbps bandwidth value to be assigned - * @return {@link Bandwidth} instance with given bandwidth - */ - public static Bandwidth kbps(double kbps) { - return bps(kbps * 1_000L); - } - - /** - * Creates a new instance with given bandwidth in Mbps. - * - * @param mbps bandwidth value to be assigned - * @return {@link Bandwidth} instance with given bandwidth - */ - public static Bandwidth mbps(double mbps) { - return bps(mbps * 1_000_000L); - } - - /** - * Creates a new instance with given bandwidth in Gbps. - * - * @param gbps bandwidth value to be assigned - * @return {@link Bandwidth} instance with given bandwidth - */ - public static Bandwidth gbps(double gbps) { - return bps(gbps * 1_000_000_000L); - } - - /** - * Returns bandwidth in bps. - * - * @return bandwidth in bps. - */ - public double bps() { - return bps; - } - - /** - * Returns a Bandwidth whose value is (this + value). - * - * @param value value to be added to this Frequency - * @return this + value - */ - public Bandwidth add(Bandwidth value) { - return bps(this.bps + value.bps); - } - - /** - * Returns a Bandwidth whose value is (this - value). - * - * @param value value to be added to this Frequency - * @return this - value - */ - public Bandwidth subtract(Bandwidth value) { - return bps(this.bps - value.bps); - } - - @Override - public int compareTo(Bandwidth other) { - return ComparisonChain.start() - .compare(this.bps, other.bps) - .result(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Bandwidth) { - Bandwidth that = (Bandwidth) obj; - return Objects.equals(this.bps, that.bps); - } - return false; - } - - @Override - public int hashCode() { - return Long.hashCode(Double.doubleToLongBits(bps)); - } - - @Override - public String toString() { - return String.valueOf(this.bps); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/BlockingBoolean.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/BlockingBoolean.java deleted file mode 100644 index f3049c31..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/BlockingBoolean.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.AbstractQueuedSynchronizer; - -/** - * Mutable boolean that allows threads to wait for a specified value. - */ -public class BlockingBoolean extends AbstractQueuedSynchronizer { - - private static final int TRUE = 1; - private static final int FALSE = 0; - - /** - * Creates a new blocking boolean with the specified value. - * - * @param value the starting value - */ - public BlockingBoolean(boolean value) { - setState(value ? TRUE : FALSE); - } - - /** - * Causes the current thread to wait until the boolean equals the specified - * value unless the thread is {@linkplain Thread#interrupt interrupted}. - * - * @param value specified value - * @throws InterruptedException if interrupted while waiting - */ - public void await(boolean value) throws InterruptedException { - acquireSharedInterruptibly(value ? TRUE : FALSE); - } - - /** - * Causes the current thread to wait until the boolean equals the specified - * value unless the thread is {@linkplain Thread#interrupt interrupted}, - * or the specified waiting time elapses. - * - * @param value specified value - * @param timeout the maximum time to wait - * @param unit the time unit of the {@code timeout} argument - * @return {@code true} if the count reached zero and {@code false} - * if the waiting time elapsed before the count reached zero - * @throws InterruptedException if interrupted while waiting - */ - public boolean await(boolean value, long timeout, TimeUnit unit) - throws InterruptedException { - return tryAcquireSharedNanos(value ? TRUE : FALSE, unit.toNanos(timeout)); - } - - protected int tryAcquireShared(int acquires) { - return (getState() == acquires) ? 1 : -1; - } - - /** - * Sets the value of the blocking boolean. - * - * @param value new value - */ - public void set(boolean value) { - releaseShared(value ? TRUE : FALSE); - } - - /** - * Gets the value of the blocking boolean. - * - * @return current value - */ - public boolean get() { - return getState() == TRUE; - } - - protected boolean tryReleaseShared(int releases) { - // Signal on state change only - int state = getState(); - if (state == releases) { - return false; - } - return compareAndSetState(state, releases); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/BoundedThreadPool.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/BoundedThreadPool.java deleted file mode 100644 index 9eef6609..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/BoundedThreadPool.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import org.slf4j.LoggerFactory; - -import java.util.concurrent.Callable; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Implementation of ThreadPoolExecutor that bounds the work queue. - * <p> - * When a new job would exceed the queue bound, the job is run on the caller's - * thread rather than on a thread from the pool. - * </p> - */ -public final class BoundedThreadPool extends ThreadPoolExecutor { - - private static final org.slf4j.Logger log = LoggerFactory.getLogger(BoundedThreadPool.class); - - protected static int maxQueueSize = 80_000; //TODO tune this value - //private static final RejectedExecutionHandler DEFAULT_HANDLER = new CallerFeedbackPolicy(); - private static final long STATS_INTERVAL = 5_000; //ms - - private final BlockingBoolean underHighLoad; - - private BoundedThreadPool(int numberOfThreads, - ThreadFactory threadFactory) { - super(numberOfThreads, numberOfThreads, - 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(maxQueueSize), - threadFactory, - new CallerFeedbackPolicy()); - underHighLoad = ((CallerFeedbackPolicy) getRejectedExecutionHandler()).load(); - } - - /** - * Returns a single-thread, bounded executor service. - * - * @param threadFactory thread factory for the worker thread. - * @return the bounded thread pool - */ - public static BoundedThreadPool newSingleThreadExecutor(ThreadFactory threadFactory) { - return new BoundedThreadPool(1, threadFactory); - } - - /** - * Returns a fixed-size, bounded executor service. - * - * @param numberOfThreads number of threads in the pool - * @param threadFactory thread factory for the worker threads. - * @return the bounded thread pool - */ - public static BoundedThreadPool newFixedThreadPool(int numberOfThreads, ThreadFactory threadFactory) { - return new BoundedThreadPool(numberOfThreads, threadFactory); - } - - //TODO Might want to switch these to use Metrics class Meter and/or Gauge instead. - private final Counter submitted = new Counter(); - private final Counter taken = new Counter(); - - @Override - public Future<?> submit(Runnable task) { - submitted.add(1); - return super.submit(task); - } - - @Override - public <T> Future<T> submit(Runnable task, T result) { - submitted.add(1); - return super.submit(task, result); - } - - @Override - public void execute(Runnable command) { - submitted.add(1); - super.execute(command); - } - - @Override - public <T> Future<T> submit(Callable<T> task) { - submitted.add(1); - return super.submit(task); - } - - - @Override - protected void beforeExecute(Thread t, Runnable r) { - super.beforeExecute(t, r); - taken.add(1); - periodicallyPrintStats(); - updateLoad(); - } - - // TODO schedule this with a fixed delay from a scheduled executor - private final AtomicLong lastPrinted = new AtomicLong(0L); - - private void periodicallyPrintStats() { - long now = System.currentTimeMillis(); - long prev = lastPrinted.get(); - if (now - prev > STATS_INTERVAL) { - if (lastPrinted.compareAndSet(prev, now)) { - log.debug("queue size: {} jobs, submitted: {} jobs/s, taken: {} jobs/s", - getQueue().size(), - submitted.throughput(), taken.throughput()); - submitted.reset(); - taken.reset(); - } - } - } - - // TODO consider updating load whenever queue changes - private void updateLoad() { - underHighLoad.set(getQueue().remainingCapacity() / (double) maxQueueSize < 0.2); - } - - /** - * Feedback policy that delays the caller's thread until the executor's work - * queue falls below a threshold, then runs the job on the caller's thread. - */ - private static final class CallerFeedbackPolicy implements RejectedExecutionHandler { - - private final BlockingBoolean underLoad = new BlockingBoolean(false); - - public BlockingBoolean load() { - return underLoad; - } - - /** - * Executes task r in the caller's thread, unless the executor - * has been shut down, in which case the task is discarded. - * - * @param r the runnable task requested to be executed - * @param e the executor attempting to execute this task - */ - public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { - if (!e.isShutdown()) { - // Wait for up to 1 second while the queue drains... - boolean notified = false; - try { - notified = underLoad.await(false, 1, TimeUnit.SECONDS); - } catch (InterruptedException exception) { - log.debug("Got exception waiting for notification:", exception); - } finally { - if (!notified) { - log.info("Waited for 1 second on {}. Proceeding with work...", - Thread.currentThread().getName()); - } else { - log.info("FIXME we got a notice"); - } - } - // Do the work on the submitter's thread - r.run(); - } - } - } -}
\ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/ByteArraySizeHashPrinter.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/ByteArraySizeHashPrinter.java deleted file mode 100644 index cc39ce28..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/ByteArraySizeHashPrinter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.Arrays; - -import com.google.common.base.MoreObjects; -import com.google.common.base.MoreObjects.ToStringHelper; - -/** - * Helper to print byte[] length and hashCode. - */ -public final class ByteArraySizeHashPrinter { - - private final byte[] bytes; - - /** - * Returns ByteArraySizeHashPrinter wrapping given byte[]. - * - * @param bytes bytes to wrap around - * @return ByteArraySizeHashPrinter - */ - public static ByteArraySizeHashPrinter of(byte[] bytes) { - return new ByteArraySizeHashPrinter(bytes); - } - - /** - * Returns ByteArraySizeHashPrinter wrapping given byte[]. - * - * @param bytes bytes to wrap around - * @return null if {@code bytes == null}, ByteArraySizeHashPrinter otherwise - */ - public static ByteArraySizeHashPrinter orNull(byte[] bytes) { - if (bytes == null) { - return null; - } - return new ByteArraySizeHashPrinter(bytes); - } - - public ByteArraySizeHashPrinter(byte[] bytes) { - this.bytes = bytes; - } - - @Override - public String toString() { - ToStringHelper helper = MoreObjects.toStringHelper("byte[]"); - if (bytes != null) { - helper.add("length", bytes.length) - .add("hash", Arrays.hashCode(bytes)); - } else { - helper.addValue(bytes); - } - return helper.toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Counter.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Counter.java deleted file mode 100644 index bde28783..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Counter.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.Objects; - -import static com.google.common.base.MoreObjects.toStringHelper; -import static com.google.common.base.Preconditions.checkArgument; - -/** - * Counting mechanism capable of tracking occurrences and rates. - */ -public class Counter { - - private long total = 0; - private long start = System.currentTimeMillis(); - private long end = 0; - - /** - * Creates a new counter. - */ - public Counter() { - } - - /** - * Creates a new counter in a specific state. If non-zero end time is - * specified, the counter will be frozen. - * - * @param start start time - * @param total total number of items to start with - * @param end end time; if non-ze - */ - public Counter(long start, long total, long end) { - checkArgument(start <= end, "Malformed interval: start > end"); - checkArgument(total >= 0, "Total must be non-negative"); - this.start = start; - this.total = total; - this.end = end; - } - - /** - * Resets the counter, by zeroing out the count and restarting the timer. - */ - public synchronized void reset() { - end = 0; - total = 0; - start = System.currentTimeMillis(); - } - - /** - * Freezes the counter in the current state including the counts and times. - */ - public synchronized void freeze() { - end = System.currentTimeMillis(); - } - - /** - * Adds the specified number of occurrences to the counter. No-op if the - * counter has been frozen. - * - * @param count number of occurrences - */ - public synchronized void add(long count) { - checkArgument(count >= 0, "Count must be non-negative"); - if (end == 0L) { - total += count; - } - } - - /** - * Returns the number of occurrences per second. - * - * @return throughput in occurrences per second - */ - public synchronized double throughput() { - return total / duration(); - } - - /** - * Returns the total number of occurrences counted. - * - * @return number of counted occurrences - */ - public synchronized long total() { - return total; - } - - /** - * Returns the duration expressed in fractional number of seconds. - * - * @return fractional number of seconds since the last reset - */ - public synchronized double duration() { - // Protect against 0 return by artificially setting duration to 1ms - long duration = (end == 0L ? System.currentTimeMillis() : end) - start; - return (duration == 0 ? 1 : duration) / 1000.0; - } - - @Override - public int hashCode() { - return Objects.hash(total, start, end); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof Counter) { - final Counter other = (Counter) obj; - return Objects.equals(this.total, other.total) && - Objects.equals(this.start, other.start) && - Objects.equals(this.end, other.end); - } - return false; - } - - @Override - public String toString() { - return toStringHelper(this) - .add("total", total) - .add("start", start) - .add("end", end) - .toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/DataRateUnit.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/DataRateUnit.java deleted file mode 100644 index d49ed7b5..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/DataRateUnit.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.onlab.util; - -import com.google.common.annotations.Beta; - -/** - * Data rate unit. - */ -@Beta -public enum DataRateUnit { - /** - * Bit per second. - */ - BPS(1L), - /** - * Kilobit per second. - * (Decimal/SI) - */ - KBPS(1_000L), - /** - * Megabit per second. - * (Decimal/SI) - */ - MBPS(1_000_000L), - /** - * Gigabit per second. - * (Decimal/SI) - */ - GBPS(1_000_000_000L); - - private final long multiplier; - - DataRateUnit(long multiplier) { - this.multiplier = multiplier; - } - - /** - * Returns the multiplier to use, when converting value of this unit to bps. - * - * @return multiplier - */ - public long multiplier() { - return multiplier; - } - - /** - * Converts given value in this unit to bits per seconds. - * - * @param v data rate value - * @return {@code v} in bits per seconds - */ - public long toBitsPerSecond(long v) { - return v * multiplier; - } - - /** - * Converts given value in this unit to bits per seconds. - * - * @param v data rate value - * @return {@code v} in bits per seconds - */ - public double toBitsPerSecond(double v) { - return v * multiplier; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/DefaultHashMap.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/DefaultHashMap.java deleted file mode 100644 index d6ddbd56..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/DefaultHashMap.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.HashMap; - -/** - * HashMap that returns a default value for unmapped keys. - */ -public final class DefaultHashMap<K, V> extends HashMap<K, V> { - - /** Default value to return when no key binding exists. */ - protected final V defaultValue; - - /** - * Constructs an empty map with the given default value. - * - * @param defaultValue the default value - */ - public DefaultHashMap(V defaultValue) { - this.defaultValue = defaultValue; - } - - @Override - public V get(Object k) { - return containsKey(k) ? super.get(k) : defaultValue; - } -}
\ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Frequency.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Frequency.java deleted file mode 100644 index 1ef71130..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Frequency.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import com.google.common.base.MoreObjects; -import com.google.common.collect.ComparisonChain; - -/** - * Class representing frequency. This class is intended to be used for a value whose unit is Hz - * and its family (KHz, MHz, etc.). - * - * <p> - * Note: this class is mainly intended to be used for lambda, which - * represents THz order. Long has enough space to represent over THz frequency as Hz, - * and the underlying value is long as Hz. This means this class can't represent - * sub-Hz accuracy. - * </p> - */ -public final class Frequency implements RichComparable<Frequency> { - - private static final long KHZ = 1_000L; - private static final long MHZ = 1_000_000L; - private static final long GHZ = 1_000_000_000L; - private static final long THZ = 1_000_000_000_000L; - - private final long frequency; // frequency in Hz - - /** - * Creates an instance representing the specified frequency in Hz. - * - * @param frequency frequency in Hz - */ - private Frequency(long frequency) { - this.frequency = frequency; - } - - /** - * Return the value this instance represents as Hz. - * - * @return frequency in Hz - */ - public long asHz() { - return frequency; - } - - /** - * Returns an instance representing the specified value in Hz. - * - * @param value frequency in Hz - * @return instance representing the given frequency - */ - public static Frequency ofHz(long value) { - return new Frequency(value); - } - - /** - * Returns an instance representing the specified value in KHz. - * - * @param value frequency in KHz - * @return instance representing the given frequency - */ - public static Frequency ofKHz(double value) { - return new Frequency((long) (value * KHZ)); - } - - /** - * Returns an instance representing the specified value in MHz. - * - * @param value frequency in MHz - * @return instance representing the given frequency - */ - public static Frequency ofMHz(double value) { - return new Frequency((long) (value * MHZ)); - } - - /** - * Returns an instance representing the specified value in GHz. - * - * @param value frequency in GHz - * @return instance representing the given frequency - */ - public static Frequency ofGHz(double value) { - return new Frequency((long) (value * GHZ)); - } - - /** - * Returns an instance representing the specified value in THz. - * - * @param value frequency in THz - * @return instance representing the given frequency - */ - public static Frequency ofTHz(double value) { - return new Frequency((long) (value * THZ)); - } - - /** - * Returns a Frequency whose value is (this + value). - * - * @param value value to be added to this Frequency - * @return this + value - */ - public Frequency add(Frequency value) { - return new Frequency(this.frequency + value.frequency); - } - - /** - * Returns a Frequency whose value is (this - value). - * - * @param value value to be subtracted from this Frequency - * @return this - value - */ - public Frequency subtract(Frequency value) { - return new Frequency(this.frequency - value.frequency); - } - - /** - * Returns a Frequency whose value is (this * value). - * - * @param value value to be multiplied by this Frequency - * @return this * value - */ - public Frequency multiply(long value) { - return new Frequency(this.frequency * value); - } - - /** - * Returns a Frequency whose value is Math.floorDiv(this, value). - * - * @param value value to be divided by this Frequency - * @return Math.floorDiv(this, value) - */ - public Frequency floorDivision(long value) { - return new Frequency(Math.floorDiv(this.frequency, value)); - } - - @Override - public int compareTo(Frequency other) { - return ComparisonChain.start() - .compare(this.frequency, other.frequency) - .result(); - } - - @Override - public int hashCode() { - return Long.hashCode(frequency); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof Frequency)) { - return false; - } - - final Frequency other = (Frequency) obj; - return this.frequency == other.frequency; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("frequency", frequency + "Hz") - .toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/GeoLocation.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/GeoLocation.java deleted file mode 100644 index 7e546531..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/GeoLocation.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.util; - -import com.google.common.base.MoreObjects; - -/** - * Geo location specified in terms of longitude and latitude. - */ -public class GeoLocation { - - public static final double EARTH_RADIUS_KM = 6378.1370D; - - private final double latitude; - private final double longitude; - - /** - * Creates a new location using the specified coordinates. - * - * @param latitude latitude line - * @param longitude longitude line - */ - public GeoLocation(double latitude, double longitude) { - this.latitude = latitude; - this.longitude = longitude; - } - - /** - * Returns the latitude of this location. - * - * @return latitude - */ - public double latitude() { - return latitude; - } - - /** - * Returns the longitude of this location. - * - * @return longitude - */ - public double longitude() { - return longitude; - } - - /** - * Returns the distance in kilometers, between this location and another. - * - * @param other other geo location - * @return distance in kilometers - */ - public double kilometersTo(GeoLocation other) { - double hereLat = Math.toRadians(latitude); - double hereLon = Math.toRadians(longitude); - double thereLat = Math.toRadians(other.latitude); - double thereLon = Math.toRadians(other.longitude); - - double cos = Math.sin(hereLat) * Math.sin(thereLat) + - Math.cos(hereLat) * Math.cos(thereLat) * Math.cos(hereLon - thereLon); - return Math.acos(cos) * EARTH_RADIUS_KM; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("latitude", latitude) - .add("longitude", longitude) - .toString(); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/GroupedThreadFactory.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/GroupedThreadFactory.java deleted file mode 100644 index 9001cf5f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/GroupedThreadFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import org.apache.commons.lang3.concurrent.ConcurrentUtils; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ThreadFactory; - -import static com.google.common.base.MoreObjects.toStringHelper; - -/** - * Thread factory for creating threads that belong to the specified thread group. - */ -public final class GroupedThreadFactory implements ThreadFactory { - - public static final String DELIMITER = "/"; - - private final ThreadGroup group; - - // Cache of created thread factories. - private static final ConcurrentHashMap<String, GroupedThreadFactory> FACTORIES = - new ConcurrentHashMap<>(); - - /** - * Returns thread factory for producing threads associated with the specified - * group name. The group name-space is hierarchical, based on slash-delimited - * name segments, e.g. {@code onos/intent}. - * - * @param groupName group name - * @return thread factory - */ - public static GroupedThreadFactory groupedThreadFactory(String groupName) { - GroupedThreadFactory factory = FACTORIES.get(groupName); - if (factory != null) { - return factory; - } - - // Find the parent group or root the group hierarchy under default group. - int i = groupName.lastIndexOf(DELIMITER); - if (i > 0) { - String name = groupName.substring(0, i); - ThreadGroup parentGroup = groupedThreadFactory(name).threadGroup(); - factory = new GroupedThreadFactory(new ThreadGroup(parentGroup, groupName)); - } else { - factory = new GroupedThreadFactory(new ThreadGroup(groupName)); - } - - return ConcurrentUtils.putIfAbsent(FACTORIES, groupName, factory); - } - - // Creates a new thread group - private GroupedThreadFactory(ThreadGroup group) { - this.group = group; - } - - /** - * Returns the thread group associated with the factory. - * - * @return thread group - */ - public ThreadGroup threadGroup() { - return group; - } - - @Override - public Thread newThread(Runnable r) { - return new Thread(group, r); - } - - @Override - public String toString() { - return toStringHelper(this).add("group", group).toString(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexDump.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexDump.java deleted file mode 100755 index cfb79390..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexDump.java +++ /dev/null @@ -1,57 +0,0 @@ -/*
- * Copyright 2015 Open Networking Laboratory
- *
- * 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.onlab.util;
-
-import org.jboss.netty.buffer.ChannelBuffer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * HexDump class an utility to dump buffer in hex format.
- */
-public final class HexDump {
- protected static final Logger log = LoggerFactory.getLogger(HexDump.class);
-
- private HexDump() {
- }
-
- /**
- * Dump the buffer content in hex format.
- *
- * @param buff buffer content to dump in hex format
- */
- public static void dump(ChannelBuffer buff) {
- try {
- byte[] yTemp;
- yTemp = buff.array();
-
- int iStartIndex = buff.readerIndex();
- int iEndIndex = buff.writerIndex();
- do {
- StringBuilder sb = new StringBuilder();
- for (int k = 0; (k < 16) && (iStartIndex < iEndIndex); ++k) {
- if (0 == k % 4) {
- sb.append(String.format(" ")); // blank after 4 bytes
- }
- sb.append(String.format("%02X ", yTemp[iStartIndex++]));
- }
- log.debug(sb.toString());
- } while (iStartIndex < iEndIndex);
- } catch (Exception e) {
- log.error("[HexDump] Invalid buffer: " + e.toString());
- }
- }
-}
diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexString.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexString.java deleted file mode 100644 index 962e1119..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/HexString.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.util; - -public final class HexString { - - private HexString() { - } - - /** - * Convert a byte array to a colon-separated hex string. - * - * @param bytes byte array to be converted - * @return converted colon-separated hex string, e.g. "0f:ca:fe:de:ad:be:ef", - * or "(null)" if given byte array is null - */ - public static String toHexString(final byte[] bytes) { - return toHexString(bytes, ":"); - } - - /** - * Convert a byte array to a hex string separated by given separator. - * - * @param bytes byte array to be converted - * @param separator the string use to separate each byte - * @return converted hex string, or "(null)" if given byte array is null - */ - public static String toHexString(final byte[] bytes, String separator) { - if (bytes == null) { - return "(null)"; - } - if (separator == null) { - separator = ""; - } - int i; - StringBuilder ret = new StringBuilder(bytes.length * 3 - 1); - String tmp; - for (i = 0; i < bytes.length; i++) { - if (i > 0) { - ret.append(separator); - } - tmp = Integer.toHexString((bytes[i] & 0xff)); - if (tmp.length() == 1) { - ret.append('0'); - } - ret.append(tmp); - } - return ret.toString(); - } - - /** - * Convert a long number to colon-separated hex string. - * Prepend zero padding until given length. - * - * @param val long number to be converted - * @param padTo prepend zeros until this length - * @return converted colon-separated hex string, e.g. "0f:ca:fe:de:ad:be:ef" - */ - public static String toHexString(final long val, final int padTo) { - char[] arr = Long.toHexString(val).toCharArray(); - StringBuilder ret = new StringBuilder(padTo * 3 - 1); - // prepend the right number of leading zeros - int i = 0; - for (; i < (padTo * 2 - arr.length); i++) { - ret.append('0'); - if ((i % 2) != 0) { - ret.append(':'); - } - } - for (int j = 0; j < arr.length; j++) { - ret.append(arr[j]); - if ((((i + j) % 2) != 0) && (j < (arr.length - 1))) { - ret.append(':'); - } - } - return ret.toString(); - } - - /** - * Convert a long number to colon-separated hex string. - * Prepend zero padding until 8 bytes. - * - * @param val long number to be converted - * @return converted colon-separated hex string, e.g. "0f:ca:fe:de:ad:be:ef" - */ - public static String toHexString(final long val) { - return toHexString(val, 8); - } - - /** - * Convert a colon-separated hex string to byte array. - * - * @param values colon-separated hex string to be converted, - * e.g. "0f:ca:fe:de:ad:be:ef" - * @return converted byte array - * @throws NumberFormatException if input hex string cannot be parsed - */ - public static byte[] fromHexString(final String values) { - String[] octets = values.split(":"); - byte[] ret = new byte[octets.length]; - - for (int i = 0; i < octets.length; i++) { - if (octets[i].length() > 2) { - throw new NumberFormatException("Invalid octet length"); - } - ret[i] = Integer.valueOf(octets[i], 16).byteValue(); - } - return ret; - } - - /** - * Convert a colon-separated hex string to long. - * - * @param value colon-separated hex string to be converted, - * e.g. "00:0f:ca:fe:de:ad:be:ef" - * @return converted long number - * @throws NumberFormatException if input hex string cannot be parsed - */ - public static long toLong(String value) { - String[] octets = value.split(":"); - if (octets.length > 8) { - throw new NumberFormatException("Input string is too big to fit in long: " + value); - } - long l = 0; - for (String octet: octets) { - if (octet.length() > 2) { - throw new NumberFormatException( - "Each colon-separated byte component must consist of 1 or 2 hex digits: " + value); - } - short s = Short.parseShort(octet, 16); - l = (l << 8) + s; - } - return l; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/ItemNotFoundException.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/ItemNotFoundException.java deleted file mode 100644 index 01440abf..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/ItemNotFoundException.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.util; - -/** - * Represents condition where an item is not found or not available. - */ -public class ItemNotFoundException extends RuntimeException { - - /** - * Creates a new exception with no message. - */ - public ItemNotFoundException() { - } - - /** - * Creates a new exception with the supplied message. - * @param message error message - */ - public ItemNotFoundException(String message) { - super(message); - } - - /** - * Creates a new exception with the supplied message and cause. - * @param message error message - * @param cause cause of the error - */ - public ItemNotFoundException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/KryoNamespace.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/KryoNamespace.java deleted file mode 100644 index 9977e35d..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/KryoNamespace.java +++ /dev/null @@ -1,437 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.tuple.Pair; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Serializer; -import com.esotericsoftware.kryo.io.ByteBufferInput; -import com.esotericsoftware.kryo.io.ByteBufferOutput; -import com.esotericsoftware.kryo.io.Input; -import com.esotericsoftware.kryo.pool.KryoCallback; -import com.esotericsoftware.kryo.pool.KryoFactory; -import com.esotericsoftware.kryo.pool.KryoPool; -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableList; - -/** - * Pool of Kryo instances, with classes pre-registered. - */ -//@ThreadSafe -public final class KryoNamespace implements KryoFactory, KryoPool { - - /** - * Default buffer size used for serialization. - * - * @see #serialize(Object) - */ - public static final int DEFAULT_BUFFER_SIZE = 4096; - public static final int MAX_BUFFER_SIZE = 100 * 1000 * 1000; - - /** - * ID to use if this KryoNamespace does not define registration id. - */ - public static final int FLOATING_ID = -1; - - /** - * Smallest ID free to use for user defined registrations. - */ - public static final int INITIAL_ID = 11; - - - private final KryoPool pool = new KryoPool.Builder(this) - .softReferences() - .build(); - - private final ImmutableList<RegistrationBlock> registeredBlocks; - - private final boolean registrationRequired; - - - /** - * KryoNamespace builder. - */ - //@NotThreadSafe - public static final class Builder { - - private int blockHeadId = INITIAL_ID; - private List<Pair<Class<?>, Serializer<?>>> types = new ArrayList<>(); - private List<RegistrationBlock> blocks = new ArrayList<>(); - private boolean registrationRequired = true; - - /** - * Builds a {@link KryoNamespace} instance. - * - * @return KryoNamespace - */ - public KryoNamespace build() { - if (!types.isEmpty()) { - blocks.add(new RegistrationBlock(this.blockHeadId, types)); - } - return new KryoNamespace(blocks, registrationRequired).populate(1); - } - - /** - * Sets the next Kryo registration Id for following register entries. - * - * @param id Kryo registration Id - * @return this - * - * @see Kryo#register(Class, Serializer, int) - */ - public Builder nextId(final int id) { - if (!types.isEmpty()) { - blocks.add(new RegistrationBlock(this.blockHeadId, types)); - types = new ArrayList<>(); - } - this.blockHeadId = id; - return this; - } - - /** - * Registers classes to be serialized using Kryo default serializer. - * - * @param expectedTypes list of classes - * @return this - */ - public Builder register(final Class<?>... expectedTypes) { - for (Class<?> clazz : expectedTypes) { - types.add(Pair.of(clazz, null)); - } - return this; - } - - /** - * Registers a class and it's serializer. - * - * @param classes list of classes to register - * @param serializer serializer to use for the class - * @return this - */ - public Builder register(Serializer<?> serializer, final Class<?>... classes) { - for (Class<?> clazz : classes) { - types.add(Pair.of(clazz, serializer)); - } - return this; - } - - private Builder register(RegistrationBlock block) { - if (block.begin() != FLOATING_ID) { - // flush pending types - nextId(block.begin()); - blocks.add(block); - nextId(block.begin() + block.types().size()); - } else { - // flush pending types - final int addedBlockBegin = blockHeadId + types.size(); - nextId(addedBlockBegin); - blocks.add(new RegistrationBlock(addedBlockBegin, block.types())); - nextId(addedBlockBegin + block.types().size()); - } - return this; - } - - /** - * Registers all the class registered to given KryoNamespace. - * - * @param ns KryoNamespace - * @return this - */ - public Builder register(final KryoNamespace ns) { - for (RegistrationBlock block : ns.registeredBlocks) { - this.register(block); - } - return this; - } - - /** - * Sets the registrationRequired flag. - * - * @param registrationRequired Kryo's registrationRequired flag - * @return this - * - * @see Kryo#setRegistrationRequired(boolean) - */ - public Builder setRegistrationRequired(boolean registrationRequired) { - this.registrationRequired = registrationRequired; - return this; - } - } - - /** - * Creates a new {@link KryoNamespace} builder. - * - * @return builder - */ - public static Builder newBuilder() { - return new Builder(); - } - - /** - * Creates a Kryo instance pool. - * - * @param registeredTypes types to register - * @param registrationRequired - */ - private KryoNamespace(final List<RegistrationBlock> registeredTypes, boolean registrationRequired) { - this.registeredBlocks = ImmutableList.copyOf(registeredTypes); - this.registrationRequired = registrationRequired; - } - - /** - * Populates the Kryo pool. - * - * @param instances to add to the pool - * @return this - */ - public KryoNamespace populate(int instances) { - - for (int i = 0; i < instances; ++i) { - release(create()); - } - return this; - } - - /** - * Serializes given object to byte array using Kryo instance in pool. - * <p> - * Note: Serialized bytes must be smaller than {@link #MAX_BUFFER_SIZE}. - * - * @param obj Object to serialize - * @return serialized bytes - */ - public byte[] serialize(final Object obj) { - return serialize(obj, DEFAULT_BUFFER_SIZE); - } - - /** - * Serializes given object to byte array using Kryo instance in pool. - * - * @param obj Object to serialize - * @param bufferSize maximum size of serialized bytes - * @return serialized bytes - */ - public byte[] serialize(final Object obj, final int bufferSize) { - ByteBufferOutput out = new ByteBufferOutput(bufferSize, MAX_BUFFER_SIZE); - try { - Kryo kryo = borrow(); - try { - kryo.writeClassAndObject(out, obj); - out.flush(); - return out.toBytes(); - } finally { - release(kryo); - } - } finally { - out.release(); - } - } - - /** - * Serializes given object to byte buffer using Kryo instance in pool. - * - * @param obj Object to serialize - * @param buffer to write to - */ - public void serialize(final Object obj, final ByteBuffer buffer) { - ByteBufferOutput out = new ByteBufferOutput(buffer); - Kryo kryo = borrow(); - try { - kryo.writeClassAndObject(out, obj); - out.flush(); - } finally { - release(kryo); - } - } - - /** - * Serializes given object to OutputStream using Kryo instance in pool. - * - * @param obj Object to serialize - * @param stream to write to - */ - public void serialize(final Object obj, final OutputStream stream) { - serialize(obj, stream, DEFAULT_BUFFER_SIZE); - } - - /** - * Serializes given object to OutputStream using Kryo instance in pool. - * - * @param obj Object to serialize - * @param stream to write to - * @param bufferSize size of the buffer in front of the stream - */ - public void serialize(final Object obj, final OutputStream stream, final int bufferSize) { - ByteBufferOutput out = new ByteBufferOutput(stream, bufferSize); - Kryo kryo = borrow(); - try { - kryo.writeClassAndObject(out, obj); - out.flush(); - } finally { - release(kryo); - } - } - - /** - * Deserializes given byte array to Object using Kryo instance in pool. - * - * @param bytes serialized bytes - * @param <T> deserialized Object type - * @return deserialized Object - */ - public <T> T deserialize(final byte[] bytes) { - Input in = new Input(bytes); - Kryo kryo = borrow(); - try { - @SuppressWarnings("unchecked") - T obj = (T) kryo.readClassAndObject(in); - return obj; - } finally { - release(kryo); - } - } - - /** - * Deserializes given byte buffer to Object using Kryo instance in pool. - * - * @param buffer input with serialized bytes - * @param <T> deserialized Object type - * @return deserialized Object - */ - public <T> T deserialize(final ByteBuffer buffer) { - ByteBufferInput in = new ByteBufferInput(buffer); - Kryo kryo = borrow(); - try { - @SuppressWarnings("unchecked") - T obj = (T) kryo.readClassAndObject(in); - return obj; - } finally { - release(kryo); - } - } - - /** - * Deserializes given InputStream to an Object using Kryo instance in pool. - * - * @param stream input stream - * @param <T> deserialized Object type - * @return deserialized Object - */ - public <T> T deserialize(final InputStream stream) { - return deserialize(stream, DEFAULT_BUFFER_SIZE); - } - - /** - * Deserializes given InputStream to an Object using Kryo instance in pool. - * - * @param stream input stream - * @param <T> deserialized Object type - * @return deserialized Object - * @param bufferSize size of the buffer in front of the stream - */ - public <T> T deserialize(final InputStream stream, final int bufferSize) { - ByteBufferInput in = new ByteBufferInput(stream, bufferSize); - Kryo kryo = borrow(); - try { - @SuppressWarnings("unchecked") - T obj = (T) kryo.readClassAndObject(in); - return obj; - } finally { - release(kryo); - } - } - - /** - * Creates a Kryo instance. - * - * @return Kryo instance - */ - @Override - public Kryo create() { - Kryo kryo = new Kryo(); - kryo.setRegistrationRequired(registrationRequired); - for (RegistrationBlock block : registeredBlocks) { - int id = block.begin(); - if (id == FLOATING_ID) { - id = kryo.getNextRegistrationId(); - } - for (Pair<Class<?>, Serializer<?>> entry : block.types()) { - final Serializer<?> serializer = entry.getRight(); - if (serializer == null) { - kryo.register(entry.getLeft(), id++); - } else { - kryo.register(entry.getLeft(), serializer, id++); - } - } - } - return kryo; - } - - @Override - public Kryo borrow() { - return pool.borrow(); - } - - @Override - public void release(Kryo kryo) { - pool.release(kryo); - } - - @Override - public <T> T run(KryoCallback<T> callback) { - return pool.run(callback); - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("registeredBlocks", registeredBlocks) - .toString(); - } - - static final class RegistrationBlock { - private final int begin; - private final ImmutableList<Pair<Class<?>, Serializer<?>>> types; - - public RegistrationBlock(int begin, List<Pair<Class<?>, Serializer<?>>> types) { - this.begin = begin; - this.types = ImmutableList.copyOf(types); - } - - public int begin() { - return begin; - } - - public ImmutableList<Pair<Class<?>, Serializer<?>>> types() { - return types; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(getClass()) - .add("begin", begin) - .add("types", types) - .toString(); - } - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/NewConcurrentHashMap.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/NewConcurrentHashMap.java deleted file mode 100644 index 2d222eac..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/NewConcurrentHashMap.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.commons.lang3.concurrent.ConcurrentInitializer; - -/** - * Creates an instance of new ConcurrentHashMap on each {@link #get()} call. - * <p> - * To be used with - * {@link org.apache.commons.lang3.concurrent.ConcurrentUtils#createIfAbsent} - * </p> - * - * @param <K> ConcurrentHashMap key type - * @param <V> ConcurrentHashMap value type - */ -public final class NewConcurrentHashMap<K, V> - implements ConcurrentInitializer<ConcurrentMap<K, V>> { - - public static final NewConcurrentHashMap<?, ?> INSTANCE = new NewConcurrentHashMap<>(); - - @SuppressWarnings("unchecked") - public static <K, V> NewConcurrentHashMap<K, V> ifNeeded() { - return (NewConcurrentHashMap<K, V>) INSTANCE; - } - - @Override - public ConcurrentMap<K, V> get() { - return new ConcurrentHashMap<>(); - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/PositionalParameterStringFormatter.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/PositionalParameterStringFormatter.java deleted file mode 100644 index 647e0c0d..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/PositionalParameterStringFormatter.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -/** - * Allows slf4j style formatting of parameters into a string. - */ -public final class PositionalParameterStringFormatter { - - /** - * Hide default constructor. - */ - private PositionalParameterStringFormatter() { - } - - /** - * Formats a string using slf4j style positional parameter replacement. - * Instances of "{}" in the source string are replaced in order by the - * specified parameter values as strings. - * - * @param source original string to format - * @param parameters list of parameters that will be substituted - * @return formatted string - */ - public static String format(String source, Object... parameters) { - String current = source; - for (Object parameter : parameters) { - if (!current.contains("{}")) { - return current; - } - current = current.replaceFirst("\\{\\}", String.valueOf(parameter)); - } - return current; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/RetryingFunction.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/RetryingFunction.java deleted file mode 100644 index 484e236f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/RetryingFunction.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.function.Function; - -import com.google.common.base.Throwables; - -/** - * Function that retries execution on failure. - * - * @param <U> input type - * @param <V> output type - */ -public class RetryingFunction<U, V> implements Function<U, V> { - - private final Function<U, V> baseFunction; - private final Class<? extends Throwable> exceptionClass; - private final int maxRetries; - private final int maxDelayBetweenRetries; - - public RetryingFunction(Function<U, V> baseFunction, - Class<? extends Throwable> exceptionClass, - int maxRetries, - int maxDelayBetweenRetries) { - this.baseFunction = baseFunction; - this.exceptionClass = exceptionClass; - this.maxRetries = maxRetries; - this.maxDelayBetweenRetries = maxDelayBetweenRetries; - } - - @Override - public V apply(U input) { - int retryAttempts = 0; - while (true) { - try { - return baseFunction.apply(input); - } catch (Throwable t) { - if (!exceptionClass.isAssignableFrom(t.getClass()) || retryAttempts == maxRetries) { - Throwables.propagate(t); - } - Tools.randomDelay(maxDelayBetweenRetries); - retryAttempts++; - } - } - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/RichComparable.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/RichComparable.java deleted file mode 100644 index 8a49bba9..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/RichComparable.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Extends useful methods for comparison to {@link Comparable} interface. - * - * @param <T> type of instance to be compared - */ -public interface RichComparable<T> extends Comparable<T> { - /** - * Compares if this object is less than the specified object. - * - * @param other the object to be compared - * @return true if this object is less than the specified object - */ - default boolean isLessThan(T other) { - return compareTo(checkNotNull(other)) < 0; - } - - /** - * Compares if this object is greater than the specified object. - * - * @param other the object to be compared - * @return true if this object is less thant the specified object - */ - default boolean isGreaterThan(T other) { - return compareTo(checkNotNull(other)) > 0; - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java deleted file mode 100644 index 051155ce..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutorService.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Executor service wrapper for shared executors with safeguards on shutdown - * to prevent inadvertent shutdown. - */ -class SharedExecutorService implements ExecutorService { - - private static final String NOT_ALLOWED = "Shutdown of shared executor is not allowed"; - - private ExecutorService executor; - - /** - * Creates a wrapper for the given executor service. - * - * @param executor executor service to wrap - */ - SharedExecutorService(ExecutorService executor) { - this.executor = executor; - } - - /** - * Returns the backing executor service. - * - * @return backing executor service - */ - ExecutorService backingExecutor() { - return executor; - } - - /** - * Swaps the backing executor with a new one and shuts down the old one. - * - * @param executor new executor service - */ - void setBackingExecutor(ExecutorService executor) { - ExecutorService oldExecutor = this.executor; - this.executor = executor; - oldExecutor.shutdown(); - } - - @Override - public void shutdown() { - throw new UnsupportedOperationException(NOT_ALLOWED); - } - - @Override - public List<Runnable> shutdownNow() { - throw new UnsupportedOperationException(NOT_ALLOWED); - } - - @Override - public boolean isShutdown() { - return executor.isShutdown(); - } - - @Override - public boolean isTerminated() { - return executor.isTerminated(); - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) - throws InterruptedException { - return executor.awaitTermination(timeout, unit); - } - - @Override - public <T> Future<T> submit(Callable<T> task) { - return executor.submit(task); - } - - @Override - public <T> Future<T> submit(Runnable task, T result) { - return executor.submit(task, result); - } - - @Override - public Future<?> submit(Runnable task) { - return executor.submit(task); - } - - @Override - public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) - throws InterruptedException { - return executor.invokeAll(tasks); - } - - @Override - public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, - long timeout, TimeUnit unit) - throws InterruptedException { - return executor.invokeAll(tasks, timeout, unit); - } - - @Override - public <T> T invokeAny(Collection<? extends Callable<T>> tasks) - throws InterruptedException, ExecutionException { - return executor.invokeAny(tasks); - } - - @Override - public <T> T invokeAny(Collection<? extends Callable<T>> tasks, - long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - return executor.invokeAny(tasks, timeout, unit); - } - - @Override - public void execute(Runnable command) { - executor.execute(command); - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java deleted file mode 100644 index 0dadce85..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SharedExecutors.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.Timer; -import java.util.concurrent.ExecutorService; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.concurrent.Executors.newFixedThreadPool; -import static java.util.concurrent.Executors.newSingleThreadExecutor; -import static org.onlab.util.Tools.groupedThreads; - -/** - * Utility for managing a set of shared execution resources, such as a timer, - * single thread executor and thread pool executor for use by various parts of - * the platform or by applications. - * <p> - * Whenever possible, use of these shared resources is encouraged over creating - * separate ones. - * </p> - */ -public final class SharedExecutors { - - public static final int DEFAULT_POOL_SIZE = 30; - - private static SharedExecutorService singleThreadExecutor = - new SharedExecutorService( - newSingleThreadExecutor(groupedThreads("onos/shared", - "onos-single-executor"))); - - private static SharedExecutorService poolThreadExecutor = - new SharedExecutorService( - newFixedThreadPool(DEFAULT_POOL_SIZE, - groupedThreads("onos/shared", - "onos-pool-executor-%d"))); - - private static SharedTimer sharedTimer = new SharedTimer(); - - // Ban public construction - private SharedExecutors() { - } - - /** - * Returns the shared single thread executor. - * - * @return shared single thread executor - */ - public static ExecutorService getSingleThreadExecutor() { - return singleThreadExecutor; - } - - /** - * Returns the shared thread pool executor. - * - * @return shared executor pool - */ - public static ExecutorService getPoolThreadExecutor() { - return poolThreadExecutor; - } - - /** - * Returns the shared timer. - * - * @return shared timer - */ - public static Timer getTimer() { - return sharedTimer; - } - - /** - * Sets the shared thread pool size. - * - * @param poolSize new pool size - */ - public static void setPoolSize(int poolSize) { - checkArgument(poolSize > 0, "Shared pool size size must be greater than 0"); - poolThreadExecutor.setBackingExecutor( - newFixedThreadPool(poolSize, groupedThreads("onos/shared", - "onos-pool-executor-%d"))); - } - - /** - * Shuts down all shared timers and executors and therefore should be - * called only by the framework. - */ - public static void shutdown() { - sharedTimer.shutdown(); - singleThreadExecutor.backingExecutor().shutdown(); - poolThreadExecutor.backingExecutor().shutdown(); - } - - // Timer extension which does not allow outside cancel method. - private static class SharedTimer extends Timer { - - public SharedTimer() { - super("onos-shared-timer"); - } - - @Override - public void cancel() { - throw new UnsupportedOperationException("Cancel of shared timer is not allowed"); - } - - private void shutdown() { - super.cancel(); - } - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SlidingWindowCounter.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SlidingWindowCounter.java deleted file mode 100644 index 4f0093c0..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/SlidingWindowCounter.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Collectors; - -import static com.google.common.base.Preconditions.checkArgument; - -/** - * Maintains a sliding window of value counts. The sliding window counter is - * initialized with a number of window slots. Calls to #incrementCount() will - * increment the value in the current window slot. Periodically the window - * slides and the oldest value count is dropped. Calls to #get() will get the - * total count for the last N window slots. - */ -public final class SlidingWindowCounter { - - private volatile int headSlot; - private final int windowSlots; - - private final List<AtomicLong> counters; - - private final ScheduledExecutorService background; - - private static final int SLIDE_WINDOW_PERIOD_SECONDS = 1; - - /** - * Creates a new sliding window counter with the given total number of - * window slots. - * - * @param windowSlots total number of window slots - */ - public SlidingWindowCounter(int windowSlots) { - checkArgument(windowSlots > 0, "Window size must be a positive integer"); - - this.windowSlots = windowSlots; - this.headSlot = 0; - - // Initialize each item in the list to an AtomicLong of 0 - this.counters = Collections.nCopies(windowSlots, 0) - .stream() - .map(AtomicLong::new) - .collect(Collectors.toCollection(ArrayList::new)); - - background = Executors.newSingleThreadScheduledExecutor(); - background.scheduleWithFixedDelay(this::advanceHead, 0, - SLIDE_WINDOW_PERIOD_SECONDS, TimeUnit.SECONDS); - } - - /** - * Releases resources used by the SlidingWindowCounter. - */ - public void destroy() { - background.shutdownNow(); - } - - /** - * Increments the count of the current window slot by 1. - */ - public void incrementCount() { - incrementCount(headSlot, 1); - } - - /** - * Increments the count of the current window slot by the given value. - * - * @param value value to increment by - */ - public void incrementCount(long value) { - incrementCount(headSlot, value); - } - - private void incrementCount(int slot, long value) { - counters.get(slot).addAndGet(value); - } - - /** - * Gets the total count for the last N window slots. - * - * @param slots number of slots to include in the count - * @return total count for last N slots - */ - public long get(int slots) { - checkArgument(slots <= windowSlots, - "Requested window must be less than the total window slots"); - - long sum = 0; - - for (int i = 0; i < slots; i++) { - int currentIndex = headSlot - i; - if (currentIndex < 0) { - currentIndex = counters.size() + currentIndex; - } - sum += counters.get(currentIndex).get(); - } - - return sum; - } - - void advanceHead() { - counters.get(slotAfter(headSlot)).set(0); - headSlot = slotAfter(headSlot); - } - - private int slotAfter(int slot) { - return (slot + 1) % windowSlots; - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Spectrum.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Spectrum.java deleted file mode 100644 index ca01c6e3..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Spectrum.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -/** - * Telecom optical wavelength bands: O, E, S, C, L and U bands. - * - * See ITU-T G-Series Recommendations, Supplement 39 - * See ITU-T G.694.1 for center frequency definition. - */ -public final class Spectrum { - - // Center frequency - public static final Frequency CENTER_FREQUENCY = Frequency.ofTHz(193.1); - - // O band (original): 1260 to 1360 nm - public static final Frequency O_BAND_MIN = Frequency.ofTHz(220.436); - public static final Frequency O_BAND_MAX = Frequency.ofTHz(237.931); - - // E band (extended): 1360 to 1460 nm - public static final Frequency E_BAND_MIN = Frequency.ofTHz(205.337); - public static final Frequency E_BAND_MAX = Frequency.ofTHz(220.436); - - // S band (short wavelength): 1460 to 1530 nm - public static final Frequency S_BAND_MIN = Frequency.ofTHz(195.943); - public static final Frequency S_BAND_MAX = Frequency.ofTHz(205.337); - - // C band (conventional): 1530 to 1565 nm - public static final Frequency C_BAND_MIN = Frequency.ofTHz(191.561); - public static final Frequency C_BAND_MAX = Frequency.ofTHz(195.943); - - // L band (long wavelength): 1565 to 1625 nm - public static final Frequency L_BAND_MIN = Frequency.ofTHz(184.488); - public static final Frequency L_BAND_MAX = Frequency.ofTHz(191.561); - - // U band (ultra-long wavelength): 1625 to 1675 nm - public static final Frequency U_BAND_MIN = Frequency.ofTHz(178.981); - public static final Frequency U_BAND_MAX = Frequency.ofTHz(184.488); - - private Spectrum() { - } -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Timer.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Timer.java deleted file mode 100644 index fe508839..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Timer.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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.onlab.util; - -import org.jboss.netty.util.HashedWheelTimer; - -/** - * Hashed-wheel timer singleton. Care must be taken to shutdown the timer - * only when the VM is ready to exit. - */ -public final class Timer { - - private static volatile HashedWheelTimer timer; - - // Ban public construction - private Timer() { - } - - /** - * Returns the singleton hashed-wheel timer. - * - * @return hashed-wheel timer - */ - public static HashedWheelTimer getTimer() { - if (Timer.timer == null) { - initTimer(); - } - return Timer.timer; - } - - private static synchronized void initTimer() { - if (Timer.timer == null) { - HashedWheelTimer hwTimer = new HashedWheelTimer(); - hwTimer.start(); - Timer.timer = hwTimer; - } - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Tools.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Tools.java deleted file mode 100644 index ffefbfd4..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/Tools.java +++ /dev/null @@ -1,577 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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.onlab.util; - -import static java.nio.file.Files.delete; -import static java.nio.file.Files.walkFileTree; -import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory; -import static org.slf4j.LoggerFactory.getLogger; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.StandardCopyOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Dictionary; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - -import org.slf4j.Logger; - -import com.google.common.base.Strings; -import com.google.common.primitives.UnsignedLongs; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -/** - * Miscellaneous utility methods. - */ -public abstract class Tools { - - private Tools() { - } - - private static final Logger log = getLogger(Tools.class); - - private static Random random = new Random(); - - /** - * Returns a thread factory that produces threads named according to the - * supplied name pattern. - * - * @param pattern name pattern - * @return thread factory - */ - public static ThreadFactory namedThreads(String pattern) { - return new ThreadFactoryBuilder() - .setNameFormat(pattern) - .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e)) - .build(); - } - - /** - * Returns a thread factory that produces threads named according to the - * supplied name pattern and from the specified thread-group. The thread - * group name is expected to be specified in slash-delimited format, e.g. - * {@code onos/intent}. The thread names will be produced by converting - * the thread group name into dash-delimited format and pre-pended to the - * specified pattern. - * - * @param groupName group name in slash-delimited format to indicate hierarchy - * @param pattern name pattern - * @return thread factory - */ - public static ThreadFactory groupedThreads(String groupName, String pattern) { - return new ThreadFactoryBuilder() - .setThreadFactory(groupedThreadFactory(groupName)) - .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern) - .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e)) - .build(); - } - - /** - * Returns a thread factory that produces threads with MIN_PRIORITY. - * - * @param factory backing ThreadFactory - * @return thread factory - */ - public static ThreadFactory minPriority(ThreadFactory factory) { - return new ThreadFactoryBuilder() - .setThreadFactory(factory) - .setPriority(Thread.MIN_PRIORITY) - .build(); - } - - /** - * Returns true if the collection is null or is empty. - * - * @param collection collection to test - * @return true if null or empty; false otherwise - */ - public static boolean isNullOrEmpty(Collection collection) { - return collection == null || collection.isEmpty(); - } - - /** - * Returns the specified item if that item is not null; otherwise throws - * not found exception. - * - * @param item item to check - * @param message not found message - * @param <T> item type - * @return item if not null - * @throws org.onlab.util.ItemNotFoundException if item is null - */ - public static <T> T nullIsNotFound(T item, String message) { - if (item == null) { - throw new ItemNotFoundException(message); - } - return item; - } - - /** - * Returns the specified set if the set is not null and not empty; - * otherwise throws a not found exception. - * - * @param item set to check - * @param message not found message - * @param <T> Set item type - * @return item if not null and not empty - * @throws org.onlab.util.ItemNotFoundException if set is null or empty - */ - public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) { - if (item == null || item.isEmpty()) { - throw new ItemNotFoundException(message); - } - return item; - } - - /** - * Returns the specified item if that item is not null; otherwise throws - * bad argument exception. - * - * @param item item to check - * @param message not found message - * @param <T> item type - * @return item if not null - * @throws IllegalArgumentException if item is null - */ - public static <T> T nullIsIllegal(T item, String message) { - if (item == null) { - throw new IllegalArgumentException(message); - } - return item; - } - - /** - * Converts a string from hex to long. - * - * @param string hex number in string form; sans 0x - * @return long value - */ - public static long fromHex(String string) { - return UnsignedLongs.parseUnsignedLong(string, 16); - } - - /** - * Converts a long value to hex string; 16 wide and sans 0x. - * - * @param value long value - * @return hex string - */ - public static String toHex(long value) { - return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0'); - } - - /** - * Converts a long value to hex string; 16 wide and sans 0x. - * - * @param value long value - * @param width string width; zero padded - * @return hex string - */ - public static String toHex(long value, int width) { - return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0'); - } - - /** - * Returns a copy of the input byte array. - * - * @param original input - * @return copy of original - */ - public static byte[] copyOf(byte[] original) { - return Arrays.copyOf(original, original.length); - } - - /** - * Get property as a string value. - * - * @param properties properties to be looked up - * @param propertyName the name of the property to look up - * @return value when the propertyName is defined or return null - */ - public static String get(Dictionary<?, ?> properties, String propertyName) { - Object v = properties.get(propertyName); - String s = (v instanceof String) ? (String) v : - v != null ? v.toString() : null; - return Strings.isNullOrEmpty(s) ? null : s.trim(); - } - - /** - * Suspends the current thread for a specified number of millis. - * - * @param ms number of millis - */ - public static void delay(int ms) { - try { - Thread.sleep(ms); - } catch (InterruptedException e) { - throw new RuntimeException("Interrupted", e); - } - } - - /** - * Returns a function that retries execution on failure. - * @param base base function - * @param exceptionClass type of exception for which to retry - * @param maxRetries max number of retries before giving up - * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from - * the interval (0, maxDelayBetweenRetries] - * @return function - * @param <U> type of function input - * @param <V> type of function output - */ - public static <U, V> Function<U, V> retryable(Function<U, V> base, - Class<? extends Throwable> exceptionClass, - int maxRetries, - int maxDelayBetweenRetries) { - return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries); - } - - /** - * Returns a Supplier that retries execution on failure. - * @param base base supplier - * @param exceptionClass type of exception for which to retry - * @param maxRetries max number of retries before giving up - * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from - * the interval (0, maxDelayBetweenRetries] - * @return supplier - * @param <V> type of supplied result - */ - public static <V> Supplier<V> retryable(Supplier<V> base, - Class<? extends Throwable> exceptionClass, - int maxRetries, - int maxDelayBetweenRetries) { - return () -> new RetryingFunction<>(v -> base.get(), - exceptionClass, - maxRetries, - maxDelayBetweenRetries).apply(null); - } - - /** - * Suspends the current thread for a random number of millis between 0 and - * the indicated limit. - * - * @param ms max number of millis - */ - public static void randomDelay(int ms) { - try { - Thread.sleep(random.nextInt(ms)); - } catch (InterruptedException e) { - throw new RuntimeException("Interrupted", e); - } - } - - /** - * Suspends the current thread for a specified number of millis and nanos. - * - * @param ms number of millis - * @param nanos number of nanos - */ - public static void delay(int ms, int nanos) { - try { - Thread.sleep(ms, nanos); - } catch (InterruptedException e) { - throw new RuntimeException("Interrupted", e); - } - } - - /** - * Slurps the contents of a file into a list of strings, one per line. - * - * @param path file path - * @return file contents - * @deprecated in Emu release - */ - @Deprecated - public static List<String> slurp(File path) { - try ( - BufferedReader br = new BufferedReader( - new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8)); - ) { - List<String> lines = new ArrayList<>(); - String line; - while ((line = br.readLine()) != null) { - lines.add(line); - } - return lines; - - } catch (IOException e) { - return null; - } - } - - /** - * Purges the specified directory path. Use with great caution since - * no attempt is made to check for symbolic links, which could result in - * deletion of unintended files. - * - * @param path directory to be removed - * @throws java.io.IOException if unable to remove contents - */ - public static void removeDirectory(String path) throws IOException { - DirectoryDeleter visitor = new DirectoryDeleter(); - File dir = new File(path); - if (dir.exists() && dir.isDirectory()) { - walkFileTree(Paths.get(path), visitor); - if (visitor.exception != null) { - throw visitor.exception; - } - } - } - - /** - * Purges the specified directory path. Use with great caution since - * no attempt is made to check for symbolic links, which could result in - * deletion of unintended files. - * - * @param dir directory to be removed - * @throws java.io.IOException if unable to remove contents - */ - public static void removeDirectory(File dir) throws IOException { - DirectoryDeleter visitor = new DirectoryDeleter(); - if (dir.exists() && dir.isDirectory()) { - walkFileTree(Paths.get(dir.getAbsolutePath()), visitor); - if (visitor.exception != null) { - throw visitor.exception; - } - } - } - - // Auxiliary path visitor for recursive directory structure removal. - private static class DirectoryDeleter extends SimpleFileVisitor<Path> { - - private IOException exception; - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) - throws IOException { - if (attributes.isRegularFile()) { - delete(file); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path directory, IOException ioe) - throws IOException { - delete(directory); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException ioe) - throws IOException { - this.exception = ioe; - return FileVisitResult.TERMINATE; - } - } - - /** - * Returns a human friendly time ago string for a specified system time. - * - * @param unixTime system time in millis - * @return human friendly time ago - */ - public static String timeAgo(long unixTime) { - long deltaMillis = System.currentTimeMillis() - unixTime; - long secondsSince = (long) (deltaMillis / 1000.0); - long minsSince = (long) (deltaMillis / (1000.0 * 60)); - long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60)); - long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24)); - if (daysSince > 0) { - return String.format("%dd ago", daysSince); - } else if (hoursSince > 0) { - return String.format("%dh ago", hoursSince); - } else if (minsSince > 0) { - return String.format("%dm ago", minsSince); - } else if (secondsSince > 0) { - return String.format("%ds ago", secondsSince); - } else { - return "just now"; - } - } - - /** - * Copies the specified directory path. Use with great caution since - * no attempt is made to check for symbolic links, which could result in - * copy of unintended files. - * - * @param src directory to be copied - * @param dst destination directory to be removed - * @throws java.io.IOException if unable to remove contents - */ - public static void copyDirectory(String src, String dst) throws IOException { - walkFileTree(Paths.get(src), new DirectoryCopier(src, dst)); - } - - /** - * Copies the specified directory path. Use with great caution since - * no attempt is made to check for symbolic links, which could result in - * copy of unintended files. - * - * @param src directory to be copied - * @param dst destination directory to be removed - * @throws java.io.IOException if unable to remove contents - */ - public static void copyDirectory(File src, File dst) throws IOException { - walkFileTree(Paths.get(src.getAbsolutePath()), - new DirectoryCopier(src.getAbsolutePath(), - dst.getAbsolutePath())); - } - - /** - * Returns the future value when complete or if future - * completes exceptionally returns the defaultValue. - * - * @param future future - * @param defaultValue default value - * @param <T> future value type - * @return future value when complete or if future - * completes exceptionally returns the defaultValue. - */ - public static <T> T futureGetOrElse(Future<T> future, T defaultValue) { - try { - return future.get(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return defaultValue; - } catch (ExecutionException e) { - return defaultValue; - } - } - - /** - * Returns the future value when complete or if future - * completes exceptionally returns the defaultValue. - * - * @param future future - * @param timeout time to wait for successful completion - * @param timeUnit time unit - * @param defaultValue default value - * @param <T> future value type - * @return future value when complete or if future - * completes exceptionally returns the defaultValue. - */ - public static <T> T futureGetOrElse(Future<T> future, - long timeout, - TimeUnit timeUnit, - T defaultValue) { - try { - return future.get(timeout, timeUnit); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return defaultValue; - } catch (ExecutionException | TimeoutException e) { - return defaultValue; - } - } - - /** - * Returns a future that is completed exceptionally. - * - * @param t exception - * @param <T> future value type - * @return future - */ - public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) { - CompletableFuture<T> future = new CompletableFuture<>(); - future.completeExceptionally(t); - return future; - } - - /** - * Returns the contents of {@code ByteBuffer} as byte array. - * <p> - * WARNING: There is a performance cost due to array copy - * when using this method. - * - * @param buffer byte buffer - * @return byte array containing the byte buffer contents - */ - public static byte[] byteBuffertoArray(ByteBuffer buffer) { - int length = buffer.remaining(); - if (buffer.hasArray()) { - int offset = buffer.arrayOffset() + buffer.position(); - return Arrays.copyOfRange(buffer.array(), offset, offset + length); - } - byte[] bytes = new byte[length]; - buffer.duplicate().get(bytes); - return bytes; - } - - /** - * Converts an iterable to a stream. - * - * @param it iterable to convert - * @param <T> type if item - * @return iterable as a stream - */ - public static <T> Stream<T> stream(Iterable<T> it) { - return StreamSupport.stream(it.spliterator(), false); - } - - // Auxiliary path visitor for recursive directory structure copying. - private static class DirectoryCopier extends SimpleFileVisitor<Path> { - private Path src; - private Path dst; - private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING; - - DirectoryCopier(String src, String dst) { - this.src = Paths.get(src); - this.dst = Paths.get(dst); - } - - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - Path targetPath = dst.resolve(src.relativize(dir)); - if (!Files.exists(targetPath)) { - Files.createDirectory(targetPath); - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - Files.copy(file, dst.resolve(src.relativize(file)), copyOption); - return FileVisitResult.CONTINUE; - } - } - -} diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/TriConsumer.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/TriConsumer.java deleted file mode 100644 index d1963c46..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/TriConsumer.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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.onlab.util; - -/** - * A consumer that accepts three arguments. - * - * @param <U> type of first argument - * @param <V> type of second argument - * @param <W> type of third argument - */ -public interface TriConsumer<U, V, W> { - - /** - * Applies the given arguments to the function. - * @param arg1 first argument - * @param arg2 second argument - * @param arg3 third argument - */ - void accept(U arg1, V arg2, W arg3); - -}
\ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/package-info.java b/framework/src/onos/utils/misc/src/main/java/org/onlab/util/package-info.java deleted file mode 100644 index 06cc394f..00000000 --- a/framework/src/onos/utils/misc/src/main/java/org/onlab/util/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ - -/** - * Miscellaneous domain-agnostic utilities. - */ -package org.onlab.util; |