repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
d-michail/jheaps
src/main/java/org/jheaps/array/AbstractArrayHeap.java
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // }
import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.LogarithmicTime;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.array; /** * Abstract implementation of a heap using an array representation. * * @author Dimitrios Michail * * @param <K> * the type of keys maintained by this heap */ abstract class AbstractArrayHeap<K> extends AbstractArrayWeakHeap<K> { private static final long serialVersionUID = 1L; /** * Construct a new heap * * @param comparator * the comparator to use * @param capacity * the initial capacity */ public AbstractArrayHeap(Comparator<? super K> comparator, int capacity) { super(comparator, capacity); } /** * Initialize the array representation */ @Override @SuppressWarnings("unchecked") protected void initCapacity(int capacity) { this.array = (K[]) new Object[capacity + 1]; } /** * {@inheritDoc} */ @Override @ConstantTime public K findMin() {
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // } // Path: src/main/java/org/jheaps/array/AbstractArrayHeap.java import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.LogarithmicTime; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.array; /** * Abstract implementation of a heap using an array representation. * * @author Dimitrios Michail * * @param <K> * the type of keys maintained by this heap */ abstract class AbstractArrayHeap<K> extends AbstractArrayWeakHeap<K> { private static final long serialVersionUID = 1L; /** * Construct a new heap * * @param comparator * the comparator to use * @param capacity * the initial capacity */ public AbstractArrayHeap(Comparator<? super K> comparator, int capacity) { super(comparator, capacity); } /** * Initialize the array representation */ @Override @SuppressWarnings("unchecked") protected void initCapacity(int capacity) { this.array = (K[]) new Object[capacity + 1]; } /** * {@inheritDoc} */ @Override @ConstantTime public K findMin() {
if (Constants.NOT_BENCHMARK && size == 0) {
d-michail/jheaps
src/test/java/org/jheaps/tree/LeftistHeapAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import java.util.Comparator; import org.jheaps.AddressableHeap;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class LeftistHeapAddressableHeapTest extends AbstractAddressableHeapTest { @Override
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/tree/LeftistHeapAddressableHeapTest.java import java.util.Comparator; import org.jheaps.AddressableHeap; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class LeftistHeapAddressableHeapTest extends AbstractAddressableHeapTest { @Override
protected AddressableHeap<Integer, Void> createHeap() {
d-michail/jheaps
src/test/java/org/jheaps/tree/RankPairingHeapAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import java.util.Comparator; import org.jheaps.AddressableHeap;
/* * (C) Copyright 2014-2019, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class RankPairingHeapAddressableHeapTest extends AbstractAddressableHeapTest { @Override
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/tree/RankPairingHeapAddressableHeapTest.java import java.util.Comparator; import org.jheaps.AddressableHeap; /* * (C) Copyright 2014-2019, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class RankPairingHeapAddressableHeapTest extends AbstractAddressableHeapTest { @Override
protected AddressableHeap<Integer, Void> createHeap() {
d-michail/jheaps
src/test/java/org/jheaps/monotone/DoubleRadixAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Random; import org.jheaps.AddressableHeap; import org.junit.Test;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class DoubleRadixAddressableHeapTest { private static final int SIZE = 100000; @Test public void testBug1() {
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/monotone/DoubleRadixAddressableHeapTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Random; import org.jheaps.AddressableHeap; import org.junit.Test; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class DoubleRadixAddressableHeapTest { private static final int SIZE = 100000; @Test public void testBug1() {
AddressableHeap<Double, Void> h = new DoubleRadixAddressableHeap<Void>(0.0, 3.667944409236726);
d-michail/jheaps
src/main/java/org/jheaps/array/BinaryArrayAddressableHeap.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import java.io.Serializable; import java.lang.reflect.Array; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import org.jheaps.AddressableHeap; import org.jheaps.annotations.LinearTime;
return new BinaryArrayAddressableHeap<K, V>(comparator); } BinaryArrayAddressableHeap<K, V> h = new BinaryArrayAddressableHeap<K, V>(comparator, keys.length); for (int i = 0; i < keys.length; i++) { K key = keys[i]; V value = (values == null) ? null : values[i]; AbstractArrayAddressableHeap<K, V>.ArrayHandle ah = h.new ArrayHandle(key, value); ah.index = i + 1; h.array[i + 1] = ah; } h.size = keys.length; for (int i = keys.length / 2; i > 0; i--) { h.fixdownWithComparator(i); } return h; } /** * Get an iterator for all handles currently in the heap. * * This method is especially useful when building a heap using the heapify * method. Unspecified behavior will occur if the heap is modified while * using this iterator. * * @return an iterator which will return all handles of the heap */
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/main/java/org/jheaps/array/BinaryArrayAddressableHeap.java import java.io.Serializable; import java.lang.reflect.Array; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import org.jheaps.AddressableHeap; import org.jheaps.annotations.LinearTime; return new BinaryArrayAddressableHeap<K, V>(comparator); } BinaryArrayAddressableHeap<K, V> h = new BinaryArrayAddressableHeap<K, V>(comparator, keys.length); for (int i = 0; i < keys.length; i++) { K key = keys[i]; V value = (values == null) ? null : values[i]; AbstractArrayAddressableHeap<K, V>.ArrayHandle ah = h.new ArrayHandle(key, value); ah.index = i + 1; h.array[i + 1] = ah; } h.size = keys.length; for (int i = keys.length / 2; i > 0; i--) { h.fixdownWithComparator(i); } return h; } /** * Get an iterator for all handles currently in the heap. * * This method is especially useful when building a heap using the heapify * method. Unspecified behavior will occur if the heap is modified while * using this iterator. * * @return an iterator which will return all handles of the heap */
public Iterator<AddressableHeap.Handle<K, V>> handlesIterator() {
d-michail/jheaps
src/test/java/org/jheaps/tree/AbstractDoubleEndedHeapTest.java
// Path: src/main/java/org/jheaps/DoubleEndedHeap.java // public interface DoubleEndedHeap<K> extends Heap<K> { // // /** // * Find an element with the maximum key. // * // * @return an element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMax(); // // /** // * Delete and return an element with the maximum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMax(); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Random; import org.jheaps.DoubleEndedHeap; import org.junit.Test;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractDoubleEndedHeapTest extends AbstractComparatorLongHeapTest { @Override
// Path: src/main/java/org/jheaps/DoubleEndedHeap.java // public interface DoubleEndedHeap<K> extends Heap<K> { // // /** // * Find an element with the maximum key. // * // * @return an element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMax(); // // /** // * Delete and return an element with the maximum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMax(); // // } // Path: src/test/java/org/jheaps/tree/AbstractDoubleEndedHeapTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Random; import org.jheaps.DoubleEndedHeap; import org.junit.Test; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractDoubleEndedHeapTest extends AbstractComparatorLongHeapTest { @Override
protected abstract DoubleEndedHeap<Long> createHeap();
d-michail/jheaps
src/test/java/org/jheaps/tree/AbstractLongHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // }
import org.jheaps.Heap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.NoSuchElementException; import java.util.Random;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractLongHeapTest { protected static final int SIZE = 100000;
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/tree/AbstractLongHeapTest.java import org.jheaps.Heap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.NoSuchElementException; import java.util.Random; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractLongHeapTest { protected static final int SIZE = 100000;
protected abstract Heap<Long> createHeap();
d-michail/jheaps
src/main/java/org/jheaps/tree/BinaryTreeSoftAddressableHeap.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // }
import java.io.Serializable; import java.util.ArrayDeque; import java.util.Comparator; import java.util.Deque; import java.util.NoSuchElementException; import org.jheaps.AddressableHeap; import org.jheaps.MergeableAddressableHeap; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.VisibleForTesting;
* performed using cHead. */ long cSize; // corrupted key K cKey; TreeNode() { this(null); } TreeNode(SoftHandle<K, V> n) { this.rank = 0; this.parent = null; this.left = null; this.right = null; this.cHead = n; this.cTail = n; if (n != null) { this.cSize = 1; this.cKey = n.key; n.tree = this; } else { this.cSize = 0; this.cKey = null; } } } // -------------------------------------------------------------------- @VisibleForTesting
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // } // Path: src/main/java/org/jheaps/tree/BinaryTreeSoftAddressableHeap.java import java.io.Serializable; import java.util.ArrayDeque; import java.util.Comparator; import java.util.Deque; import java.util.NoSuchElementException; import org.jheaps.AddressableHeap; import org.jheaps.MergeableAddressableHeap; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.VisibleForTesting; * performed using cHead. */ long cSize; // corrupted key K cKey; TreeNode() { this(null); } TreeNode(SoftHandle<K, V> n) { this.rank = 0; this.parent = null; this.left = null; this.right = null; this.cHead = n; this.cTail = n; if (n != null) { this.cSize = 1; this.cKey = n.key; n.tree = this; } else { this.cSize = 0; this.cKey = null; } } } // -------------------------------------------------------------------- @VisibleForTesting
static class SoftHandle<K, V> implements AddressableHeap.Handle<K, V>, Serializable {
d-michail/jheaps
src/test/java/org/jheaps/monotone/LongRadixAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import org.jheaps.AddressableHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.NoSuchElementException; import java.util.Random;
/* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class LongRadixAddressableHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/monotone/LongRadixAddressableHeapTest.java import org.jheaps.AddressableHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.NoSuchElementException; import java.util.Random; /* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class LongRadixAddressableHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
AddressableHeap<Long, Void> h = new LongRadixAddressableHeap<Void>(0L, 100L);
d-michail/jheaps
src/test/java/org/jheaps/monotone/LongRadixHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/LongRadixHeap.java // public class LongRadixHeap extends AbstractRadixHeap<Long> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public LongRadixHeap(long minKey, long maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Long>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Long>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Long o1, Long o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Long a, Long b) { // /* // * Value equal // */ // if (a.longValue() == b.longValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // double axorb = a ^ b; // return Math.getExponent(axorb); // } // // }
import org.jheaps.Heap; import org.jheaps.monotone.LongRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random;
/* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class LongRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/LongRadixHeap.java // public class LongRadixHeap extends AbstractRadixHeap<Long> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public LongRadixHeap(long minKey, long maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Long>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Long>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Long o1, Long o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Long a, Long b) { // /* // * Value equal // */ // if (a.longValue() == b.longValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // double axorb = a ^ b; // return Math.getExponent(axorb); // } // // } // Path: src/test/java/org/jheaps/monotone/LongRadixHeapTest.java import org.jheaps.Heap; import org.jheaps.monotone.LongRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random; /* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class LongRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
Heap<Long> h = new LongRadixHeap(0L, 100L);
d-michail/jheaps
src/test/java/org/jheaps/monotone/LongRadixHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/LongRadixHeap.java // public class LongRadixHeap extends AbstractRadixHeap<Long> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public LongRadixHeap(long minKey, long maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Long>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Long>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Long o1, Long o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Long a, Long b) { // /* // * Value equal // */ // if (a.longValue() == b.longValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // double axorb = a ^ b; // return Math.getExponent(axorb); // } // // }
import org.jheaps.Heap; import org.jheaps.monotone.LongRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random;
/* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class LongRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/LongRadixHeap.java // public class LongRadixHeap extends AbstractRadixHeap<Long> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public LongRadixHeap(long minKey, long maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Long>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Long>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Long o1, Long o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Long a, Long b) { // /* // * Value equal // */ // if (a.longValue() == b.longValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // double axorb = a ^ b; // return Math.getExponent(axorb); // } // // } // Path: src/test/java/org/jheaps/monotone/LongRadixHeapTest.java import org.jheaps.Heap; import org.jheaps.monotone.LongRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random; /* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class LongRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
Heap<Long> h = new LongRadixHeap(0L, 100L);
d-michail/jheaps
src/test/java/org/jheaps/tree/AbstractMergeableAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableAddressableHeap; import org.junit.BeforeClass; import org.junit.Test;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractMergeableAddressableHeapTest { protected static final int SIZE = 100000; private static Comparator<Integer> comparator; private static class TestComparator implements Comparator<Integer>, Serializable { private static final long serialVersionUID = 1L; @Override public int compare(Integer o1, Integer o2) { if (o1 < o2) { return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); }
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // } // Path: src/test/java/org/jheaps/tree/AbstractMergeableAddressableHeapTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableAddressableHeap; import org.junit.BeforeClass; import org.junit.Test; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractMergeableAddressableHeapTest { protected static final int SIZE = 100000; private static Comparator<Integer> comparator; private static class TestComparator implements Comparator<Integer>, Serializable { private static final long serialVersionUID = 1L; @Override public int compare(Integer o1, Integer o2) { if (o1 < o2) { return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); }
protected abstract MergeableAddressableHeap<Integer, String> createHeap(Comparator<Integer> comparator);
d-michail/jheaps
src/test/java/org/jheaps/tree/AbstractMergeableAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableAddressableHeap; import org.junit.BeforeClass; import org.junit.Test;
return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); } protected abstract MergeableAddressableHeap<Integer, String> createHeap(Comparator<Integer> comparator); protected abstract MergeableAddressableHeap<Integer, String> createHeap(); @Test public void testMeld1() { MergeableAddressableHeap<Integer, String> a = createHeap(); a.insert(10); a.insert(11); a.insert(12); a.insert(13); MergeableAddressableHeap<Integer, String> b = createHeap(); b.insert(14); b.insert(15); b.insert(16);
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // } // Path: src/test/java/org/jheaps/tree/AbstractMergeableAddressableHeapTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableAddressableHeap; import org.junit.BeforeClass; import org.junit.Test; return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); } protected abstract MergeableAddressableHeap<Integer, String> createHeap(Comparator<Integer> comparator); protected abstract MergeableAddressableHeap<Integer, String> createHeap(); @Test public void testMeld1() { MergeableAddressableHeap<Integer, String> a = createHeap(); a.insert(10); a.insert(11); a.insert(12); a.insert(13); MergeableAddressableHeap<Integer, String> b = createHeap(); b.insert(14); b.insert(15); b.insert(16);
Handle<Integer, String> b4 = b.insert(17);
d-michail/jheaps
src/main/java/org/jheaps/array/MinMaxBinaryArrayDoubleEndedHeap.java
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // } // // Path: src/main/java/org/jheaps/DoubleEndedHeap.java // public interface DoubleEndedHeap<K> extends Heap<K> { // // /** // * Find an element with the maximum key. // * // * @return an element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMax(); // // /** // * Delete and return an element with the maximum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMax(); // // }
import java.io.Serializable; import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.DoubleEndedHeap; import org.jheaps.annotations.LinearTime; import org.jheaps.annotations.VisibleForTesting;
if (size >= 3) { fixdownMax(3); } } else { result = array[2]; array[2] = array[size]; array[size] = null; size--; fixdownMax(2); } } else { if (comparator.compare(array[3], array[2]) > 0) { result = array[3]; array[3] = array[size]; array[size] = null; size--; if (size >= 3) { fixdownMaxWithComparator(3); } } else { result = array[2]; array[2] = array[size]; array[size] = null; size--; fixdownMaxWithComparator(2); } } break; }
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // } // // Path: src/main/java/org/jheaps/DoubleEndedHeap.java // public interface DoubleEndedHeap<K> extends Heap<K> { // // /** // * Find an element with the maximum key. // * // * @return an element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMax(); // // /** // * Delete and return an element with the maximum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the maximum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMax(); // // } // Path: src/main/java/org/jheaps/array/MinMaxBinaryArrayDoubleEndedHeap.java import java.io.Serializable; import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.DoubleEndedHeap; import org.jheaps.annotations.LinearTime; import org.jheaps.annotations.VisibleForTesting; if (size >= 3) { fixdownMax(3); } } else { result = array[2]; array[2] = array[size]; array[size] = null; size--; fixdownMax(2); } } else { if (comparator.compare(array[3], array[2]) > 0) { result = array[3]; array[3] = array[size]; array[size] = null; size--; if (size >= 3) { fixdownMaxWithComparator(3); } } else { result = array[2]; array[2] = array[size]; array[size] = null; size--; fixdownMaxWithComparator(2); } } break; }
if (Constants.NOT_BENCHMARK) {
d-michail/jheaps
src/test/java/org/jheaps/tree/D4DaryTreeAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import java.util.Comparator; import org.jheaps.AddressableHeap;
/* * (C) Copyright 2014-2019, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class D4DaryTreeAddressableHeapTest extends AbstractAddressableHeapTest { @Override
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/tree/D4DaryTreeAddressableHeapTest.java import java.util.Comparator; import org.jheaps.AddressableHeap; /* * (C) Copyright 2014-2019, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class D4DaryTreeAddressableHeapTest extends AbstractAddressableHeapTest { @Override
protected AddressableHeap<Integer, Void> createHeap() {
d-michail/jheaps
src/test/java/org/jheaps/tree/ReflectedFibonacciHeapAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import java.util.Comparator; import org.jheaps.AddressableHeap;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class ReflectedFibonacciHeapAddressableHeapTest extends AbstractAddressableHeapTest { @Override
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/tree/ReflectedFibonacciHeapAddressableHeapTest.java import java.util.Comparator; import org.jheaps.AddressableHeap; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class ReflectedFibonacciHeapAddressableHeapTest extends AbstractAddressableHeapTest { @Override
protected AddressableHeap<Integer, Void> createHeap() {
d-michail/jheaps
src/main/java/org/jheaps/array/BinaryArrayIntegerValueHeap.java
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // } // // Path: src/main/java/org/jheaps/ValueHeap.java // public interface ValueHeap<K, V> extends Heap<K> { // // /** // * Insert an element into the heap. // * // * @param key // * the key to insert // * @param value // * the value to insert // */ // void insert(K key, V value); // // /** // * Find the value of an element with the minimum key. // * // * @return the value of an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // V findMinValue(); // // }
import java.io.Serializable; import java.lang.reflect.Array; import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.ValueHeap; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.LogarithmicTime;
*/ @Override @ConstantTime public long size() { return size; } /** * {@inheritDoc} */ @Override @ConstantTime public void clear() { size = 0; } /** * {@inheritDoc} */ @Override public Comparator<? super Integer> comparator() { return null; } /** * {@inheritDoc} */ @Override @ConstantTime public Integer findMin() {
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // } // // Path: src/main/java/org/jheaps/ValueHeap.java // public interface ValueHeap<K, V> extends Heap<K> { // // /** // * Insert an element into the heap. // * // * @param key // * the key to insert // * @param value // * the value to insert // */ // void insert(K key, V value); // // /** // * Find the value of an element with the minimum key. // * // * @return the value of an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // V findMinValue(); // // } // Path: src/main/java/org/jheaps/array/BinaryArrayIntegerValueHeap.java import java.io.Serializable; import java.lang.reflect.Array; import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.ValueHeap; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.LogarithmicTime; */ @Override @ConstantTime public long size() { return size; } /** * {@inheritDoc} */ @Override @ConstantTime public void clear() { size = 0; } /** * {@inheritDoc} */ @Override public Comparator<? super Integer> comparator() { return null; } /** * {@inheritDoc} */ @Override @ConstantTime public Integer findMin() {
if (Constants.NOT_BENCHMARK && size == 0) {
d-michail/jheaps
src/test/java/org/jheaps/monotone/BigIntegerRadixHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/BigIntegerRadixHeap.java // public class BigIntegerRadixHeap extends AbstractRadixHeap<BigInteger> { // // private final static long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public BigIntegerRadixHeap(BigInteger minKey, BigInteger maxKey) { // super(); // if (minKey == null) { // throw new IllegalArgumentException("Minimum key cannot be null"); // } // if (minKey.compareTo(BigInteger.ZERO) < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey == null) { // throw new IllegalArgumentException("Maximum key cannot be null"); // } // if (maxKey.compareTo(minKey) < 0) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // BigInteger diff = maxKey.subtract(minKey); // int numBuckets = 2 + 1 + diff.bitLength(); // // // construct representation // this.buckets = (List<BigInteger>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<BigInteger>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(BigInteger o1, BigInteger o2) { // return o1.compareTo(o2); // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(BigInteger a, BigInteger b) { // if (a.equals(b)) { // return -1; // } // /* // * return floor(log_2(a xor b)). // */ // return a.xor(b).bitLength() - 1; // } // // }
import org.jheaps.Heap; import org.jheaps.monotone.BigIntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Random;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class BigIntegerRadixHeapTest { private static final BigInteger SIZE = BigInteger.valueOf(100000); @Test public void testBug2() {
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/BigIntegerRadixHeap.java // public class BigIntegerRadixHeap extends AbstractRadixHeap<BigInteger> { // // private final static long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public BigIntegerRadixHeap(BigInteger minKey, BigInteger maxKey) { // super(); // if (minKey == null) { // throw new IllegalArgumentException("Minimum key cannot be null"); // } // if (minKey.compareTo(BigInteger.ZERO) < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey == null) { // throw new IllegalArgumentException("Maximum key cannot be null"); // } // if (maxKey.compareTo(minKey) < 0) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // BigInteger diff = maxKey.subtract(minKey); // int numBuckets = 2 + 1 + diff.bitLength(); // // // construct representation // this.buckets = (List<BigInteger>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<BigInteger>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(BigInteger o1, BigInteger o2) { // return o1.compareTo(o2); // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(BigInteger a, BigInteger b) { // if (a.equals(b)) { // return -1; // } // /* // * return floor(log_2(a xor b)). // */ // return a.xor(b).bitLength() - 1; // } // // } // Path: src/test/java/org/jheaps/monotone/BigIntegerRadixHeapTest.java import org.jheaps.Heap; import org.jheaps.monotone.BigIntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Random; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class BigIntegerRadixHeapTest { private static final BigInteger SIZE = BigInteger.valueOf(100000); @Test public void testBug2() {
Heap<BigInteger> h = new BigIntegerRadixHeap(BigInteger.ZERO, BigInteger.valueOf(100));
d-michail/jheaps
src/test/java/org/jheaps/monotone/BigIntegerRadixHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/BigIntegerRadixHeap.java // public class BigIntegerRadixHeap extends AbstractRadixHeap<BigInteger> { // // private final static long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public BigIntegerRadixHeap(BigInteger minKey, BigInteger maxKey) { // super(); // if (minKey == null) { // throw new IllegalArgumentException("Minimum key cannot be null"); // } // if (minKey.compareTo(BigInteger.ZERO) < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey == null) { // throw new IllegalArgumentException("Maximum key cannot be null"); // } // if (maxKey.compareTo(minKey) < 0) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // BigInteger diff = maxKey.subtract(minKey); // int numBuckets = 2 + 1 + diff.bitLength(); // // // construct representation // this.buckets = (List<BigInteger>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<BigInteger>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(BigInteger o1, BigInteger o2) { // return o1.compareTo(o2); // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(BigInteger a, BigInteger b) { // if (a.equals(b)) { // return -1; // } // /* // * return floor(log_2(a xor b)). // */ // return a.xor(b).bitLength() - 1; // } // // }
import org.jheaps.Heap; import org.jheaps.monotone.BigIntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Random;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class BigIntegerRadixHeapTest { private static final BigInteger SIZE = BigInteger.valueOf(100000); @Test public void testBug2() {
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/BigIntegerRadixHeap.java // public class BigIntegerRadixHeap extends AbstractRadixHeap<BigInteger> { // // private final static long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public BigIntegerRadixHeap(BigInteger minKey, BigInteger maxKey) { // super(); // if (minKey == null) { // throw new IllegalArgumentException("Minimum key cannot be null"); // } // if (minKey.compareTo(BigInteger.ZERO) < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey == null) { // throw new IllegalArgumentException("Maximum key cannot be null"); // } // if (maxKey.compareTo(minKey) < 0) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // BigInteger diff = maxKey.subtract(minKey); // int numBuckets = 2 + 1 + diff.bitLength(); // // // construct representation // this.buckets = (List<BigInteger>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<BigInteger>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(BigInteger o1, BigInteger o2) { // return o1.compareTo(o2); // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(BigInteger a, BigInteger b) { // if (a.equals(b)) { // return -1; // } // /* // * return floor(log_2(a xor b)). // */ // return a.xor(b).bitLength() - 1; // } // // } // Path: src/test/java/org/jheaps/monotone/BigIntegerRadixHeapTest.java import org.jheaps.Heap; import org.jheaps.monotone.BigIntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Random; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class BigIntegerRadixHeapTest { private static final BigInteger SIZE = BigInteger.valueOf(100000); @Test public void testBug2() {
Heap<BigInteger> h = new BigIntegerRadixHeap(BigInteger.ZERO, BigInteger.valueOf(100));
d-michail/jheaps
src/test/java/org/jheaps/tree/AbstractIntegerHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // }
import org.jheaps.Heap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.NoSuchElementException; import java.util.Random;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractIntegerHeapTest { protected static final int SIZE = 100000;
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/tree/AbstractIntegerHeapTest.java import org.jheaps.Heap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.NoSuchElementException; import java.util.Random; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractIntegerHeapTest { protected static final int SIZE = 100000;
protected abstract Heap<Integer> createHeap();
d-michail/jheaps
src/test/java/org/jheaps/tree/SkewHeapMergeableAddressableHeapTest.java
// Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // }
import java.util.Comparator; import org.jheaps.MergeableAddressableHeap;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class SkewHeapMergeableAddressableHeapTest extends AbstractMergeableAddressableHeapTest { @Override
// Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // } // Path: src/test/java/org/jheaps/tree/SkewHeapMergeableAddressableHeapTest.java import java.util.Comparator; import org.jheaps.MergeableAddressableHeap; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class SkewHeapMergeableAddressableHeapTest extends AbstractMergeableAddressableHeapTest { @Override
protected MergeableAddressableHeap<Integer, String> createHeap() {
d-michail/jheaps
src/test/java/org/jheaps/monotone/DoubleRadixHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Random; import org.jheaps.Heap; import org.junit.Test;
/* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class DoubleRadixHeapTest { private static final int SIZE = 100000; /* * Affects version 0.7 of the library. */ @Test public void testBug1() {
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/monotone/DoubleRadixHeapTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Random; import org.jheaps.Heap; import org.junit.Test; /* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class DoubleRadixHeapTest { private static final int SIZE = 100000; /* * Affects version 0.7 of the library. */ @Test public void testBug1() {
Heap<Double> h = new DoubleRadixHeap(0.0, 3.667944409236726);
d-michail/jheaps
src/test/java/org/jheaps/monotone/BigIntegerRadixAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // }
import org.jheaps.AddressableHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Random;
/* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class BigIntegerRadixAddressableHeapTest { private static final BigInteger SIZE = BigInteger.valueOf(100000); @Test public void testBug2() {
// Path: src/main/java/org/jheaps/AddressableHeap.java // public interface AddressableHeap<K, V> { // // /** // * A heap element handle. Allows someone to address an element already in a // * heap and perform additional operations. // * // * @param <K> // * the type of keys maintained by this heap // * @param <V> // * the type of values maintained by this heap // */ // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // /** // * Returns the comparator used to order the keys in this AddressableHeap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this addressable heap uses the natural ordering // * of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a new element into the heap. // * // * @param key // * the element's key // * @param value // * the element's value // * // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key, V value); // // /** // * Insert a new element into the heap with a null value. // * // * @param key // * the element's key // * @return a handle for the newly added element // */ // AddressableHeap.Handle<K, V> insert(K key); // // /** // * Find an element with the minimum key. // * // * @return a handle to an element with minimum key // */ // AddressableHeap.Handle<K, V> findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. After the element is // * deleted the handle is invalidated and only method {@link Handle#getKey()} // * and {@link Handle#getValue()} can be used. // * // * @return a handle to the deleted element with minimum key // */ // AddressableHeap.Handle<K, V> deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in the heap. // * // * @return the number of elements in the heap // */ // long size(); // // /** // * Clear all the elements of the heap. After calling this method all handles // * should be considered invalidated and the behavior of methods // * {@link Handle#decreaseKey(Object)} and {@link Handle#delete()} is // * undefined. // */ // void clear(); // // } // Path: src/test/java/org/jheaps/monotone/BigIntegerRadixAddressableHeapTest.java import org.jheaps.AddressableHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.util.Arrays; import java.util.Random; /* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class BigIntegerRadixAddressableHeapTest { private static final BigInteger SIZE = BigInteger.valueOf(100000); @Test public void testBug2() {
AddressableHeap<BigInteger, Void> h = new BigIntegerRadixAddressableHeap<Void>(BigInteger.ZERO, BigInteger.valueOf(100));
d-michail/jheaps
src/main/java/org/jheaps/array/BinaryArrayWeakHeap.java
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // }
import java.io.Serializable; import java.util.BitSet; import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.LinearTime; import org.jheaps.annotations.LogarithmicTime;
* @throws IllegalArgumentException * in case the array is null */ @LinearTime public static <K> BinaryArrayWeakHeap<K> heapify(K[] array, Comparator<? super K> comparator) { if (array == null) { throw new IllegalArgumentException("Array cannot be null"); } if (array.length == 0) { return new BinaryArrayWeakHeap<K>(comparator); } BinaryArrayWeakHeap<K> h = new BinaryArrayWeakHeap<K>(comparator, array.length); System.arraycopy(array, 0, h.array, 0, array.length); h.size = array.length; for (int j = h.size - 1; j > 0; j--) { h.joinWithComparator(h.dancestor(j), j); } return h; } /** * {@inheritDoc} */ @Override @ConstantTime public K findMin() {
// Path: src/main/java/org/jheaps/Constants.java // public class Constants { // // /** // * Library name // */ // public static final String NAME = "JHeaps"; // // /** // * Global debug flag which affects compiled code // */ // public static final boolean DEBUG = false; // // /** // * Global level one debug flag which affects compiled code. // */ // public static final boolean DEBUG_LEVEL1 = false; // // /** // * Global level two debug flag which affects compiled code // */ // public static final boolean DEBUG_LEVEL2 = false; // // /** // * Global benchmarking flag. This flag enables sanity checks when the code // * is not for benchmarking performance. When benchmarking we assume that the // * user provided the correct input. // */ // public static final boolean NOT_BENCHMARK = true; // // private Constants() { // } // // } // Path: src/main/java/org/jheaps/array/BinaryArrayWeakHeap.java import java.io.Serializable; import java.util.BitSet; import java.util.Comparator; import java.util.NoSuchElementException; import org.jheaps.Constants; import org.jheaps.annotations.ConstantTime; import org.jheaps.annotations.LinearTime; import org.jheaps.annotations.LogarithmicTime; * @throws IllegalArgumentException * in case the array is null */ @LinearTime public static <K> BinaryArrayWeakHeap<K> heapify(K[] array, Comparator<? super K> comparator) { if (array == null) { throw new IllegalArgumentException("Array cannot be null"); } if (array.length == 0) { return new BinaryArrayWeakHeap<K>(comparator); } BinaryArrayWeakHeap<K> h = new BinaryArrayWeakHeap<K>(comparator, array.length); System.arraycopy(array, 0, h.array, 0, array.length); h.size = array.length; for (int j = h.size - 1; j > 0; j--) { h.joinWithComparator(h.dancestor(j), j); } return h; } /** * {@inheritDoc} */ @Override @ConstantTime public K findMin() {
if (Constants.NOT_BENCHMARK && size == 0) {
d-michail/jheaps
src/test/java/org/jheaps/tree/AbstractMergeableDoubleEndedAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableDoubleEndedAddressableHeap.java // public interface MergeableDoubleEndedAddressableHeap<K, V> extends DoubleEndedAddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableDoubleEndedAddressableHeap<K, V> other); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableDoubleEndedAddressableHeap; import org.junit.BeforeClass; import org.junit.Test;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractMergeableDoubleEndedAddressableHeapTest { protected static final int SIZE = 100000; private static Comparator<Integer> comparator; private static class TestComparator implements Comparator<Integer>, Serializable { private static final long serialVersionUID = 1L; @Override public int compare(Integer o1, Integer o2) { if (o1 < o2) { return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); }
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableDoubleEndedAddressableHeap.java // public interface MergeableDoubleEndedAddressableHeap<K, V> extends DoubleEndedAddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableDoubleEndedAddressableHeap<K, V> other); // // } // Path: src/test/java/org/jheaps/tree/AbstractMergeableDoubleEndedAddressableHeapTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableDoubleEndedAddressableHeap; import org.junit.BeforeClass; import org.junit.Test; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public abstract class AbstractMergeableDoubleEndedAddressableHeapTest { protected static final int SIZE = 100000; private static Comparator<Integer> comparator; private static class TestComparator implements Comparator<Integer>, Serializable { private static final long serialVersionUID = 1L; @Override public int compare(Integer o1, Integer o2) { if (o1 < o2) { return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); }
protected abstract MergeableDoubleEndedAddressableHeap<Integer, String> createHeap();
d-michail/jheaps
src/test/java/org/jheaps/tree/AbstractMergeableDoubleEndedAddressableHeapTest.java
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableDoubleEndedAddressableHeap.java // public interface MergeableDoubleEndedAddressableHeap<K, V> extends DoubleEndedAddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableDoubleEndedAddressableHeap<K, V> other); // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableDoubleEndedAddressableHeap; import org.junit.BeforeClass; import org.junit.Test;
return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); } protected abstract MergeableDoubleEndedAddressableHeap<Integer, String> createHeap(); protected abstract MergeableDoubleEndedAddressableHeap<Integer, String> createHeap(Comparator<Integer> comparator); @Test public void testMeld1() { MergeableDoubleEndedAddressableHeap<Integer, String> a = createHeap(); a.insert(10); a.insert(11); a.insert(12); a.insert(13); MergeableDoubleEndedAddressableHeap<Integer, String> b = createHeap(); b.insert(14); b.insert(15); b.insert(16);
// Path: src/main/java/org/jheaps/AddressableHeap.java // interface Handle<K, V> { // // /** // * Return the key of the element. // * // * @return the key of the element // */ // K getKey(); // // /** // * Return the value of the element. // * // * @return the value of the element // */ // V getValue(); // // /** // * Set the value of the element. // * // * @param value // * the new value // */ // void setValue(V value); // // /** // * Decrease the key of the element. // * // * @param newKey // * the new key // * @throws IllegalArgumentException // * if the new key is larger than the old key according to // * the comparator used when constructing the heap or the // * natural ordering of the elements if no comparator was // * used // */ // void decreaseKey(K newKey); // // /** // * Delete the element from the heap that it belongs. // * // * @throws IllegalArgumentException // * in case this function is called twice on the same element // * or the element has already been deleted using // * {@link AddressableHeap#deleteMin()}. // */ // void delete(); // // } // // Path: src/main/java/org/jheaps/MergeableDoubleEndedAddressableHeap.java // public interface MergeableDoubleEndedAddressableHeap<K, V> extends DoubleEndedAddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableDoubleEndedAddressableHeap<K, V> other); // // } // Path: src/test/java/org/jheaps/tree/AbstractMergeableDoubleEndedAddressableHeapTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.Serializable; import java.util.Comparator; import org.jheaps.AddressableHeap.Handle; import org.jheaps.MergeableDoubleEndedAddressableHeap; import org.junit.BeforeClass; import org.junit.Test; return 1; } else if (o1 > o2) { return -1; } else { return 0; } } } @BeforeClass public static void setUpClass() { comparator = new TestComparator(); } protected abstract MergeableDoubleEndedAddressableHeap<Integer, String> createHeap(); protected abstract MergeableDoubleEndedAddressableHeap<Integer, String> createHeap(Comparator<Integer> comparator); @Test public void testMeld1() { MergeableDoubleEndedAddressableHeap<Integer, String> a = createHeap(); a.insert(10); a.insert(11); a.insert(12); a.insert(13); MergeableDoubleEndedAddressableHeap<Integer, String> b = createHeap(); b.insert(14); b.insert(15); b.insert(16);
Handle<Integer, String> b4 = b.insert(17);
d-michail/jheaps
src/test/java/org/jheaps/monotone/IntegerRadixHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/IntegerRadixHeap.java // public class IntegerRadixHeap extends AbstractRadixHeap<Integer> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public IntegerRadixHeap(int minKey, int maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Integer>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Integer>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Integer o1, Integer o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Integer a, Integer b) { // /* // * Value equal // */ // if (a.intValue() == b.intValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // float axorb = a ^ b; // return Math.getExponent(axorb); // } // // }
import org.jheaps.Heap; import org.jheaps.monotone.IntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random;
/* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class IntegerRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/IntegerRadixHeap.java // public class IntegerRadixHeap extends AbstractRadixHeap<Integer> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public IntegerRadixHeap(int minKey, int maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Integer>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Integer>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Integer o1, Integer o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Integer a, Integer b) { // /* // * Value equal // */ // if (a.intValue() == b.intValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // float axorb = a ^ b; // return Math.getExponent(axorb); // } // // } // Path: src/test/java/org/jheaps/monotone/IntegerRadixHeapTest.java import org.jheaps.Heap; import org.jheaps.monotone.IntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random; /* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class IntegerRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
Heap<Integer> h = new IntegerRadixHeap(0, 100);
d-michail/jheaps
src/test/java/org/jheaps/monotone/IntegerRadixHeapTest.java
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/IntegerRadixHeap.java // public class IntegerRadixHeap extends AbstractRadixHeap<Integer> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public IntegerRadixHeap(int minKey, int maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Integer>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Integer>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Integer o1, Integer o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Integer a, Integer b) { // /* // * Value equal // */ // if (a.intValue() == b.intValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // float axorb = a ^ b; // return Math.getExponent(axorb); // } // // }
import org.jheaps.Heap; import org.jheaps.monotone.IntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random;
/* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class IntegerRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
// Path: src/main/java/org/jheaps/Heap.java // public interface Heap<K> { // // /** // * Returns the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the {@linkplain Comparable natural // * ordering} of its keys. // * // * @return the comparator used to order the keys in this heap, or // * {@code null} if this heap uses the natural ordering of its keys // */ // Comparator<? super K> comparator(); // // /** // * Insert a key into the heap. // * // * @param key // * the key to insert // */ // void insert(K key); // // /** // * Find an element with the minimum key. // * // * @return an element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K findMin(); // // /** // * Delete and return an element with the minimum key. If multiple such // * elements exists, only one of them will be deleted. // * // * @return the deleted element with the minimum key // * @throws NoSuchElementException // * if the heap is empty // */ // K deleteMin(); // // /** // * Returns {@code true} if this heap is empty. // * // * @return {@code true} if this heap is empty, {@code false} otherwise // */ // boolean isEmpty(); // // /** // * Returns the number of elements in this heap. // * // * @return the number of elements in this heap // */ // long size(); // // /** // * Clear all the elements of this heap. // */ // void clear(); // // } // // Path: src/main/java/org/jheaps/monotone/IntegerRadixHeap.java // public class IntegerRadixHeap extends AbstractRadixHeap<Integer> { // // private static final long serialVersionUID = 1; // // /** // * Constructs a new heap which can store values between a minimum and a // * maximum key value (inclusive). // * // * It is important to use the smallest key range as the heap uses O(logC) // * where C=maxKey-minKey+1 buckets to store elements. Moreover, the // * operation {@code deleteMin} requires amortized O(logC) time. // * // * @param minKey // * the non-negative minimum key that this heap supports // * (inclusive) // * @param maxKey // * the maximum key that this heap supports (inclusive) // * @throws IllegalArgumentException // * if the minimum key is negative // * @throws IllegalArgumentException // * if the maximum key is less than the minimum key // */ // @SuppressWarnings("unchecked") // public IntegerRadixHeap(int minKey, int maxKey) { // super(); // if (minKey < 0) { // throw new IllegalArgumentException("Minimum key must be non-negative"); // } // this.minKey = minKey; // this.lastDeletedKey = minKey; // if (maxKey < minKey) { // throw new IllegalArgumentException("Maximum key cannot be less than the minimum"); // } // this.maxKey = maxKey; // // // compute number of buckets // int numBuckets; // if (maxKey == minKey) { // numBuckets = 2; // } else { // numBuckets = 2 + 1 + (int) Math.floor(Math.log((double)maxKey - minKey) / Math.log(2)); // } // // // construct representation // this.buckets = (List<Integer>[]) Array.newInstance(List.class, numBuckets); // for (int i = 0; i < this.buckets.length; i++) { // buckets[i] = new ArrayList<Integer>(); // } // this.size = 0; // this.currentMin = null; // } // // /** // * {@inheritDoc} // */ // @Override // protected int compare(Integer o1, Integer o2) { // if (o1 < o2) { // return -1; // } else if (o1 > o2) { // return 1; // } else { // return 0; // } // } // // /** // * {@inheritDoc} // */ // @Override // protected int msd(Integer a, Integer b) { // /* // * Value equal // */ // if (a.intValue() == b.intValue()) { // return -1; // } // /* // * This is a fast way to compute floor(log_2(a xor b)). // */ // float axorb = a ^ b; // return Math.getExponent(axorb); // } // // } // Path: src/test/java/org/jheaps/monotone/IntegerRadixHeapTest.java import org.jheaps.Heap; import org.jheaps.monotone.IntegerRadixHeap; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Random; /* * (C) Copyright 2014-2018, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.monotone; public class IntegerRadixHeapTest { private static final int SIZE = 100000; @Test public void testBug2() {
Heap<Integer> h = new IntegerRadixHeap(0, 100);
d-michail/jheaps
src/test/java/org/jheaps/tree/LeftistHeapMergeableAddressableHeapTest.java
// Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // }
import java.util.Comparator; import org.jheaps.MergeableAddressableHeap;
/* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class LeftistHeapMergeableAddressableHeapTest extends AbstractMergeableAddressableHeapTest { @Override
// Path: src/main/java/org/jheaps/MergeableAddressableHeap.java // public interface MergeableAddressableHeap<K, V> extends AddressableHeap<K, V> { // // /** // * Meld a heap into the current heap. // * // * After the operation the {@code other} heap will be empty and will not // * permit further insertions. // * // * @param other // * a merge-able heap // * @throws ClassCastException // * if {@code other} is not compatible with this heap // * @throws IllegalArgumentException // * if {@code other} does not have a compatible comparator // */ // void meld(MergeableAddressableHeap<K, V> other); // // } // Path: src/test/java/org/jheaps/tree/LeftistHeapMergeableAddressableHeapTest.java import java.util.Comparator; import org.jheaps.MergeableAddressableHeap; /* * (C) Copyright 2014-2016, by Dimitrios Michail * * JHeaps Library * * 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.jheaps.tree; public class LeftistHeapMergeableAddressableHeapTest extends AbstractMergeableAddressableHeapTest { @Override
protected MergeableAddressableHeap<Integer, String> createHeap() {
brarcher/budget-watch
app/src/main/java/protect/budgetwatch/MainActivity.java
// Path: app/src/main/java/protect/budgetwatch/intro/IntroActivity.java // public class IntroActivity extends AppIntro // { // @Override // public void init(Bundle savedInstanceState) // { // addSlide(new IntroSlide1()); // addSlide(new IntroSlide2()); // addSlide(new IntroSlide3()); // addSlide(new IntroSlide4()); // addSlide(new IntroSlide5()); // addSlide(new IntroSlide6()); // addSlide(new IntroSlide7()); // } // // @Override // public void onSkipPressed(Fragment fragment) { // finish(); // } // // @Override // public void onDonePressed(Fragment fragment) { // finish(); // } // }
import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.common.collect.ImmutableMap; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import protect.budgetwatch.intro.IntroActivity;
String.format(getString(R.string.app_revision_fmt), "<a href=\"" + getString(R.string.app_revision_url) + "\">" + getString(R.string.app_revision_url) + "</a>") + "</p><hr/><p>" + String.format(getString(R.string.app_copyright_fmt), year) + "</p><hr/><p>" + getString(R.string.app_license) + "</p><hr/><p>" + String.format(getString(R.string.app_libraries), appName, libs.toString()) + "</p><hr/><p>" + String.format(getString(R.string.app_resources), appName, resources.toString()); wv.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "utf-8", null); new AlertDialog.Builder(this) .setView(wv) .setCancelable(true) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } private void startIntro() {
// Path: app/src/main/java/protect/budgetwatch/intro/IntroActivity.java // public class IntroActivity extends AppIntro // { // @Override // public void init(Bundle savedInstanceState) // { // addSlide(new IntroSlide1()); // addSlide(new IntroSlide2()); // addSlide(new IntroSlide3()); // addSlide(new IntroSlide4()); // addSlide(new IntroSlide5()); // addSlide(new IntroSlide6()); // addSlide(new IntroSlide7()); // } // // @Override // public void onSkipPressed(Fragment fragment) { // finish(); // } // // @Override // public void onDonePressed(Fragment fragment) { // finish(); // } // } // Path: app/src/main/java/protect/budgetwatch/MainActivity.java import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.common.collect.ImmutableMap; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import protect.budgetwatch.intro.IntroActivity; String.format(getString(R.string.app_revision_fmt), "<a href=\"" + getString(R.string.app_revision_url) + "\">" + getString(R.string.app_revision_url) + "</a>") + "</p><hr/><p>" + String.format(getString(R.string.app_copyright_fmt), year) + "</p><hr/><p>" + getString(R.string.app_license) + "</p><hr/><p>" + String.format(getString(R.string.app_libraries), appName, libs.toString()) + "</p><hr/><p>" + String.format(getString(R.string.app_resources), appName, resources.toString()); wv.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "utf-8", null); new AlertDialog.Builder(this) .setView(wv) .setCancelable(true) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } private void startIntro() {
Intent intent = new Intent(this, IntroActivity.class);
iiljkic/utp4j
src/main/java/net/utp4j/data/SelectiveAckHeaderExtension.java
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // }
import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUbyte; import java.util.Arrays;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Selective ACK header extension. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class SelectiveAckHeaderExtension extends UtpHeaderExtension { private byte nextExtension; private byte[] bitMask; /* Bit mappings */ public static byte[] BITMAP = { 1, 2, 4, 8, 16, 32, 64, (byte) 128}; /** * true if the ACK+number-th bit is set to 1 in the bitmask * @param bitmask bitmask * @param number number * @return true if bit is set, otherwise false. */ public static boolean isBitMarked(byte bitmask, int number) { if (number < 2 || number > 9 ) { return false; } else { boolean returnvalue = (BITMAP[number - 2] & bitmask) == BITMAP[number - 2]; return returnvalue; } } @Override public byte getNextExtension() { return nextExtension; } @Override public void setNextExtension(byte nextExtension) { this.nextExtension = nextExtension; } @Override public byte getLength() {
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // Path: src/main/java/net/utp4j/data/SelectiveAckHeaderExtension.java import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUbyte; import java.util.Arrays; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Selective ACK header extension. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class SelectiveAckHeaderExtension extends UtpHeaderExtension { private byte nextExtension; private byte[] bitMask; /* Bit mappings */ public static byte[] BITMAP = { 1, 2, 4, 8, 16, 32, 64, (byte) 128}; /** * true if the ACK+number-th bit is set to 1 in the bitmask * @param bitmask bitmask * @param number number * @return true if bit is set, otherwise false. */ public static boolean isBitMarked(byte bitmask, int number) { if (number < 2 || number > 9 ) { return false; } else { boolean returnvalue = (BITMAP[number - 2] & bitmask) == BITMAP[number - 2]; return returnvalue; } } @Override public byte getNextExtension() { return nextExtension; } @Override public void setNextExtension(byte nextExtension) { this.nextExtension = nextExtension; } @Override public byte getLength() {
return longToUbyte(bitMask.length);
iiljkic/utp4j
src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // }
import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues )
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // Path: src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues )
long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT;
iiljkic/utp4j
src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // }
import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues )
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // Path: src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues )
long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT;
iiljkic/utp4j
src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // }
import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues ) long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT; try {
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // Path: src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues ) long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT; try {
returnStamp = longToUint(stamp);
iiljkic/utp4j
src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // }
import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues ) long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT; try { returnStamp = longToUint(stamp);
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static final long MAX_UINT = 4294967295L; // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // Path: src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java import static net.utp4j.data.bytes.UnsignedTypesUtil.MAX_UINT; import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUint; import net.utp4j.data.bytes.UnsignedTypesUtil; import net.utp4j.data.bytes.exceptions.ByteOverflowException; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Implements micro second accuracy timestamps for uTP headers and to measure time elapsed. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class MicroSecondsTimeStamp { private static long initDateMillis = System.currentTimeMillis(); private static long startNs = System.nanoTime(); /** * Returns a uTP time stamp for packet headers. * @return timestamp */ public int utpTimeStamp() { int returnStamp; //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues ) long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT; try { returnStamp = longToUint(stamp);
} catch (ByteOverflowException exp) {
iiljkic/utp4j
src/main/java/net/utp4j/channels/impl/recieve/UtpRecieveRunnable.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UDP_HEADER_LENGTH = 48; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UTP_PACKET_LENGTH = 1500;
import static net.utp4j.data.UtpPacketUtils.MAX_UDP_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.MAX_UTP_PACKET_LENGTH; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.channels.impl.recieve; /** * Runs in a loop and listens on a {@see DataGramSocket} for incomming packets and passes them. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class UtpRecieveRunnable extends Thread implements Runnable { private DatagramSocket socket; private UtpPacketRecievable packetReciever; private boolean graceFullInterrupt = false; private final static Logger log = LoggerFactory.getLogger(UtpRecieveRunnable.class); public UtpRecieveRunnable(DatagramSocket socket, UtpPacketRecievable queueable) { this.socket = socket; this.packetReciever = queueable; } public void graceFullInterrupt() { super.interrupt(); graceFullInterrupt = true; socket.close(); } private boolean continueThread() { return !graceFullInterrupt; } @Override public void run() { while(continueThread()) {
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UDP_HEADER_LENGTH = 48; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UTP_PACKET_LENGTH = 1500; // Path: src/main/java/net/utp4j/channels/impl/recieve/UtpRecieveRunnable.java import static net.utp4j.data.UtpPacketUtils.MAX_UDP_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.MAX_UTP_PACKET_LENGTH; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.channels.impl.recieve; /** * Runs in a loop and listens on a {@see DataGramSocket} for incomming packets and passes them. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class UtpRecieveRunnable extends Thread implements Runnable { private DatagramSocket socket; private UtpPacketRecievable packetReciever; private boolean graceFullInterrupt = false; private final static Logger log = LoggerFactory.getLogger(UtpRecieveRunnable.class); public UtpRecieveRunnable(DatagramSocket socket, UtpPacketRecievable queueable) { this.socket = socket; this.packetReciever = queueable; } public void graceFullInterrupt() { super.interrupt(); graceFullInterrupt = true; socket.close(); } private boolean continueThread() { return !graceFullInterrupt; } @Override public void run() { while(continueThread()) {
byte[] buffer = new byte[MAX_UDP_HEADER_LENGTH + MAX_UTP_PACKET_LENGTH];
iiljkic/utp4j
src/main/java/net/utp4j/channels/impl/recieve/UtpRecieveRunnable.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UDP_HEADER_LENGTH = 48; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UTP_PACKET_LENGTH = 1500;
import static net.utp4j.data.UtpPacketUtils.MAX_UDP_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.MAX_UTP_PACKET_LENGTH; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.channels.impl.recieve; /** * Runs in a loop and listens on a {@see DataGramSocket} for incomming packets and passes them. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class UtpRecieveRunnable extends Thread implements Runnable { private DatagramSocket socket; private UtpPacketRecievable packetReciever; private boolean graceFullInterrupt = false; private final static Logger log = LoggerFactory.getLogger(UtpRecieveRunnable.class); public UtpRecieveRunnable(DatagramSocket socket, UtpPacketRecievable queueable) { this.socket = socket; this.packetReciever = queueable; } public void graceFullInterrupt() { super.interrupt(); graceFullInterrupt = true; socket.close(); } private boolean continueThread() { return !graceFullInterrupt; } @Override public void run() { while(continueThread()) {
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UDP_HEADER_LENGTH = 48; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int MAX_UTP_PACKET_LENGTH = 1500; // Path: src/main/java/net/utp4j/channels/impl/recieve/UtpRecieveRunnable.java import static net.utp4j.data.UtpPacketUtils.MAX_UDP_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.MAX_UTP_PACKET_LENGTH; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.channels.impl.recieve; /** * Runs in a loop and listens on a {@see DataGramSocket} for incomming packets and passes them. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class UtpRecieveRunnable extends Thread implements Runnable { private DatagramSocket socket; private UtpPacketRecievable packetReciever; private boolean graceFullInterrupt = false; private final static Logger log = LoggerFactory.getLogger(UtpRecieveRunnable.class); public UtpRecieveRunnable(DatagramSocket socket, UtpPacketRecievable queueable) { this.socket = socket; this.packetReciever = queueable; } public void graceFullInterrupt() { super.interrupt(); graceFullInterrupt = true; socket.close(); } private boolean continueThread() { return !graceFullInterrupt; } @Override public void run() { while(continueThread()) {
byte[] buffer = new byte[MAX_UDP_HEADER_LENGTH + MAX_UTP_PACKET_LENGTH];
iiljkic/utp4j
src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // }
import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001";
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // Path: src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001";
String actual0 = toBinaryString(DATA, type0excpected.length());
iiljkic/utp4j
src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // }
import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length());
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // Path: src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length());
String actual1 = toBinaryString(FIN, type1excpected.length());
iiljkic/utp4j
src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // }
import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length());
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // Path: src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length());
String actual2 = toBinaryString(STATE, type2excpected.length());
iiljkic/utp4j
src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // }
import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length()); String actual2 = toBinaryString(STATE, type2excpected.length());
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // Path: src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length()); String actual2 = toBinaryString(STATE, type2excpected.length());
String actual3 = toBinaryString(RESET, type3excpected.length());
iiljkic/utp4j
src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // }
import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length()); String actual2 = toBinaryString(STATE, type2excpected.length()); String actual3 = toBinaryString(RESET, type3excpected.length());
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // Path: src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length()); String actual2 = toBinaryString(STATE, type2excpected.length()); String actual3 = toBinaryString(RESET, type3excpected.length());
String actual4 = toBinaryString(SYN, type4excpected.length());
iiljkic/utp4j
src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // }
import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length()); String actual2 = toBinaryString(STATE, type2excpected.length()); String actual3 = toBinaryString(RESET, type3excpected.length()); String actual4 = toBinaryString(SYN, type4excpected.length()); assertEquals(type0excpected, actual0); assertEquals(type1excpected, actual1); assertEquals(type2excpected, actual2); assertEquals(type3excpected, actual3); assertEquals(type4excpected, actual4); } /** * Tests joinArray() with two arrays. */ @Test public void testJoinArray() { byte[] array1 = { 0, 1, 2}; byte[] array2 = {3, 4, 5};
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte DATA = (byte) (VERSION | longToUbyte(0)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte FIN = (byte) (VERSION | longToUbyte(16)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte RESET = (byte) (VERSION | longToUbyte(48)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte STATE = (byte) (VERSION | longToUbyte(32)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final byte SYN = (byte) (VERSION | longToUbyte(64)); // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // Path: src/test/java/net/utp4j/data/bytes/UtpPacketUtilsTest.java import static net.utp4j.data.UtpPacketUtils.DATA; import static net.utp4j.data.UtpPacketUtils.FIN; import static net.utp4j.data.UtpPacketUtils.RESET; import static net.utp4j.data.UtpPacketUtils.STATE; import static net.utp4j.data.UtpPacketUtils.SYN; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import static org.junit.Assert.assertEquals; import org.junit.Test; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data.bytes; public class UtpPacketUtilsTest { /** * Testing with type 0,1,2,3,4 which correspondents to: ST_DATA, ST_FIN, ST_STATE, ST_RESET, ST_SYN * and provoking exceptions for arguments out of range. * see http://bittorrent.org/beps/bep_0029.html */ @Test public void testTypeAndVersionByte() { String type0excpected = "1"; String type1excpected = "10001"; String type2excpected = "100001"; String type3excpected = "110001"; String type4excpected = "1000001"; String actual0 = toBinaryString(DATA, type0excpected.length()); String actual1 = toBinaryString(FIN, type1excpected.length()); String actual2 = toBinaryString(STATE, type2excpected.length()); String actual3 = toBinaryString(RESET, type3excpected.length()); String actual4 = toBinaryString(SYN, type4excpected.length()); assertEquals(type0excpected, actual0); assertEquals(type1excpected, actual1); assertEquals(type2excpected, actual2); assertEquals(type3excpected, actual3); assertEquals(type4excpected, actual4); } /** * Tests joinArray() with two arrays. */ @Test public void testJoinArray() { byte[] array1 = { 0, 1, 2}; byte[] array2 = {3, 4, 5};
byte[] returnArray = joinByteArray(array1, array2);
iiljkic/utp4j
src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java
// Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/SignedNumberException.java // public class SignedNumberException extends RuntimeException { // // private static final long serialVersionUID = 1339267381376290545L; // // public SignedNumberException(String message) { // super(message); // } // public SignedNumberException() { // super("No negative values allowed"); // } // // }
import net.utp4j.data.bytes.exceptions.ByteOverflowException; import net.utp4j.data.bytes.exceptions.SignedNumberException;
package net.utp4j.data.bytes; /** * * Workaround to java's lack of unsigned types. * Methods provided here intend to return integers, bytes and shorts which can be interpreted as unsigned types. * E.G. Java's byte initialized with 0xFF will correspond to -1, with this workaround we can use more readable * decimal value of 255 to convert it to -1, which in binary form is 11111111 and interpreted as an unsigned * value, it would be 255. * * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public final class UnsignedTypesUtil { public static final long MAX_UBYTE = 255; public static final long MAX_USHORT = 65535; public static final long MAX_UINT = 4294967295L; public static byte longToUbyte(long longvalue) { if (longvalue > MAX_UBYTE) {
// Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/SignedNumberException.java // public class SignedNumberException extends RuntimeException { // // private static final long serialVersionUID = 1339267381376290545L; // // public SignedNumberException(String message) { // super(message); // } // public SignedNumberException() { // super("No negative values allowed"); // } // // } // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java import net.utp4j.data.bytes.exceptions.ByteOverflowException; import net.utp4j.data.bytes.exceptions.SignedNumberException; package net.utp4j.data.bytes; /** * * Workaround to java's lack of unsigned types. * Methods provided here intend to return integers, bytes and shorts which can be interpreted as unsigned types. * E.G. Java's byte initialized with 0xFF will correspond to -1, with this workaround we can use more readable * decimal value of 255 to convert it to -1, which in binary form is 11111111 and interpreted as an unsigned * value, it would be 255. * * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public final class UnsignedTypesUtil { public static final long MAX_UBYTE = 255; public static final long MAX_USHORT = 65535; public static final long MAX_UINT = 4294967295L; public static byte longToUbyte(long longvalue) { if (longvalue > MAX_UBYTE) {
throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue));
iiljkic/utp4j
src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java
// Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/SignedNumberException.java // public class SignedNumberException extends RuntimeException { // // private static final long serialVersionUID = 1339267381376290545L; // // public SignedNumberException(String message) { // super(message); // } // public SignedNumberException() { // super("No negative values allowed"); // } // // }
import net.utp4j.data.bytes.exceptions.ByteOverflowException; import net.utp4j.data.bytes.exceptions.SignedNumberException;
package net.utp4j.data.bytes; /** * * Workaround to java's lack of unsigned types. * Methods provided here intend to return integers, bytes and shorts which can be interpreted as unsigned types. * E.G. Java's byte initialized with 0xFF will correspond to -1, with this workaround we can use more readable * decimal value of 255 to convert it to -1, which in binary form is 11111111 and interpreted as an unsigned * value, it would be 255. * * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public final class UnsignedTypesUtil { public static final long MAX_UBYTE = 255; public static final long MAX_USHORT = 65535; public static final long MAX_UINT = 4294967295L; public static byte longToUbyte(long longvalue) { if (longvalue > MAX_UBYTE) { throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); } else if (longvalue < 0) {
// Path: src/main/java/net/utp4j/data/bytes/exceptions/ByteOverflowException.java // public class ByteOverflowException extends RuntimeException { // // private static final long serialVersionUID = -2545130698255742704L; // // public ByteOverflowException(String message) { // super(message); // } // // public ByteOverflowException() { // super("Overflow happened."); // } // } // // Path: src/main/java/net/utp4j/data/bytes/exceptions/SignedNumberException.java // public class SignedNumberException extends RuntimeException { // // private static final long serialVersionUID = 1339267381376290545L; // // public SignedNumberException(String message) { // super(message); // } // public SignedNumberException() { // super("No negative values allowed"); // } // // } // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java import net.utp4j.data.bytes.exceptions.ByteOverflowException; import net.utp4j.data.bytes.exceptions.SignedNumberException; package net.utp4j.data.bytes; /** * * Workaround to java's lack of unsigned types. * Methods provided here intend to return integers, bytes and shorts which can be interpreted as unsigned types. * E.G. Java's byte initialized with 0xFF will correspond to -1, with this workaround we can use more readable * decimal value of 255 to convert it to -1, which in binary form is 11111111 and interpreted as an unsigned * value, it would be 255. * * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public final class UnsignedTypesUtil { public static final long MAX_UBYTE = 255; public static final long MAX_USHORT = 65535; public static final long MAX_UINT = 4294967295L; public static byte longToUbyte(long longvalue) { if (longvalue > MAX_UBYTE) { throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); } else if (longvalue < 0) {
throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue));
iiljkic/utp4j
src/main/java/net/utp4j/data/UtpHeaderExtension.java
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // }
import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUbyte;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Header Extension, uTP might support other header extensions someday. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public abstract class UtpHeaderExtension { public static UtpHeaderExtension resolve(byte b) {
// Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // Path: src/main/java/net/utp4j/data/UtpHeaderExtension.java import static net.utp4j.data.bytes.UnsignedTypesUtil.longToUbyte; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; /** * Header Extension, uTP might support other header extensions someday. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public abstract class UtpHeaderExtension { public static UtpHeaderExtension resolve(byte b) {
if (b == longToUbyte(1)) {
iiljkic/utp4j
src/main/java/net/utp4j/channels/exception/ChannelStateException.java
// Path: src/main/java/net/utp4j/channels/UtpSocketState.java // public enum UtpSocketState { // // /** // * Indicates that a syn packet has been send. // */ // SYN_SENT, // // /** // * Indicates that a connection has been established. // */ // CONNECTED, // // /** // * Indicates that no connection is established. // */ // CLOSED, // // /** // * Indicates that a SYN has been recieved but could not be acked. // */ // SYN_ACKING_FAILED, // // /** // * Indicates that the fin Packet has been send. // */ // FIN_SEND, // // /** // * Indicates that a fin was recieved. // */ // GOT_FIN, // // }
import java.net.SocketAddress; import net.utp4j.channels.UtpSocketState;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.channels.exception; /** * Exception indicates that the channel is in the wrong state. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class ChannelStateException extends RuntimeException { private static final long serialVersionUID = -6506270718267816636L;
// Path: src/main/java/net/utp4j/channels/UtpSocketState.java // public enum UtpSocketState { // // /** // * Indicates that a syn packet has been send. // */ // SYN_SENT, // // /** // * Indicates that a connection has been established. // */ // CONNECTED, // // /** // * Indicates that no connection is established. // */ // CLOSED, // // /** // * Indicates that a SYN has been recieved but could not be acked. // */ // SYN_ACKING_FAILED, // // /** // * Indicates that the fin Packet has been send. // */ // FIN_SEND, // // /** // * Indicates that a fin was recieved. // */ // GOT_FIN, // // } // Path: src/main/java/net/utp4j/channels/exception/ChannelStateException.java import java.net.SocketAddress; import net.utp4j.channels.UtpSocketState; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.channels.exception; /** * Exception indicates that the channel is in the wrong state. * @author Ivan Iljkic (i.iljkic@gmail.com) * */ public class ChannelStateException extends RuntimeException { private static final long serialVersionUID = -6506270718267816636L;
private UtpSocketState state;
iiljkic/utp4j
src/main/java/net/utp4j/data/UtpPacket.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int DEF_HEADER_LENGTH = 20; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // }
import static net.utp4j.data.UtpPacketUtils.DEF_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import java.util.ArrayList; import net.utp4j.data.bytes.UnsignedTypesUtil;
public int getWindowSize() { return windowSize; } public void setWindowSize(int windowSize) { this.windowSize = windowSize; } public short getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(short sequenceNumber) { this.sequenceNumber = sequenceNumber; } public short getAckNumber() { return ackNumber; } public void setAckNumber(short ackNumber) { this.ackNumber = ackNumber; } /** * Returns a byte array version of this packet. */ public byte[] toByteArray() { if (!hasExtensions()) {
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int DEF_HEADER_LENGTH = 20; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // Path: src/main/java/net/utp4j/data/UtpPacket.java import static net.utp4j.data.UtpPacketUtils.DEF_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import java.util.ArrayList; import net.utp4j.data.bytes.UnsignedTypesUtil; public int getWindowSize() { return windowSize; } public void setWindowSize(int windowSize) { this.windowSize = windowSize; } public short getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(short sequenceNumber) { this.sequenceNumber = sequenceNumber; } public short getAckNumber() { return ackNumber; } public void setAckNumber(short ackNumber) { this.ackNumber = ackNumber; } /** * Returns a byte array version of this packet. */ public byte[] toByteArray() { if (!hasExtensions()) {
return joinByteArray(getExtensionlessByteArray(), getPayload());
iiljkic/utp4j
src/main/java/net/utp4j/data/UtpPacket.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int DEF_HEADER_LENGTH = 20; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // }
import static net.utp4j.data.UtpPacketUtils.DEF_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import java.util.ArrayList; import net.utp4j.data.bytes.UnsignedTypesUtil;
public void setWindowSize(int windowSize) { this.windowSize = windowSize; } public short getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(short sequenceNumber) { this.sequenceNumber = sequenceNumber; } public short getAckNumber() { return ackNumber; } public void setAckNumber(short ackNumber) { this.ackNumber = ackNumber; } /** * Returns a byte array version of this packet. */ public byte[] toByteArray() { if (!hasExtensions()) { return joinByteArray(getExtensionlessByteArray(), getPayload()); }
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int DEF_HEADER_LENGTH = 20; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // Path: src/main/java/net/utp4j/data/UtpPacket.java import static net.utp4j.data.UtpPacketUtils.DEF_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import java.util.ArrayList; import net.utp4j.data.bytes.UnsignedTypesUtil; public void setWindowSize(int windowSize) { this.windowSize = windowSize; } public short getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(short sequenceNumber) { this.sequenceNumber = sequenceNumber; } public short getAckNumber() { return ackNumber; } public void setAckNumber(short ackNumber) { this.ackNumber = ackNumber; } /** * Returns a byte array version of this packet. */ public byte[] toByteArray() { if (!hasExtensions()) { return joinByteArray(getExtensionlessByteArray(), getPayload()); }
int offset = DEF_HEADER_LENGTH;
iiljkic/utp4j
src/main/java/net/utp4j/data/UtpPacket.java
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int DEF_HEADER_LENGTH = 20; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // }
import static net.utp4j.data.UtpPacketUtils.DEF_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import java.util.ArrayList; import net.utp4j.data.bytes.UnsignedTypesUtil;
int length = 0; for (int i = 0; i < extensions.length; i++) { length += 2 + extensions[i].getBitMask().length; } return length; } /** * returns the total packet length. * @return bytes. */ public int getPacketLength() { byte[] pl = getPayload(); int plLength = pl != null ? pl.length : 0; return DEF_HEADER_LENGTH + getTotalLengthOfExtensions() + plLength; } /** * Sets the packet data from the array * @param array the array * @param length total packet length * @param offset the packet starts here */ public void setFromByteArray(byte[] array, int length, int offset) { if (array == null) { return; } typeVersion = array[0]; firstExtension = array[1];
// Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static final int DEF_HEADER_LENGTH = 20; // // Path: src/main/java/net/utp4j/data/UtpPacketUtils.java // public static byte[] joinByteArray(byte[] array1, byte[] array2) { // // int length1 = array1 == null ? 0 : array1.length; // int length2 = array2 == null ? 0 : array2.length; // // // int totalLength = length1 + length2; // byte[] returnArray = new byte[totalLength]; // // int i = 0; // for (; i < length1; i++) { // returnArray[i] = array1[i]; // } // // for (int j = 0; j < length2; j++) { // returnArray[i] = array2[j]; // i++; // } // // return returnArray; // // } // // Path: src/main/java/net/utp4j/data/bytes/UnsignedTypesUtil.java // public final class UnsignedTypesUtil { // // public static final long MAX_UBYTE = 255; // public static final long MAX_USHORT = 65535; // public static final long MAX_UINT = 4294967295L; // // // public static byte longToUbyte(long longvalue) { // if (longvalue > MAX_UBYTE) { // throw new ByteOverflowException(getExceptionText(MAX_UBYTE, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UBYTE, longvalue)); // } // return (byte) (longvalue & 0xFF); // } // // public static short longToUshort(long longvalue) { // if (longvalue > MAX_USHORT) { // throw new ByteOverflowException(getExceptionText(MAX_USHORT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_USHORT, longvalue)); // } // return (short) (longvalue & 0xFFFF); // } // // public static int longToUint(long longvalue) { // if (longvalue > MAX_UINT) { // throw new ByteOverflowException(getExceptionText(MAX_UINT, longvalue)); // } else if (longvalue < 0) { // throw new SignedNumberException(getExceptionText(MAX_UINT, longvalue)); // } // return (int) (longvalue & 0xFFFFFFFF); // } // // private static String getExceptionText(long max, long actual) { // return "Cannot convert to unsigned type. " + // "Possible values [0, " + max + "] but got " + actual + "."; // } // // public static short bytesToUshort(byte first, byte second) { // short value = (short)( ((first & 0xFF) << 8) | (second & 0xFF) ); // return value; // } // // public static int bytesToUint(byte first, byte second, byte third, byte fourth) { // int firstI = (first & 0xFF) << 24; // int secondI = (second & 0xFF) << 16; // int thirdI = (third & 0xFF) << 8; // int fourthI = (fourth & 0xFF); // // return firstI | secondI | thirdI | fourthI; // // // } // // // // } // Path: src/main/java/net/utp4j/data/UtpPacket.java import static net.utp4j.data.UtpPacketUtils.DEF_HEADER_LENGTH; import static net.utp4j.data.UtpPacketUtils.joinByteArray; import java.util.ArrayList; import net.utp4j.data.bytes.UnsignedTypesUtil; int length = 0; for (int i = 0; i < extensions.length; i++) { length += 2 + extensions[i].getBitMask().length; } return length; } /** * returns the total packet length. * @return bytes. */ public int getPacketLength() { byte[] pl = getPayload(); int plLength = pl != null ? pl.length : 0; return DEF_HEADER_LENGTH + getTotalLengthOfExtensions() + plLength; } /** * Sets the packet data from the array * @param array the array * @param length total packet length * @param offset the packet starts here */ public void setFromByteArray(byte[] array, int length, int offset) { if (array == null) { return; } typeVersion = array[0]; firstExtension = array[1];
connectionId = UnsignedTypesUtil.bytesToUshort(array[2], array[3]);
iiljkic/utp4j
src/test/java/net/utp4j/data/MicroSecondsTimeStampTest.java
// Path: src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java // public class MicroSecondsTimeStamp { // // private static long initDateMillis = System.currentTimeMillis(); // private static long startNs = System.nanoTime(); // // /** // * Returns a uTP time stamp for packet headers. // * @return timestamp // */ // public int utpTimeStamp() { // int returnStamp; // //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues ) // long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT; // try { // returnStamp = longToUint(stamp); // } catch (ByteOverflowException exp) { // stamp = stamp % MAX_UINT; // returnStamp = longToUint(stamp); // } // return returnStamp; // } // // /** // * Calculates the Difference of the uTP timestamp between now and parameter. // * @param othertimestamp timestamp // * @return difference // */ // public int utpDifference(int othertimestamp) { // return utpDifference(utpTimeStamp(), othertimestamp); // } // /** // * calculates the utp Difference of timestamps (this - other) // * @param thisTimeStamp // * @param othertimestamp // * @return difference. // */ // public int utpDifference(int thisTimeStamp, int othertimestamp) { // int nowTime = thisTimeStamp; // long nowTimeL = nowTime & 0xFFFFFFFF; // long otherTimeL = othertimestamp & 0xFFFFFFFF; // long differenceL = nowTimeL - otherTimeL; // // TODO: POSSIBLE BUG NEGATIVE DIFFERENCE // if (differenceL < 0) { // differenceL += MAX_UINT; // } // return longToUint(differenceL); // } // // // /** // * @return timestamp with micro second resulution // */ // public long timeStamp() { // // long currentNs = System.nanoTime(); // long deltaMs = (currentNs - startNs)/1000; // return (initDateMillis*1000 + deltaMs); // } // // // public long getBegin() { // return (initDateMillis * 1000); // } // // public long getStartNs() { // return startNs; // } // // public long getInitDateMs() { // return initDateMillis; // } // // }
import static org.junit.Assert.assertTrue; import org.junit.Test; import net.utp4j.data.MicroSecondsTimeStamp;
/* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; public class MicroSecondsTimeStampTest { @Test public void test() throws InterruptedException {
// Path: src/main/java/net/utp4j/data/MicroSecondsTimeStamp.java // public class MicroSecondsTimeStamp { // // private static long initDateMillis = System.currentTimeMillis(); // private static long startNs = System.nanoTime(); // // /** // * Returns a uTP time stamp for packet headers. // * @return timestamp // */ // public int utpTimeStamp() { // int returnStamp; // //TODO: if performance issues, try bitwise & operator since constant MAX_UINT equals 0xFFFFFF // // (see http://en.wikipedia.org/wiki/Modulo_operation#Performance_issues ) // long stamp = timeStamp() % UnsignedTypesUtil.MAX_UINT; // try { // returnStamp = longToUint(stamp); // } catch (ByteOverflowException exp) { // stamp = stamp % MAX_UINT; // returnStamp = longToUint(stamp); // } // return returnStamp; // } // // /** // * Calculates the Difference of the uTP timestamp between now and parameter. // * @param othertimestamp timestamp // * @return difference // */ // public int utpDifference(int othertimestamp) { // return utpDifference(utpTimeStamp(), othertimestamp); // } // /** // * calculates the utp Difference of timestamps (this - other) // * @param thisTimeStamp // * @param othertimestamp // * @return difference. // */ // public int utpDifference(int thisTimeStamp, int othertimestamp) { // int nowTime = thisTimeStamp; // long nowTimeL = nowTime & 0xFFFFFFFF; // long otherTimeL = othertimestamp & 0xFFFFFFFF; // long differenceL = nowTimeL - otherTimeL; // // TODO: POSSIBLE BUG NEGATIVE DIFFERENCE // if (differenceL < 0) { // differenceL += MAX_UINT; // } // return longToUint(differenceL); // } // // // /** // * @return timestamp with micro second resulution // */ // public long timeStamp() { // // long currentNs = System.nanoTime(); // long deltaMs = (currentNs - startNs)/1000; // return (initDateMillis*1000 + deltaMs); // } // // // public long getBegin() { // return (initDateMillis * 1000); // } // // public long getStartNs() { // return startNs; // } // // public long getInitDateMs() { // return initDateMillis; // } // // } // Path: src/test/java/net/utp4j/data/MicroSecondsTimeStampTest.java import static org.junit.Assert.assertTrue; import org.junit.Test; import net.utp4j.data.MicroSecondsTimeStamp; /* Copyright 2013 Ivan Iljkic * * 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 net.utp4j.data; public class MicroSecondsTimeStampTest { @Test public void test() throws InterruptedException {
MicroSecondsTimeStamp stamp1 = new MicroSecondsTimeStamp();
lkoskela/beaninject
src/test/java/org/laughingpanda/beaninject/example/TestExample.java
// Path: src/main/java/org/laughingpanda/beaninject/Inject.java // public class Inject { // // /** // * Returns a target identifier that uses an injector that injects directly // * to a member field regardless of the field's visibility. // * // * @param fieldName // * The name of the field to inject. // */ // public static ITargetIdentifier field(final String fieldName) { // return new ITargetIdentifier() { // public IDependencyInjector of(final Object target) { // return new FieldInjector(target, fieldName); // } // }; // } // // public static ITargetIdentifier fieldAnnotatedWith( // final Class<? extends Annotation> annotation) { // return new ITargetIdentifier() { // public IDependencyInjector of(Object target) { // return new AnnotatedFieldInjector(target, annotation); // } // }; // } // // public static IStaticTargetIdentifier staticField(final String fieldName) { // return new IStaticTargetIdentifier() { // public IDependencyInjector of(final Class<?> target) { // return new StaticNamedFieldInjector(target, fieldName); // } // }; // } // // /** // * Returns a target identifier that uses an injector that injects through a // * property setter method (regardless of the method's visibility). // * // * @param propertyName // * The name of the property to inject. E.g. "foo" where the // * respective setter method's name is "setFoo". // */ // public static ITargetIdentifier property(final String propertyName) { // return new ITargetIdentifier() { // public IDependencyInjector of(Object target) { // String methodName = "set" // + propertyName.substring(0, 1).toUpperCase() // + propertyName.substring(1); // return new MethodInjector(target, methodName); // } // }; // } // // public static ITargetIdentifier propertyAnnotatedWith( // final Class<? extends Annotation> annotation) { // return new ITargetIdentifier() { // public IDependencyInjector of(Object target) { // return new AnnotatedMethodInjector(target, annotation); // } // }; // } // // /** // * Returns an injector implementation which uses the given dependency // * object's type to infer which setter/field to inject. // * // * @param target // * The target object for injection. // */ // public static IVarargDependencyInjector bean(final Object target) { // return new AbstractVarargDependencyInjector() { // public void with(Object... dependencies) { // TypeBasedInjector injector = new TypeBasedInjector(); // for (Object dependency : dependencies) { // injector.validateInjectionOf(target, dependency); // } // for (Object dependency : dependencies) { // injector.inject(target, dependency); // } // } // }; // } // // /** // * Returns an injector implementation which delegates actual injection to // * the given strategy when provided with a target to inject. // * // * @param strategy // * The injection strategy. // */ // public static ITargetInjector with(final IInjectionStrategy strategy) { // return new ITargetInjector() { // public void bean(Object target) { // strategy.inject(target); // } // }; // } // // public static IDependencyInjector staticFieldOf(final Class<?> targetClass) { // return new IDependencyInjector() { // public void with(Object dependency) { // new StaticTypedFieldInjector(targetClass).with(dependency); // } // }; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.Test; import org.laughingpanda.beaninject.Inject;
/* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject.example; /** * @author Lasse Koskela */ public class TestExample { private Target target; public class Target { private String field; public void setPropertyName(String value) { this.field = value; } public String getPropertyName() { return field; } } public static junit.framework.Test suite() { return new JUnit4TestAdapter(TestExample.class); } @Before public void setUp() { target = new Target(); assertNull(target.getPropertyName()); } @Test public void exampleOfInjectingWithSetter() throws Exception {
// Path: src/main/java/org/laughingpanda/beaninject/Inject.java // public class Inject { // // /** // * Returns a target identifier that uses an injector that injects directly // * to a member field regardless of the field's visibility. // * // * @param fieldName // * The name of the field to inject. // */ // public static ITargetIdentifier field(final String fieldName) { // return new ITargetIdentifier() { // public IDependencyInjector of(final Object target) { // return new FieldInjector(target, fieldName); // } // }; // } // // public static ITargetIdentifier fieldAnnotatedWith( // final Class<? extends Annotation> annotation) { // return new ITargetIdentifier() { // public IDependencyInjector of(Object target) { // return new AnnotatedFieldInjector(target, annotation); // } // }; // } // // public static IStaticTargetIdentifier staticField(final String fieldName) { // return new IStaticTargetIdentifier() { // public IDependencyInjector of(final Class<?> target) { // return new StaticNamedFieldInjector(target, fieldName); // } // }; // } // // /** // * Returns a target identifier that uses an injector that injects through a // * property setter method (regardless of the method's visibility). // * // * @param propertyName // * The name of the property to inject. E.g. "foo" where the // * respective setter method's name is "setFoo". // */ // public static ITargetIdentifier property(final String propertyName) { // return new ITargetIdentifier() { // public IDependencyInjector of(Object target) { // String methodName = "set" // + propertyName.substring(0, 1).toUpperCase() // + propertyName.substring(1); // return new MethodInjector(target, methodName); // } // }; // } // // public static ITargetIdentifier propertyAnnotatedWith( // final Class<? extends Annotation> annotation) { // return new ITargetIdentifier() { // public IDependencyInjector of(Object target) { // return new AnnotatedMethodInjector(target, annotation); // } // }; // } // // /** // * Returns an injector implementation which uses the given dependency // * object's type to infer which setter/field to inject. // * // * @param target // * The target object for injection. // */ // public static IVarargDependencyInjector bean(final Object target) { // return new AbstractVarargDependencyInjector() { // public void with(Object... dependencies) { // TypeBasedInjector injector = new TypeBasedInjector(); // for (Object dependency : dependencies) { // injector.validateInjectionOf(target, dependency); // } // for (Object dependency : dependencies) { // injector.inject(target, dependency); // } // } // }; // } // // /** // * Returns an injector implementation which delegates actual injection to // * the given strategy when provided with a target to inject. // * // * @param strategy // * The injection strategy. // */ // public static ITargetInjector with(final IInjectionStrategy strategy) { // return new ITargetInjector() { // public void bean(Object target) { // strategy.inject(target); // } // }; // } // // public static IDependencyInjector staticFieldOf(final Class<?> targetClass) { // return new IDependencyInjector() { // public void with(Object dependency) { // new StaticTypedFieldInjector(targetClass).with(dependency); // } // }; // } // } // Path: src/test/java/org/laughingpanda/beaninject/example/TestExample.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.Test; import org.laughingpanda.beaninject.Inject; /* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject.example; /** * @author Lasse Koskela */ public class TestExample { private Target target; public class Target { private String field; public void setPropertyName(String value) { this.field = value; } public String getPropertyName() { return field; } } public static junit.framework.Test suite() { return new JUnit4TestAdapter(TestExample.class); } @Before public void setUp() { target = new Target(); assertNull(target.getPropertyName()); } @Test public void exampleOfInjectingWithSetter() throws Exception {
Inject.property("propertyName").of(target).with("value");
lkoskela/beaninject
src/main/java/org/laughingpanda/beaninject/impl/StaticTypedFieldInjector.java
// Path: src/main/java/org/laughingpanda/beaninject/InjectionError.java // @SuppressWarnings("serial") // public class InjectionError extends RuntimeException { // public InjectionError(String detail, Class<?> dependencyType) { // super("Injection failed: " + detail.trim() + " for an object of type " // + dependencyType.getName()); // } // }
import java.lang.reflect.Field; import java.util.List; import org.laughingpanda.beaninject.InjectionError;
/* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject.impl; /** * @author Lasse Koskela */ public class StaticTypedFieldInjector extends AbstractObjectInjector { private Class<?> targetClass; public StaticTypedFieldInjector(Class<?> targetClass) { super(targetClass, null); this.targetClass = targetClass; } public void with(Object dependency) { List<Field> fields = collectMatchingStaticFieldsFrom(dependency .getClass()); if (fields.isEmpty()) {
// Path: src/main/java/org/laughingpanda/beaninject/InjectionError.java // @SuppressWarnings("serial") // public class InjectionError extends RuntimeException { // public InjectionError(String detail, Class<?> dependencyType) { // super("Injection failed: " + detail.trim() + " for an object of type " // + dependencyType.getName()); // } // } // Path: src/main/java/org/laughingpanda/beaninject/impl/StaticTypedFieldInjector.java import java.lang.reflect.Field; import java.util.List; import org.laughingpanda.beaninject.InjectionError; /* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject.impl; /** * @author Lasse Koskela */ public class StaticTypedFieldInjector extends AbstractObjectInjector { private Class<?> targetClass; public StaticTypedFieldInjector(Class<?> targetClass) { super(targetClass, null); this.targetClass = targetClass; } public void with(Object dependency) { List<Field> fields = collectMatchingStaticFieldsFrom(dependency .getClass()); if (fields.isEmpty()) {
throw new InjectionError("no matching static field", dependency
lkoskela/beaninject
src/test/java/org/laughingpanda/beaninject/TestTypeInjectionWithMultipleValues.java
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassA.java // public class TypeClassA extends TypeClass { // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassB.java // public class TypeClassB extends TypeClass { // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor; import org.laughingpanda.beaninject.target.TypeClassA; import org.laughingpanda.beaninject.target.TypeClassB;
/* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject; /** * @author Lasse Koskela */ public class TestTypeInjectionWithMultipleValues { private Object target = new Object() { @SuppressWarnings("unused")
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassA.java // public class TypeClassA extends TypeClass { // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassB.java // public class TypeClassB extends TypeClass { // } // Path: src/test/java/org/laughingpanda/beaninject/TestTypeInjectionWithMultipleValues.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor; import org.laughingpanda.beaninject.target.TypeClassA; import org.laughingpanda.beaninject.target.TypeClassB; /* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject; /** * @author Lasse Koskela */ public class TestTypeInjectionWithMultipleValues { private Object target = new Object() { @SuppressWarnings("unused")
public TypeClassA fieldA;
lkoskela/beaninject
src/test/java/org/laughingpanda/beaninject/TestTypeInjectionWithMultipleValues.java
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassA.java // public class TypeClassA extends TypeClass { // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassB.java // public class TypeClassB extends TypeClass { // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor; import org.laughingpanda.beaninject.target.TypeClassA; import org.laughingpanda.beaninject.target.TypeClassB;
/* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject; /** * @author Lasse Koskela */ public class TestTypeInjectionWithMultipleValues { private Object target = new Object() { @SuppressWarnings("unused") public TypeClassA fieldA; @SuppressWarnings("unused")
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassA.java // public class TypeClassA extends TypeClass { // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassB.java // public class TypeClassB extends TypeClass { // } // Path: src/test/java/org/laughingpanda/beaninject/TestTypeInjectionWithMultipleValues.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor; import org.laughingpanda.beaninject.target.TypeClassA; import org.laughingpanda.beaninject.target.TypeClassB; /* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject; /** * @author Lasse Koskela */ public class TestTypeInjectionWithMultipleValues { private Object target = new Object() { @SuppressWarnings("unused") public TypeClassA fieldA; @SuppressWarnings("unused")
public TypeClassB fieldB;
lkoskela/beaninject
src/test/java/org/laughingpanda/beaninject/TestTypeInjectionWithMultipleValues.java
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassA.java // public class TypeClassA extends TypeClass { // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassB.java // public class TypeClassB extends TypeClass { // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor; import org.laughingpanda.beaninject.target.TypeClassA; import org.laughingpanda.beaninject.target.TypeClassB;
/* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject; /** * @author Lasse Koskela */ public class TestTypeInjectionWithMultipleValues { private Object target = new Object() { @SuppressWarnings("unused") public TypeClassA fieldA; @SuppressWarnings("unused") public TypeClassB fieldB; }; @Test public void multipleObjectsToInjectByType() throws Exception { TypeClassA valueForA = new TypeClassA(); TypeClassB valueForB = new TypeClassB(); Inject.bean(target).with(valueForA, valueForB); assertEquals(readField("fieldA", target), valueForA); assertEquals(readField("fieldB", target), valueForB); } @Test public void multipleObjectsToInjectByTypeWhenSomeFail() throws Exception { try { Inject.bean(target).with(new TypeClassA(), new String()); fail("Type-based injection should fail if injection of any of the provided values fails."); } catch (Exception expected) { } assertNull(readField("fieldA", target)); assertNull(readField("fieldB", target)); } private Object readField(String name, Object target) throws Exception {
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassA.java // public class TypeClassA extends TypeClass { // } // // Path: src/test/java/org/laughingpanda/beaninject/target/TypeClassB.java // public class TypeClassB extends TypeClass { // } // Path: src/test/java/org/laughingpanda/beaninject/TestTypeInjectionWithMultipleValues.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import junit.framework.JUnit4TestAdapter; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor; import org.laughingpanda.beaninject.target.TypeClassA; import org.laughingpanda.beaninject.target.TypeClassB; /* * Copyright 2006 Lasse Koskela * * 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.laughingpanda.beaninject; /** * @author Lasse Koskela */ public class TestTypeInjectionWithMultipleValues { private Object target = new Object() { @SuppressWarnings("unused") public TypeClassA fieldA; @SuppressWarnings("unused") public TypeClassB fieldB; }; @Test public void multipleObjectsToInjectByType() throws Exception { TypeClassA valueForA = new TypeClassA(); TypeClassB valueForB = new TypeClassB(); Inject.bean(target).with(valueForA, valueForB); assertEquals(readField("fieldA", target), valueForA); assertEquals(readField("fieldB", target), valueForB); } @Test public void multipleObjectsToInjectByTypeWhenSomeFail() throws Exception { try { Inject.bean(target).with(new TypeClassA(), new String()); fail("Type-based injection should fail if injection of any of the provided values fails."); } catch (Exception expected) { } assertNull(readField("fieldA", target)); assertNull(readField("fieldB", target)); } private Object readField(String name, Object target) throws Exception {
return Accessor.field(name, target.getClass()).get(target);
lkoskela/beaninject
src/test/java/org/laughingpanda/beaninject/TestStaticFieldInjection.java
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor;
@SuppressWarnings("unused") public static class ClassWithMultipleFieldsOfSameType { private static Object privateStaticObject; private static Object anotherPrivateStaticObject; private static PepsiMax privateStaticPepsiMax; private static PepsiMax anotherPrivateStaticPepsiMax; } @SuppressWarnings("unused") public static class ClassWithMultipleFieldsOfSameInterface { private static Drinkable privateStaticDrinkable; private static Drinkable anotherPrivateStaticDrinkable; } @SuppressWarnings("unused") public static class ClassWithOneFieldOfEachNonRelatedType { private static int privateStaticInt; private static Apple privateStaticApple; private static Drinkable privateStaticDrinkable; } @Before public void setUp() throws Exception { resetStaticFieldsOf(ClassWithoutFields.class); resetStaticFieldsOf(ClassWithMultipleFieldsOfSameType.class); resetStaticFieldsOf(ClassWithMultipleFieldsOfSameInterface.class); resetStaticFieldsOf(ClassWithOneFieldOfEachNonRelatedType.class); } private void resetStaticFieldsOf(Class<?> klass) {
// Path: src/main/java/org/laughingpanda/beaninject/impl/Accessor.java // public class Accessor { // // public static List<Method> methods(Class<?> clazz) { // Method[] declared = clazz.getDeclaredMethods(); // List<Method> methods = new ArrayList<Method>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // methods.addAll(methods(clazz.getSuperclass())); // } // return methods; // } // // public static List<Field> fields(Class<?> clazz) { // Field[] declared = clazz.getDeclaredFields(); // List<Field> fields = new ArrayList<Field>(Arrays // .asList(declared)); // if (clazz.getSuperclass() != null) { // fields.addAll(fields(clazz.getSuperclass())); // } // return fields; // } // // public static Field field(String name, Class<?> clazz) { // for (Field field : fields(clazz)) { // if (field.getName().equals(name)) { // return makeAccessible(field); // } // } // return null; // } // // private static Field makeAccessible(Field field) { // if (!field.isAccessible()) { // field.setAccessible(true); // } // return field; // } // // public static List<Field> fieldsAssignableFrom(Class<?> type, // Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().isAssignableFrom(type)) { // fields.add(field); // } // } // return fields; // } // // public static List<Field> fieldsOfType(Class<?> type, Class<?> target) { // List<Field> fields = new ArrayList<Field>(); // for (Field field : fields(target)) { // if (field.getType().equals(type)) { // fields.add(field); // } // } // return fields; // } // // public static Field annotatedField( // Class<? extends Annotation> annotation, // Class<? extends Object> clazz) { // for (Field field : fields(clazz)) { // if (field.isAnnotationPresent(annotation)) { // return field; // } // } // return null; // } // // } // Path: src/test/java/org/laughingpanda/beaninject/TestStaticFieldInjection.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import junit.framework.JUnit4TestAdapter; import org.junit.Before; import org.junit.Test; import org.laughingpanda.beaninject.impl.Accessor; @SuppressWarnings("unused") public static class ClassWithMultipleFieldsOfSameType { private static Object privateStaticObject; private static Object anotherPrivateStaticObject; private static PepsiMax privateStaticPepsiMax; private static PepsiMax anotherPrivateStaticPepsiMax; } @SuppressWarnings("unused") public static class ClassWithMultipleFieldsOfSameInterface { private static Drinkable privateStaticDrinkable; private static Drinkable anotherPrivateStaticDrinkable; } @SuppressWarnings("unused") public static class ClassWithOneFieldOfEachNonRelatedType { private static int privateStaticInt; private static Apple privateStaticApple; private static Drinkable privateStaticDrinkable; } @Before public void setUp() throws Exception { resetStaticFieldsOf(ClassWithoutFields.class); resetStaticFieldsOf(ClassWithMultipleFieldsOfSameType.class); resetStaticFieldsOf(ClassWithMultipleFieldsOfSameInterface.class); resetStaticFieldsOf(ClassWithOneFieldOfEachNonRelatedType.class); } private void resetStaticFieldsOf(Class<?> klass) {
for (Field field : Accessor.fields(klass)) {
anaselhajjaji/android-samples
JsonSample/app/src/main/java/com/example/anas/jsonsample/MainActivity.java
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java // public interface JsonService { // // @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1") // Call<JsonAnswer> getAnswers(); // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/Utils.java // public class Utils { // public static final String BASE_URL = "https://fantasy.premierleague.com/"; // // public static JsonService getJsonService() { // return RetrofitClient.getClient(BASE_URL).create(JsonService.class); // } // }
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.anas.jsonsample.model.JsonAnswer; import com.example.anas.jsonsample.service.JsonService; import com.example.anas.jsonsample.service.Utils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package com.example.anas.jsonsample; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StandingsResultsAdapter mAdapter;
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java // public interface JsonService { // // @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1") // Call<JsonAnswer> getAnswers(); // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/Utils.java // public class Utils { // public static final String BASE_URL = "https://fantasy.premierleague.com/"; // // public static JsonService getJsonService() { // return RetrofitClient.getClient(BASE_URL).create(JsonService.class); // } // } // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.anas.jsonsample.model.JsonAnswer; import com.example.anas.jsonsample.service.JsonService; import com.example.anas.jsonsample.service.Utils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; package com.example.anas.jsonsample; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StandingsResultsAdapter mAdapter;
private JsonService mService;
anaselhajjaji/android-samples
JsonSample/app/src/main/java/com/example/anas/jsonsample/MainActivity.java
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java // public interface JsonService { // // @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1") // Call<JsonAnswer> getAnswers(); // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/Utils.java // public class Utils { // public static final String BASE_URL = "https://fantasy.premierleague.com/"; // // public static JsonService getJsonService() { // return RetrofitClient.getClient(BASE_URL).create(JsonService.class); // } // }
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.anas.jsonsample.model.JsonAnswer; import com.example.anas.jsonsample.service.JsonService; import com.example.anas.jsonsample.service.Utils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package com.example.anas.jsonsample; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StandingsResultsAdapter mAdapter; private JsonService mService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java // public interface JsonService { // // @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1") // Call<JsonAnswer> getAnswers(); // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/Utils.java // public class Utils { // public static final String BASE_URL = "https://fantasy.premierleague.com/"; // // public static JsonService getJsonService() { // return RetrofitClient.getClient(BASE_URL).create(JsonService.class); // } // } // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.anas.jsonsample.model.JsonAnswer; import com.example.anas.jsonsample.service.JsonService; import com.example.anas.jsonsample.service.Utils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; package com.example.anas.jsonsample; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StandingsResultsAdapter mAdapter; private JsonService mService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
mService = Utils.getJsonService();
anaselhajjaji/android-samples
JsonSample/app/src/main/java/com/example/anas/jsonsample/MainActivity.java
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java // public interface JsonService { // // @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1") // Call<JsonAnswer> getAnswers(); // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/Utils.java // public class Utils { // public static final String BASE_URL = "https://fantasy.premierleague.com/"; // // public static JsonService getJsonService() { // return RetrofitClient.getClient(BASE_URL).create(JsonService.class); // } // }
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.anas.jsonsample.model.JsonAnswer; import com.example.anas.jsonsample.service.JsonService; import com.example.anas.jsonsample.service.Utils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package com.example.anas.jsonsample; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StandingsResultsAdapter mAdapter; private JsonService mService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mService = Utils.getJsonService(); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); mAdapter = new StandingsResultsAdapter(); recyclerView.setAdapter(mAdapter); prepareData(); } private void prepareData() {
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java // public interface JsonService { // // @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1") // Call<JsonAnswer> getAnswers(); // } // // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/Utils.java // public class Utils { // public static final String BASE_URL = "https://fantasy.premierleague.com/"; // // public static JsonService getJsonService() { // return RetrofitClient.getClient(BASE_URL).create(JsonService.class); // } // } // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.anas.jsonsample.model.JsonAnswer; import com.example.anas.jsonsample.service.JsonService; import com.example.anas.jsonsample.service.Utils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; package com.example.anas.jsonsample; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private StandingsResultsAdapter mAdapter; private JsonService mService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mService = Utils.getJsonService(); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); mAdapter = new StandingsResultsAdapter(); recyclerView.setAdapter(mAdapter); prepareData(); } private void prepareData() {
mService.getAnswers().enqueue(new Callback<JsonAnswer>() {
anaselhajjaji/android-samples
JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // }
import com.example.anas.jsonsample.model.JsonAnswer; import retrofit2.Call; import retrofit2.http.GET;
package com.example.anas.jsonsample.service; /** * Created by anas on 10/11/2017. */ public interface JsonService { @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1")
// Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/model/JsonAnswer.java // public class JsonAnswer { // // @SerializedName("new_entries") // @Expose // private NewEntries newEntries; // @SerializedName("league") // @Expose // private League league; // @SerializedName("standings") // @Expose // private Standings standings; // @SerializedName("update_status") // @Expose // private Integer updateStatus; // // public NewEntries getNewEntries() { // return newEntries; // } // // public void setNewEntries(NewEntries newEntries) { // this.newEntries = newEntries; // } // // public League getLeague() { // return league; // } // // public void setLeague(League league) { // this.league = league; // } // // public Standings getStandings() { // return standings; // } // // public void setStandings(Standings standings) { // this.standings = standings; // } // // public Integer getUpdateStatus() { // return updateStatus; // } // // public void setUpdateStatus(Integer updateStatus) { // this.updateStatus = updateStatus; // } // // } // Path: JsonSample/app/src/main/java/com/example/anas/jsonsample/service/JsonService.java import com.example.anas.jsonsample.model.JsonAnswer; import retrofit2.Call; import retrofit2.http.GET; package com.example.anas.jsonsample.service; /** * Created by anas on 10/11/2017. */ public interface JsonService { @GET("/drf/leagues-classic-standings/624264?phase=1&le-page=1&ls-page=1")
Call<JsonAnswer> getAnswers();
x-hansong/EasyChat
Server/src/main/java/com/easychat/service/UserService.java
// Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/dto/output/UserDetailDTO.java // public class UserDetailDTO { // private Long id; // private String name; // private String nick; // private String sex; // private String phone; // private String email; // private String avatar; // private String signInfo; // // public UserDetailDTO() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // } // // Path: Server/src/main/java/com/easychat/model/entity/User.java // @Entity // @Table(name="User") // public class User implements Serializable{ // public User() { // this.sex = "0"; // this.name = ""; // this.nick = ""; // this.password = ""; // this.phone = ""; // this.email = ""; // this.avatar = ""; // this.signInfo = ""; // } // // @Id // @GeneratedValue // @Column(name="id") // private Long id; // // @Column(name="sex") // private String sex; // // @Column(name="name") // private String name; // // @Column(name="nick") // private String nick; // // @Column(name="password") // private String password; // // // @Column(name="phone") // private String phone; // // @Column(name="email") // private String email; // // @Column(name="avatar") // private String avatar; // // // @Column(name="sign_info") // private String signInfo; // // @OneToMany // @JoinTable( // name = "FriendRelationship", // joinColumns = @JoinColumn(name = "aid"), // inverseJoinColumns = @JoinColumn(name = "bid") // ) // private Set<User> friendList = new HashSet<>(); // // public Set<User> getFriendList() { // return friendList; // } // // public void setFriendList(Set<User> friendList) { // this.friendList = friendList; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // }
import com.easychat.model.dto.input.UserDTO; import com.easychat.model.dto.output.UserDetailDTO; import com.easychat.model.entity.User;
package com.easychat.service; /** * Created by yonah on 15-10-18 */ public interface UserService { void addUser(UserDTO userDTO);
// Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/dto/output/UserDetailDTO.java // public class UserDetailDTO { // private Long id; // private String name; // private String nick; // private String sex; // private String phone; // private String email; // private String avatar; // private String signInfo; // // public UserDetailDTO() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // } // // Path: Server/src/main/java/com/easychat/model/entity/User.java // @Entity // @Table(name="User") // public class User implements Serializable{ // public User() { // this.sex = "0"; // this.name = ""; // this.nick = ""; // this.password = ""; // this.phone = ""; // this.email = ""; // this.avatar = ""; // this.signInfo = ""; // } // // @Id // @GeneratedValue // @Column(name="id") // private Long id; // // @Column(name="sex") // private String sex; // // @Column(name="name") // private String name; // // @Column(name="nick") // private String nick; // // @Column(name="password") // private String password; // // // @Column(name="phone") // private String phone; // // @Column(name="email") // private String email; // // @Column(name="avatar") // private String avatar; // // // @Column(name="sign_info") // private String signInfo; // // @OneToMany // @JoinTable( // name = "FriendRelationship", // joinColumns = @JoinColumn(name = "aid"), // inverseJoinColumns = @JoinColumn(name = "bid") // ) // private Set<User> friendList = new HashSet<>(); // // public Set<User> getFriendList() { // return friendList; // } // // public void setFriendList(Set<User> friendList) { // this.friendList = friendList; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // } // Path: Server/src/main/java/com/easychat/service/UserService.java import com.easychat.model.dto.input.UserDTO; import com.easychat.model.dto.output.UserDetailDTO; import com.easychat.model.entity.User; package com.easychat.service; /** * Created by yonah on 15-10-18 */ public interface UserService { void addUser(UserDTO userDTO);
User authenticate(UserDTO userDTO);
x-hansong/EasyChat
Server/src/main/java/com/easychat/service/UserService.java
// Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/dto/output/UserDetailDTO.java // public class UserDetailDTO { // private Long id; // private String name; // private String nick; // private String sex; // private String phone; // private String email; // private String avatar; // private String signInfo; // // public UserDetailDTO() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // } // // Path: Server/src/main/java/com/easychat/model/entity/User.java // @Entity // @Table(name="User") // public class User implements Serializable{ // public User() { // this.sex = "0"; // this.name = ""; // this.nick = ""; // this.password = ""; // this.phone = ""; // this.email = ""; // this.avatar = ""; // this.signInfo = ""; // } // // @Id // @GeneratedValue // @Column(name="id") // private Long id; // // @Column(name="sex") // private String sex; // // @Column(name="name") // private String name; // // @Column(name="nick") // private String nick; // // @Column(name="password") // private String password; // // // @Column(name="phone") // private String phone; // // @Column(name="email") // private String email; // // @Column(name="avatar") // private String avatar; // // // @Column(name="sign_info") // private String signInfo; // // @OneToMany // @JoinTable( // name = "FriendRelationship", // joinColumns = @JoinColumn(name = "aid"), // inverseJoinColumns = @JoinColumn(name = "bid") // ) // private Set<User> friendList = new HashSet<>(); // // public Set<User> getFriendList() { // return friendList; // } // // public void setFriendList(Set<User> friendList) { // this.friendList = friendList; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // }
import com.easychat.model.dto.input.UserDTO; import com.easychat.model.dto.output.UserDetailDTO; import com.easychat.model.entity.User;
package com.easychat.service; /** * Created by yonah on 15-10-18 */ public interface UserService { void addUser(UserDTO userDTO); User authenticate(UserDTO userDTO); void modifyUserInfo(String name,String json);
// Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/dto/output/UserDetailDTO.java // public class UserDetailDTO { // private Long id; // private String name; // private String nick; // private String sex; // private String phone; // private String email; // private String avatar; // private String signInfo; // // public UserDetailDTO() { // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // } // // Path: Server/src/main/java/com/easychat/model/entity/User.java // @Entity // @Table(name="User") // public class User implements Serializable{ // public User() { // this.sex = "0"; // this.name = ""; // this.nick = ""; // this.password = ""; // this.phone = ""; // this.email = ""; // this.avatar = ""; // this.signInfo = ""; // } // // @Id // @GeneratedValue // @Column(name="id") // private Long id; // // @Column(name="sex") // private String sex; // // @Column(name="name") // private String name; // // @Column(name="nick") // private String nick; // // @Column(name="password") // private String password; // // // @Column(name="phone") // private String phone; // // @Column(name="email") // private String email; // // @Column(name="avatar") // private String avatar; // // // @Column(name="sign_info") // private String signInfo; // // @OneToMany // @JoinTable( // name = "FriendRelationship", // joinColumns = @JoinColumn(name = "aid"), // inverseJoinColumns = @JoinColumn(name = "bid") // ) // private Set<User> friendList = new HashSet<>(); // // public Set<User> getFriendList() { // return friendList; // } // // public void setFriendList(Set<User> friendList) { // this.friendList = friendList; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getSex() { // return sex; // } // // public void setSex(String sex) { // this.sex = sex; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getNick() { // return nick; // } // // public void setNick(String nick) { // this.nick = nick; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // // public String getPhone() { // return phone; // } // // public void setPhone(String phone) { // this.phone = phone; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getAvatar() { // return avatar; // } // // public void setAvatar(String avatar) { // this.avatar = avatar; // } // // // public String getSignInfo() { // return signInfo; // } // // public void setSignInfo(String signInfo) { // this.signInfo = signInfo; // } // } // Path: Server/src/main/java/com/easychat/service/UserService.java import com.easychat.model.dto.input.UserDTO; import com.easychat.model.dto.output.UserDetailDTO; import com.easychat.model.entity.User; package com.easychat.service; /** * Created by yonah on 15-10-18 */ public interface UserService { void addUser(UserDTO userDTO); User authenticate(UserDTO userDTO); void modifyUserInfo(String name,String json);
UserDetailDTO getUser(String name);
x-hansong/EasyChat
Server/src/main/java/com/easychat/controller/WSController.java
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // }
import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController {
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // } // Path: Server/src/main/java/com/easychat/controller/WSController.java import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController {
private UserService userService;
x-hansong/EasyChat
Server/src/main/java/com/easychat/controller/WSController.java
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // }
import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController { private UserService userService; private SimpMessagingTemplate simpMessagingTemplate; private static Logger logger = LoggerFactory.getLogger(GroupController.class); @Autowired public WSController(UserService userService, SimpMessagingTemplate simpMessagingTemplate) { this.userService = userService; this.simpMessagingTemplate = simpMessagingTemplate; } @MessageMapping("/chat")
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // } // Path: Server/src/main/java/com/easychat/controller/WSController.java import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController { private UserService userService; private SimpMessagingTemplate simpMessagingTemplate; private static Logger logger = LoggerFactory.getLogger(GroupController.class); @Autowired public WSController(UserService userService, SimpMessagingTemplate simpMessagingTemplate) { this.userService = userService; this.simpMessagingTemplate = simpMessagingTemplate; } @MessageMapping("/chat")
public void chat(Message message){
x-hansong/EasyChat
Server/src/main/java/com/easychat/controller/WSController.java
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // }
import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController { private UserService userService; private SimpMessagingTemplate simpMessagingTemplate; private static Logger logger = LoggerFactory.getLogger(GroupController.class); @Autowired public WSController(UserService userService, SimpMessagingTemplate simpMessagingTemplate) { this.userService = userService; this.simpMessagingTemplate = simpMessagingTemplate; } @MessageMapping("/chat") public void chat(Message message){ logger.debug(message.getContent()); simpMessagingTemplate.convertAndSend("/queue/channel/" + message.getToUser(),message); } @MessageMapping("/accept")
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // } // Path: Server/src/main/java/com/easychat/controller/WSController.java import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController { private UserService userService; private SimpMessagingTemplate simpMessagingTemplate; private static Logger logger = LoggerFactory.getLogger(GroupController.class); @Autowired public WSController(UserService userService, SimpMessagingTemplate simpMessagingTemplate) { this.userService = userService; this.simpMessagingTemplate = simpMessagingTemplate; } @MessageMapping("/chat") public void chat(Message message){ logger.debug(message.getContent()); simpMessagingTemplate.convertAndSend("/queue/channel/" + message.getToUser(),message); } @MessageMapping("/accept")
public void accept(AcceptInvitationMsg msg){
x-hansong/EasyChat
Server/src/main/java/com/easychat/controller/WSController.java
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // }
import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController { private UserService userService; private SimpMessagingTemplate simpMessagingTemplate; private static Logger logger = LoggerFactory.getLogger(GroupController.class); @Autowired public WSController(UserService userService, SimpMessagingTemplate simpMessagingTemplate) { this.userService = userService; this.simpMessagingTemplate = simpMessagingTemplate; } @MessageMapping("/chat") public void chat(Message message){ logger.debug(message.getContent()); simpMessagingTemplate.convertAndSend("/queue/channel/" + message.getToUser(),message); } @MessageMapping("/accept") public void accept(AcceptInvitationMsg msg){ userService.setFriendRelationship(msg.getToUser(), msg.getFromUser());
// Path: Server/src/main/java/com/easychat/model/msg/AcceptInvitationMsg.java // public class AcceptInvitationMsg { // private String fromUser; // private String toUser; // private String content; // private String type; // // public AcceptInvitationMsg() { // } // // public AcceptInvitationMsg(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // this.type = "ACCEPT_INVITATION"; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/CommandMsg.java // public class CommandMsg { // private String command; // private String type; // // public CommandMsg() { // } // // public CommandMsg(String command) { // this.type = "COMMAND"; // this.command = command; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // } // // Path: Server/src/main/java/com/easychat/model/msg/Message.java // public class Message { // private String fromUser; // private String toUser; // private String content; // // public String getToUser() { // return toUser; // } // // public void setToUser(String toUser) { // this.toUser = toUser; // } // // public String getFromUser() { // return fromUser; // } // // public void setFromUser(String fromUser) { // this.fromUser = fromUser; // } // // public Message(){ // // } // // public Message(String fromUser, String toUser, String content) { // this.fromUser = fromUser; // this.toUser = toUser; // this.content = content; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // } // // Path: Server/src/main/java/com/easychat/service/UserService.java // public interface UserService { // void addUser(UserDTO userDTO); // User authenticate(UserDTO userDTO); // void modifyUserInfo(String name,String json); // UserDetailDTO getUser(String name); // String getFriends(String name); // void deleteFriend(String userName,String friendName); // String getFriendInfo(String name,String friend_name); // String getStrangerInfo(String name,String stranger_name); // boolean setFriendRelationship(String aName, String bName); // } // Path: Server/src/main/java/com/easychat/controller/WSController.java import com.easychat.model.msg.AcceptInvitationMsg; import com.easychat.model.msg.CommandMsg; import com.easychat.model.msg.Message; import com.easychat.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; package com.easychat.controller; /** * Created by xhans on 2015/12/19. */ @Controller @RequestMapping("/") public class WSController { private UserService userService; private SimpMessagingTemplate simpMessagingTemplate; private static Logger logger = LoggerFactory.getLogger(GroupController.class); @Autowired public WSController(UserService userService, SimpMessagingTemplate simpMessagingTemplate) { this.userService = userService; this.simpMessagingTemplate = simpMessagingTemplate; } @MessageMapping("/chat") public void chat(Message message){ logger.debug(message.getContent()); simpMessagingTemplate.convertAndSend("/queue/channel/" + message.getToUser(),message); } @MessageMapping("/accept") public void accept(AcceptInvitationMsg msg){ userService.setFriendRelationship(msg.getToUser(), msg.getFromUser());
simpMessagingTemplate.convertAndSend("/queue/system/" + msg.getFromUser(), new CommandMsg("REFRESH_FRIENDLIST"));
x-hansong/EasyChat
Server/src/test/java/com/easychat/test/webserver/GroupControllerTest.java
// Path: Server/src/main/java/com/easychat/Server.java // @SpringBootApplication // public class Server { // public static void main(String[] args) { // SpringApplication.run(Server.class, args); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // }
import com.easychat.Server; import com.easychat.repository.GroupRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate;
package com.easychat.test.webserver; /** * Created by king on 2015/12/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Server.class) @WebIntegrationTest public class GroupControllerTest { private static final String URL = "http://localhost:8080/v1/groups"; private RestTemplate restTemplate = new TestRestTemplate(); @Autowired
// Path: Server/src/main/java/com/easychat/Server.java // @SpringBootApplication // public class Server { // public static void main(String[] args) { // SpringApplication.run(Server.class, args); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // } // Path: Server/src/test/java/com/easychat/test/webserver/GroupControllerTest.java import com.easychat.Server; import com.easychat.repository.GroupRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; package com.easychat.test.webserver; /** * Created by king on 2015/12/14. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Server.class) @WebIntegrationTest public class GroupControllerTest { private static final String URL = "http://localhost:8080/v1/groups"; private RestTemplate restTemplate = new TestRestTemplate(); @Autowired
private GroupRepository groupRepository;
x-hansong/EasyChat
Server/src/main/java/com/easychat/exception/GlobalControllerExceptionHandler.java
// Path: Server/src/main/java/com/easychat/model/error/ErrorInfo.java // public class ErrorInfo { // private String error; // private String description; // // public String getError() { // return error; // } // // public void setError(String error) { // this.error = error; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public ErrorInfo(String error, String description) { // this.error = error; // this.description = description; // } // }
import com.easychat.model.error.ErrorInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest;
package com.easychat.exception; /** * Created by yonah on 15-11-6. */ @ControllerAdvice public class GlobalControllerExceptionHandler { static Logger logger = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class); @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(value = NotFoundException.class) @ResponseBody
// Path: Server/src/main/java/com/easychat/model/error/ErrorInfo.java // public class ErrorInfo { // private String error; // private String description; // // public String getError() { // return error; // } // // public void setError(String error) { // this.error = error; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public ErrorInfo(String error, String description) { // this.error = error; // this.description = description; // } // } // Path: Server/src/main/java/com/easychat/exception/GlobalControllerExceptionHandler.java import com.easychat.model.error.ErrorInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; package com.easychat.exception; /** * Created by yonah on 15-11-6. */ @ControllerAdvice public class GlobalControllerExceptionHandler { static Logger logger = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class); @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(value = NotFoundException.class) @ResponseBody
public ErrorInfo handleNotFound(HttpServletRequest req, NotFoundException ex){
x-hansong/EasyChat
Server/src/main/java/com/easychat/utils/JsonUtils.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // }
import com.easychat.exception.BadRequestException; import com.easychat.model.error.ErrorType; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException;
package com.easychat.utils; /** * Created by yonah on 15-11-13. */ public class JsonUtils { /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class); private final static ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); } private JsonUtils() { } public static String encode(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (JsonMappingException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } return null; } /** * 将json string反序列化成对象 * * @param json * @param valueType * @return */
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // Path: Server/src/main/java/com/easychat/utils/JsonUtils.java import com.easychat.exception.BadRequestException; import com.easychat.model.error.ErrorType; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; package com.easychat.utils; /** * Created by yonah on 15-11-13. */ public class JsonUtils { /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class); private final static ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); } private JsonUtils() { } public static String encode(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (JsonMappingException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } return null; } /** * 将json string反序列化成对象 * * @param json * @param valueType * @return */
public static <T> T decode(String json, Class<T> valueType) throws BadRequestException {
x-hansong/EasyChat
Server/src/main/java/com/easychat/utils/JsonUtils.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // }
import com.easychat.exception.BadRequestException; import com.easychat.model.error.ErrorType; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException;
public static String encode(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (JsonMappingException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } return null; } /** * 将json string反序列化成对象 * * @param json * @param valueType * @return */ public static <T> T decode(String json, Class<T> valueType) throws BadRequestException { try { return objectMapper.readValue(json, valueType); } catch (JsonParseException e) { logger.error("decode(String, Class<T>)", e); } catch (JsonMappingException e) { logger.error("decode(String, Class<T>)", e); } catch (IOException e) { logger.error("decode(String, Class<T>)", e); }
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // Path: Server/src/main/java/com/easychat/utils/JsonUtils.java import com.easychat.exception.BadRequestException; import com.easychat.model.error.ErrorType; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; public static String encode(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (JsonMappingException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } catch (IOException e) { logger.error("encode(Object)", e); //$NON-NLS-1$ } return null; } /** * 将json string反序列化成对象 * * @param json * @param valueType * @return */ public static <T> T decode(String json, Class<T> valueType) throws BadRequestException { try { return objectMapper.readValue(json, valueType); } catch (JsonParseException e) { logger.error("decode(String, Class<T>)", e); } catch (JsonMappingException e) { logger.error("decode(String, Class<T>)", e); } catch (IOException e) { logger.error("decode(String, Class<T>)", e); }
throw new BadRequestException(ErrorType.ILLEGAL_ARGUMENT, "invalid json");
x-hansong/EasyChat
Server/src/main/java/com/easychat/service/impl/GroupServiceImpl.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRelationshipRepository.java // public interface GroupRelationshipRepository extends JpaRepository<GroupRelationship, Long>, GroupRelationshipRepositoryCustom { // List<GroupRelationship> findByGid(Long gid); // GroupRelationship findByGidAndUid(Long gid, Long uid); // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // } // // Path: Server/src/main/java/com/easychat/service/GroupService.java // public interface GroupService { // boolean exists(long gid); // String createGroup(String json); // String deleteGroup(long gid,long uid); // String updateGroupAvatarAndAnnouncement(long gid ,long uid ,String json); // String quitGroup(long gid, long uid ); // String inviteIntoGroup(long gid ,String json); // }
import com.easychat.exception.BadRequestException; import com.easychat.repository.GroupRelationshipRepository; import com.easychat.repository.GroupRepository; import com.easychat.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package com.easychat.service.impl; /** * Created by king on 2015/12/7. */ @Service public class GroupServiceImpl implements GroupService {
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRelationshipRepository.java // public interface GroupRelationshipRepository extends JpaRepository<GroupRelationship, Long>, GroupRelationshipRepositoryCustom { // List<GroupRelationship> findByGid(Long gid); // GroupRelationship findByGidAndUid(Long gid, Long uid); // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // } // // Path: Server/src/main/java/com/easychat/service/GroupService.java // public interface GroupService { // boolean exists(long gid); // String createGroup(String json); // String deleteGroup(long gid,long uid); // String updateGroupAvatarAndAnnouncement(long gid ,long uid ,String json); // String quitGroup(long gid, long uid ); // String inviteIntoGroup(long gid ,String json); // } // Path: Server/src/main/java/com/easychat/service/impl/GroupServiceImpl.java import com.easychat.exception.BadRequestException; import com.easychat.repository.GroupRelationshipRepository; import com.easychat.repository.GroupRepository; import com.easychat.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package com.easychat.service.impl; /** * Created by king on 2015/12/7. */ @Service public class GroupServiceImpl implements GroupService {
private GroupRepository groupRepository;
x-hansong/EasyChat
Server/src/main/java/com/easychat/service/impl/GroupServiceImpl.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRelationshipRepository.java // public interface GroupRelationshipRepository extends JpaRepository<GroupRelationship, Long>, GroupRelationshipRepositoryCustom { // List<GroupRelationship> findByGid(Long gid); // GroupRelationship findByGidAndUid(Long gid, Long uid); // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // } // // Path: Server/src/main/java/com/easychat/service/GroupService.java // public interface GroupService { // boolean exists(long gid); // String createGroup(String json); // String deleteGroup(long gid,long uid); // String updateGroupAvatarAndAnnouncement(long gid ,long uid ,String json); // String quitGroup(long gid, long uid ); // String inviteIntoGroup(long gid ,String json); // }
import com.easychat.exception.BadRequestException; import com.easychat.repository.GroupRelationshipRepository; import com.easychat.repository.GroupRepository; import com.easychat.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package com.easychat.service.impl; /** * Created by king on 2015/12/7. */ @Service public class GroupServiceImpl implements GroupService { private GroupRepository groupRepository;
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRelationshipRepository.java // public interface GroupRelationshipRepository extends JpaRepository<GroupRelationship, Long>, GroupRelationshipRepositoryCustom { // List<GroupRelationship> findByGid(Long gid); // GroupRelationship findByGidAndUid(Long gid, Long uid); // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // } // // Path: Server/src/main/java/com/easychat/service/GroupService.java // public interface GroupService { // boolean exists(long gid); // String createGroup(String json); // String deleteGroup(long gid,long uid); // String updateGroupAvatarAndAnnouncement(long gid ,long uid ,String json); // String quitGroup(long gid, long uid ); // String inviteIntoGroup(long gid ,String json); // } // Path: Server/src/main/java/com/easychat/service/impl/GroupServiceImpl.java import com.easychat.exception.BadRequestException; import com.easychat.repository.GroupRelationshipRepository; import com.easychat.repository.GroupRepository; import com.easychat.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package com.easychat.service.impl; /** * Created by king on 2015/12/7. */ @Service public class GroupServiceImpl implements GroupService { private GroupRepository groupRepository;
private GroupRelationshipRepository groupRelationshipRepository;
x-hansong/EasyChat
Server/src/main/java/com/easychat/service/impl/GroupServiceImpl.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRelationshipRepository.java // public interface GroupRelationshipRepository extends JpaRepository<GroupRelationship, Long>, GroupRelationshipRepositoryCustom { // List<GroupRelationship> findByGid(Long gid); // GroupRelationship findByGidAndUid(Long gid, Long uid); // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // } // // Path: Server/src/main/java/com/easychat/service/GroupService.java // public interface GroupService { // boolean exists(long gid); // String createGroup(String json); // String deleteGroup(long gid,long uid); // String updateGroupAvatarAndAnnouncement(long gid ,long uid ,String json); // String quitGroup(long gid, long uid ); // String inviteIntoGroup(long gid ,String json); // }
import com.easychat.exception.BadRequestException; import com.easychat.repository.GroupRelationshipRepository; import com.easychat.repository.GroupRepository; import com.easychat.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
package com.easychat.service.impl; /** * Created by king on 2015/12/7. */ @Service public class GroupServiceImpl implements GroupService { private GroupRepository groupRepository; private GroupRelationshipRepository groupRelationshipRepository; static Logger logger = LoggerFactory.getLogger(GroupServiceImpl.class); @Autowired public GroupServiceImpl(GroupRepository groupRepository,GroupRelationshipRepository groupRelationshipRepository){ this.groupRepository = groupRepository; this.groupRelationshipRepository = groupRelationshipRepository; } @Override public boolean exists(long gid) { return groupRepository.exists(gid); } @Override
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/repository/GroupRelationshipRepository.java // public interface GroupRelationshipRepository extends JpaRepository<GroupRelationship, Long>, GroupRelationshipRepositoryCustom { // List<GroupRelationship> findByGid(Long gid); // GroupRelationship findByGidAndUid(Long gid, Long uid); // } // // Path: Server/src/main/java/com/easychat/repository/GroupRepository.java // public interface GroupRepository extends JpaRepository<Group, Long> { // List<Group> findByName(String name); // // // } // // Path: Server/src/main/java/com/easychat/service/GroupService.java // public interface GroupService { // boolean exists(long gid); // String createGroup(String json); // String deleteGroup(long gid,long uid); // String updateGroupAvatarAndAnnouncement(long gid ,long uid ,String json); // String quitGroup(long gid, long uid ); // String inviteIntoGroup(long gid ,String json); // } // Path: Server/src/main/java/com/easychat/service/impl/GroupServiceImpl.java import com.easychat.exception.BadRequestException; import com.easychat.repository.GroupRelationshipRepository; import com.easychat.repository.GroupRepository; import com.easychat.service.GroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; package com.easychat.service.impl; /** * Created by king on 2015/12/7. */ @Service public class GroupServiceImpl implements GroupService { private GroupRepository groupRepository; private GroupRelationshipRepository groupRelationshipRepository; static Logger logger = LoggerFactory.getLogger(GroupServiceImpl.class); @Autowired public GroupServiceImpl(GroupRepository groupRepository,GroupRelationshipRepository groupRelationshipRepository){ this.groupRepository = groupRepository; this.groupRelationshipRepository = groupRelationshipRepository; } @Override public boolean exists(long gid) { return groupRepository.exists(gid); } @Override
public String createGroup(String json) throws BadRequestException {
x-hansong/EasyChat
Server/src/main/java/com/easychat/validator/UserDTOValidator.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // // Path: Server/src/main/java/com/easychat/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>{ // // User findByName(String name); // } // // Path: Server/src/main/java/com/easychat/utils/CommonUtils.java // public class CommonUtils { // // /** // * 生成token // * @return 生成一个UUID并返回 // */ // // public static String getUUID(){ // return UUID.randomUUID().toString(); // } // // /** // * 进行md5加密 // * @return 返回经过md5加密后的字符串 // */ // public static String md5(String password) { // try { // MessageDigest MD5 = MessageDigest.getInstance("MD5"); // MD5.update(password.getBytes()); // String pwd = new BigInteger(1, MD5.digest()).toString(16); // return pwd; // } catch (Exception e) { // e.printStackTrace(); // } // return password; // } // // /** * 验证Email // * * @param email email地址,格式:zhang@gmail.com,zhang@xxx.com.cn,xxx代表邮件服务商 // * 允许为"" // * * @return 验证成功返回true,验证失败返回false // * */ // public static boolean checkEmail(String email) { // if(email.equals("")) // return true; // else { // String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; // return Pattern.matches(regex, email); // } // } // /** // * 验证用户名 // * @return 用户名合法则返回true,否则返回false // */ // public static boolean checkName(String name){ // String regex="^[0-9a-zA-Z_]{6,10}$"; // return Pattern.matches(regex, name); // } // /** // * 验证密码 // * @return 密码合法则返回true,否则返回false // */ // public static boolean checkPassword(String password){ // String regex="^[0-9a-zA-Z]{6,10}$"; // return Pattern.matches(regex, password); // } // /** // * 验证手机号码 // * 允许为"" // */ // public static boolean checkPhone(String phone){ // if(phone.equals("")) // return true; // else { // String regex = "^1\\d{10}$"; // return Pattern.matches(regex, phone); // } // } // /** // * 验证性别 // */ // public static boolean checkSex(String sex) { // return true; // } // /** // * 验证昵称 // */ // public static boolean checkNick(String nick){ // String regex="^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,11}$"; // return Pattern.matches(regex,nick); // } // /** // * 验证个性签名 // */ // public static boolean checkSignInfo(String signInfo){ // if("".equals(signInfo)){ // return true; // } // else { // String regex = "^[a-zA-Z0-9,.?!,。?!\\u4e00-\\u9fa5]{1,140}$"; // return Pattern.matches(regex, signInfo); // } // } // }
import com.easychat.exception.BadRequestException; import com.easychat.model.dto.input.UserDTO; import com.easychat.model.error.ErrorType; import com.easychat.repository.UserRepository; import com.easychat.utils.CommonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.Validator;
package com.easychat.validator; /** * Created by xhans on 2016/1/28. */ public class UserDTOValidator implements Validator{ @Autowired
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // // Path: Server/src/main/java/com/easychat/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>{ // // User findByName(String name); // } // // Path: Server/src/main/java/com/easychat/utils/CommonUtils.java // public class CommonUtils { // // /** // * 生成token // * @return 生成一个UUID并返回 // */ // // public static String getUUID(){ // return UUID.randomUUID().toString(); // } // // /** // * 进行md5加密 // * @return 返回经过md5加密后的字符串 // */ // public static String md5(String password) { // try { // MessageDigest MD5 = MessageDigest.getInstance("MD5"); // MD5.update(password.getBytes()); // String pwd = new BigInteger(1, MD5.digest()).toString(16); // return pwd; // } catch (Exception e) { // e.printStackTrace(); // } // return password; // } // // /** * 验证Email // * * @param email email地址,格式:zhang@gmail.com,zhang@xxx.com.cn,xxx代表邮件服务商 // * 允许为"" // * * @return 验证成功返回true,验证失败返回false // * */ // public static boolean checkEmail(String email) { // if(email.equals("")) // return true; // else { // String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; // return Pattern.matches(regex, email); // } // } // /** // * 验证用户名 // * @return 用户名合法则返回true,否则返回false // */ // public static boolean checkName(String name){ // String regex="^[0-9a-zA-Z_]{6,10}$"; // return Pattern.matches(regex, name); // } // /** // * 验证密码 // * @return 密码合法则返回true,否则返回false // */ // public static boolean checkPassword(String password){ // String regex="^[0-9a-zA-Z]{6,10}$"; // return Pattern.matches(regex, password); // } // /** // * 验证手机号码 // * 允许为"" // */ // public static boolean checkPhone(String phone){ // if(phone.equals("")) // return true; // else { // String regex = "^1\\d{10}$"; // return Pattern.matches(regex, phone); // } // } // /** // * 验证性别 // */ // public static boolean checkSex(String sex) { // return true; // } // /** // * 验证昵称 // */ // public static boolean checkNick(String nick){ // String regex="^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,11}$"; // return Pattern.matches(regex,nick); // } // /** // * 验证个性签名 // */ // public static boolean checkSignInfo(String signInfo){ // if("".equals(signInfo)){ // return true; // } // else { // String regex = "^[a-zA-Z0-9,.?!,。?!\\u4e00-\\u9fa5]{1,140}$"; // return Pattern.matches(regex, signInfo); // } // } // } // Path: Server/src/main/java/com/easychat/validator/UserDTOValidator.java import com.easychat.exception.BadRequestException; import com.easychat.model.dto.input.UserDTO; import com.easychat.model.error.ErrorType; import com.easychat.repository.UserRepository; import com.easychat.utils.CommonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.Validator; package com.easychat.validator; /** * Created by xhans on 2016/1/28. */ public class UserDTOValidator implements Validator{ @Autowired
private UserRepository userRepository;
x-hansong/EasyChat
Server/src/main/java/com/easychat/validator/UserDTOValidator.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // // Path: Server/src/main/java/com/easychat/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>{ // // User findByName(String name); // } // // Path: Server/src/main/java/com/easychat/utils/CommonUtils.java // public class CommonUtils { // // /** // * 生成token // * @return 生成一个UUID并返回 // */ // // public static String getUUID(){ // return UUID.randomUUID().toString(); // } // // /** // * 进行md5加密 // * @return 返回经过md5加密后的字符串 // */ // public static String md5(String password) { // try { // MessageDigest MD5 = MessageDigest.getInstance("MD5"); // MD5.update(password.getBytes()); // String pwd = new BigInteger(1, MD5.digest()).toString(16); // return pwd; // } catch (Exception e) { // e.printStackTrace(); // } // return password; // } // // /** * 验证Email // * * @param email email地址,格式:zhang@gmail.com,zhang@xxx.com.cn,xxx代表邮件服务商 // * 允许为"" // * * @return 验证成功返回true,验证失败返回false // * */ // public static boolean checkEmail(String email) { // if(email.equals("")) // return true; // else { // String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; // return Pattern.matches(regex, email); // } // } // /** // * 验证用户名 // * @return 用户名合法则返回true,否则返回false // */ // public static boolean checkName(String name){ // String regex="^[0-9a-zA-Z_]{6,10}$"; // return Pattern.matches(regex, name); // } // /** // * 验证密码 // * @return 密码合法则返回true,否则返回false // */ // public static boolean checkPassword(String password){ // String regex="^[0-9a-zA-Z]{6,10}$"; // return Pattern.matches(regex, password); // } // /** // * 验证手机号码 // * 允许为"" // */ // public static boolean checkPhone(String phone){ // if(phone.equals("")) // return true; // else { // String regex = "^1\\d{10}$"; // return Pattern.matches(regex, phone); // } // } // /** // * 验证性别 // */ // public static boolean checkSex(String sex) { // return true; // } // /** // * 验证昵称 // */ // public static boolean checkNick(String nick){ // String regex="^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,11}$"; // return Pattern.matches(regex,nick); // } // /** // * 验证个性签名 // */ // public static boolean checkSignInfo(String signInfo){ // if("".equals(signInfo)){ // return true; // } // else { // String regex = "^[a-zA-Z0-9,.?!,。?!\\u4e00-\\u9fa5]{1,140}$"; // return Pattern.matches(regex, signInfo); // } // } // }
import com.easychat.exception.BadRequestException; import com.easychat.model.dto.input.UserDTO; import com.easychat.model.error.ErrorType; import com.easychat.repository.UserRepository; import com.easychat.utils.CommonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.Validator;
package com.easychat.validator; /** * Created by xhans on 2016/1/28. */ public class UserDTOValidator implements Validator{ @Autowired private UserRepository userRepository; @Override public boolean supports(Class<?> clazz) {
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // // Path: Server/src/main/java/com/easychat/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>{ // // User findByName(String name); // } // // Path: Server/src/main/java/com/easychat/utils/CommonUtils.java // public class CommonUtils { // // /** // * 生成token // * @return 生成一个UUID并返回 // */ // // public static String getUUID(){ // return UUID.randomUUID().toString(); // } // // /** // * 进行md5加密 // * @return 返回经过md5加密后的字符串 // */ // public static String md5(String password) { // try { // MessageDigest MD5 = MessageDigest.getInstance("MD5"); // MD5.update(password.getBytes()); // String pwd = new BigInteger(1, MD5.digest()).toString(16); // return pwd; // } catch (Exception e) { // e.printStackTrace(); // } // return password; // } // // /** * 验证Email // * * @param email email地址,格式:zhang@gmail.com,zhang@xxx.com.cn,xxx代表邮件服务商 // * 允许为"" // * * @return 验证成功返回true,验证失败返回false // * */ // public static boolean checkEmail(String email) { // if(email.equals("")) // return true; // else { // String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; // return Pattern.matches(regex, email); // } // } // /** // * 验证用户名 // * @return 用户名合法则返回true,否则返回false // */ // public static boolean checkName(String name){ // String regex="^[0-9a-zA-Z_]{6,10}$"; // return Pattern.matches(regex, name); // } // /** // * 验证密码 // * @return 密码合法则返回true,否则返回false // */ // public static boolean checkPassword(String password){ // String regex="^[0-9a-zA-Z]{6,10}$"; // return Pattern.matches(regex, password); // } // /** // * 验证手机号码 // * 允许为"" // */ // public static boolean checkPhone(String phone){ // if(phone.equals("")) // return true; // else { // String regex = "^1\\d{10}$"; // return Pattern.matches(regex, phone); // } // } // /** // * 验证性别 // */ // public static boolean checkSex(String sex) { // return true; // } // /** // * 验证昵称 // */ // public static boolean checkNick(String nick){ // String regex="^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,11}$"; // return Pattern.matches(regex,nick); // } // /** // * 验证个性签名 // */ // public static boolean checkSignInfo(String signInfo){ // if("".equals(signInfo)){ // return true; // } // else { // String regex = "^[a-zA-Z0-9,.?!,。?!\\u4e00-\\u9fa5]{1,140}$"; // return Pattern.matches(regex, signInfo); // } // } // } // Path: Server/src/main/java/com/easychat/validator/UserDTOValidator.java import com.easychat.exception.BadRequestException; import com.easychat.model.dto.input.UserDTO; import com.easychat.model.error.ErrorType; import com.easychat.repository.UserRepository; import com.easychat.utils.CommonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.Validator; package com.easychat.validator; /** * Created by xhans on 2016/1/28. */ public class UserDTOValidator implements Validator{ @Autowired private UserRepository userRepository; @Override public boolean supports(Class<?> clazz) {
return UserDTO.class.equals(clazz);//声明校验的类
x-hansong/EasyChat
Server/src/main/java/com/easychat/validator/UserDTOValidator.java
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // // Path: Server/src/main/java/com/easychat/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>{ // // User findByName(String name); // } // // Path: Server/src/main/java/com/easychat/utils/CommonUtils.java // public class CommonUtils { // // /** // * 生成token // * @return 生成一个UUID并返回 // */ // // public static String getUUID(){ // return UUID.randomUUID().toString(); // } // // /** // * 进行md5加密 // * @return 返回经过md5加密后的字符串 // */ // public static String md5(String password) { // try { // MessageDigest MD5 = MessageDigest.getInstance("MD5"); // MD5.update(password.getBytes()); // String pwd = new BigInteger(1, MD5.digest()).toString(16); // return pwd; // } catch (Exception e) { // e.printStackTrace(); // } // return password; // } // // /** * 验证Email // * * @param email email地址,格式:zhang@gmail.com,zhang@xxx.com.cn,xxx代表邮件服务商 // * 允许为"" // * * @return 验证成功返回true,验证失败返回false // * */ // public static boolean checkEmail(String email) { // if(email.equals("")) // return true; // else { // String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; // return Pattern.matches(regex, email); // } // } // /** // * 验证用户名 // * @return 用户名合法则返回true,否则返回false // */ // public static boolean checkName(String name){ // String regex="^[0-9a-zA-Z_]{6,10}$"; // return Pattern.matches(regex, name); // } // /** // * 验证密码 // * @return 密码合法则返回true,否则返回false // */ // public static boolean checkPassword(String password){ // String regex="^[0-9a-zA-Z]{6,10}$"; // return Pattern.matches(regex, password); // } // /** // * 验证手机号码 // * 允许为"" // */ // public static boolean checkPhone(String phone){ // if(phone.equals("")) // return true; // else { // String regex = "^1\\d{10}$"; // return Pattern.matches(regex, phone); // } // } // /** // * 验证性别 // */ // public static boolean checkSex(String sex) { // return true; // } // /** // * 验证昵称 // */ // public static boolean checkNick(String nick){ // String regex="^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,11}$"; // return Pattern.matches(regex,nick); // } // /** // * 验证个性签名 // */ // public static boolean checkSignInfo(String signInfo){ // if("".equals(signInfo)){ // return true; // } // else { // String regex = "^[a-zA-Z0-9,.?!,。?!\\u4e00-\\u9fa5]{1,140}$"; // return Pattern.matches(regex, signInfo); // } // } // }
import com.easychat.exception.BadRequestException; import com.easychat.model.dto.input.UserDTO; import com.easychat.model.error.ErrorType; import com.easychat.repository.UserRepository; import com.easychat.utils.CommonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.Validator;
package com.easychat.validator; /** * Created by xhans on 2016/1/28. */ public class UserDTOValidator implements Validator{ @Autowired private UserRepository userRepository; @Override public boolean supports(Class<?> clazz) { return UserDTO.class.equals(clazz);//声明校验的类 } @Override public void validate(Object target, Errors errors) { UserDTO userDTO = (UserDTO) target; String nameTest = userDTO.getName(); String passwordTest = userDTO.getPassword();
// Path: Server/src/main/java/com/easychat/exception/BadRequestException.java // public class BadRequestException extends BasicException{ // public BadRequestException(String error, String description) { // super(error, description); // } // } // // Path: Server/src/main/java/com/easychat/model/dto/input/UserDTO.java // public class UserDTO { // private String name; // // private String password; // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // } // // Path: Server/src/main/java/com/easychat/model/error/ErrorType.java // public final class ErrorType { // public static final String NO_ERROR = "no_error"; // public static final String INVALID_GRANT = "invalid_grant"; // public static final String SERVICE_RESOURCE_NOT_FOUND = "service_resource_not_found"; // public static final String DUPLICATE_UNIQUE_PROPERTY_EXISTS="duplicate_unique_property_exists"; // public static final String ILLEGAL_ARGUMENT="illegal_argument"; // public static final String AUTH_BAD_ACCESS_TOKEN="auth_bad_access_token"; // } // // Path: Server/src/main/java/com/easychat/repository/UserRepository.java // public interface UserRepository extends JpaRepository<User, Long>{ // // User findByName(String name); // } // // Path: Server/src/main/java/com/easychat/utils/CommonUtils.java // public class CommonUtils { // // /** // * 生成token // * @return 生成一个UUID并返回 // */ // // public static String getUUID(){ // return UUID.randomUUID().toString(); // } // // /** // * 进行md5加密 // * @return 返回经过md5加密后的字符串 // */ // public static String md5(String password) { // try { // MessageDigest MD5 = MessageDigest.getInstance("MD5"); // MD5.update(password.getBytes()); // String pwd = new BigInteger(1, MD5.digest()).toString(16); // return pwd; // } catch (Exception e) { // e.printStackTrace(); // } // return password; // } // // /** * 验证Email // * * @param email email地址,格式:zhang@gmail.com,zhang@xxx.com.cn,xxx代表邮件服务商 // * 允许为"" // * * @return 验证成功返回true,验证失败返回false // * */ // public static boolean checkEmail(String email) { // if(email.equals("")) // return true; // else { // String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; // return Pattern.matches(regex, email); // } // } // /** // * 验证用户名 // * @return 用户名合法则返回true,否则返回false // */ // public static boolean checkName(String name){ // String regex="^[0-9a-zA-Z_]{6,10}$"; // return Pattern.matches(regex, name); // } // /** // * 验证密码 // * @return 密码合法则返回true,否则返回false // */ // public static boolean checkPassword(String password){ // String regex="^[0-9a-zA-Z]{6,10}$"; // return Pattern.matches(regex, password); // } // /** // * 验证手机号码 // * 允许为"" // */ // public static boolean checkPhone(String phone){ // if(phone.equals("")) // return true; // else { // String regex = "^1\\d{10}$"; // return Pattern.matches(regex, phone); // } // } // /** // * 验证性别 // */ // public static boolean checkSex(String sex) { // return true; // } // /** // * 验证昵称 // */ // public static boolean checkNick(String nick){ // String regex="^[a-zA-Z0-9\\u4e00-\\u9fa5]{1,11}$"; // return Pattern.matches(regex,nick); // } // /** // * 验证个性签名 // */ // public static boolean checkSignInfo(String signInfo){ // if("".equals(signInfo)){ // return true; // } // else { // String regex = "^[a-zA-Z0-9,.?!,。?!\\u4e00-\\u9fa5]{1,140}$"; // return Pattern.matches(regex, signInfo); // } // } // } // Path: Server/src/main/java/com/easychat/validator/UserDTOValidator.java import com.easychat.exception.BadRequestException; import com.easychat.model.dto.input.UserDTO; import com.easychat.model.error.ErrorType; import com.easychat.repository.UserRepository; import com.easychat.utils.CommonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.Validator; package com.easychat.validator; /** * Created by xhans on 2016/1/28. */ public class UserDTOValidator implements Validator{ @Autowired private UserRepository userRepository; @Override public boolean supports(Class<?> clazz) { return UserDTO.class.equals(clazz);//声明校验的类 } @Override public void validate(Object target, Errors errors) { UserDTO userDTO = (UserDTO) target; String nameTest = userDTO.getName(); String passwordTest = userDTO.getPassword();
if (!CommonUtils.checkName(nameTest)
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/MT19937_64Random.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // }
import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readLong;
/* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * This is a 64-bit version of Mersenne Twister pseudorandom number generator. * <p> * <i> * References: M. Matsumoto and T. Nishimura, "Mersenne Twister: a * 623-dimensionally equidistributed uniform pseudorandom number generator". * ACM Transactions on Modeling and Computer Simulation 8. (Jan. 1998) 3--30. * </i> * <p> * <em> * This is a port of the * <a href="https://github.com/rabauke/trng4/blob/master/src/mt19937_64.hpp"> * trng::mt19937_64</a> PRNG class of the * <a href="https://github.com/rabauke/trng4/blob/master/doc/trng.pdf">TRNG</a> library created by Heiko * Bauke.</em> * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0 */ public class MT19937_64Random implements SplittableRandom { private static final int N = 312; private static final int M = 156; private static final long UM = 0xFFFFFFFF80000000L; // most significant bit private static final long LM = 0x7FFFFFFFL; // least significant 31 bits private static final long[] MAG01 = {0L, 0xB5026F5AA96619E9L}; /** * The internal state of this PRNG. */ private static final class State { int mti; final long[] mt = new long[N]; State(final byte[] seed) { setSeed(seed); } State(final long seed) { setSeed(seed); } void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); } for (mti = 0; mti < N; ++mti) {
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // Path: prngine/src/main/java/io/jenetics/prngine/MT19937_64Random.java import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readLong; /* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * This is a 64-bit version of Mersenne Twister pseudorandom number generator. * <p> * <i> * References: M. Matsumoto and T. Nishimura, "Mersenne Twister: a * 623-dimensionally equidistributed uniform pseudorandom number generator". * ACM Transactions on Modeling and Computer Simulation 8. (Jan. 1998) 3--30. * </i> * <p> * <em> * This is a port of the * <a href="https://github.com/rabauke/trng4/blob/master/src/mt19937_64.hpp"> * trng::mt19937_64</a> PRNG class of the * <a href="https://github.com/rabauke/trng4/blob/master/doc/trng.pdf">TRNG</a> library created by Heiko * Bauke.</em> * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0 */ public class MT19937_64Random implements SplittableRandom { private static final int N = 312; private static final int M = 156; private static final long UM = 0xFFFFFFFF80000000L; // most significant bit private static final long LM = 0x7FFFFFFFL; // least significant 31 bits private static final long[] MAG01 = {0L, 0xB5026F5AA96619E9L}; /** * The internal state of this PRNG. */ private static final class State { int mti; final long[] mt = new long[N]; State(final byte[] seed) { setSeed(seed); } State(final long seed) { setSeed(seed); } void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); } for (mti = 0; mti < N; ++mti) {
mt[mti] = readLong(seed, mti);
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/Seeds.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static byte[] toBytes(final int value) { // final byte[] bytes = new byte[4]; // bytes[0] = (byte)(value >>> 24); // bytes[1] = (byte)(value >>> 16); // bytes[2] = (byte)(value >>> 8); // bytes[3] = (byte) value; // return bytes; // }
import java.util.random.RandomGenerator; import static java.lang.Math.min; import static io.jenetics.prngine.Bytes.toBytes;
* @see #seed() * * @param length the length of the returned byte array. * @return a new <em>seed</em> byte array of the given length * @throws NegativeArraySizeException if the given length is smaller * than zero. */ public static byte[] seedBytes(final int length) { return seedBytes(new byte[length]); } /** * Fills the given {@code seedBytes} with the given {@code seed} value. If * the {@code length} is bigger than 8, the {@code seed} value is * <em>stretched</em> for filling the returned seed array. This method is * deterministic and doesn't increase the entropy of the input {@code seed}. * * @see #expandSeedToBytes(long, int) * * @param seed the seed value * @param seedBytes the resulting seeding byte array to fill * @return the given byte array, for method chaining. * @throws NullPointerException if the {@code seedBytes} array is * {@code null}. */ public static byte[] expandSeedToBytes(final long seed, final byte[] seedBytes) { long seedValue = seed; for (int i = 0, len = seedBytes.length; i < len;) { final int n = min(len - i, Long.SIZE/Byte.SIZE);
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static byte[] toBytes(final int value) { // final byte[] bytes = new byte[4]; // bytes[0] = (byte)(value >>> 24); // bytes[1] = (byte)(value >>> 16); // bytes[2] = (byte)(value >>> 8); // bytes[3] = (byte) value; // return bytes; // } // Path: prngine/src/main/java/io/jenetics/prngine/Seeds.java import java.util.random.RandomGenerator; import static java.lang.Math.min; import static io.jenetics.prngine.Bytes.toBytes; * @see #seed() * * @param length the length of the returned byte array. * @return a new <em>seed</em> byte array of the given length * @throws NegativeArraySizeException if the given length is smaller * than zero. */ public static byte[] seedBytes(final int length) { return seedBytes(new byte[length]); } /** * Fills the given {@code seedBytes} with the given {@code seed} value. If * the {@code length} is bigger than 8, the {@code seed} value is * <em>stretched</em> for filling the returned seed array. This method is * deterministic and doesn't increase the entropy of the input {@code seed}. * * @see #expandSeedToBytes(long, int) * * @param seed the seed value * @param seedBytes the resulting seeding byte array to fill * @return the given byte array, for method chaining. * @throws NullPointerException if the {@code seedBytes} array is * {@code null}. */ public static byte[] expandSeedToBytes(final long seed, final byte[] seedBytes) { long seedValue = seed; for (int i = 0, len = seedBytes.length; i < len;) { final int n = min(len - i, Long.SIZE/Byte.SIZE);
final byte[] bytes = toBytes(seedValue);
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/XOR64ShiftRandom.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // }
import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readLong; import java.util.List; import java.util.random.RandomGenerator;
public XOR64ShiftRandom(final byte[] seed) { this(Param.DEFAULT, seed); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and the * given seed. * * @param seed the seed of the PRNG */ public XOR64ShiftRandom(final long seed) { this(Param.DEFAULT, Seeds.expandSeedToBytes(seed, SEED_BYTES)); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and safe * seed. */ public XOR64ShiftRandom() { this(Param.DEFAULT, Seeds.seed()); } private void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // Path: prngine/src/main/java/io/jenetics/prngine/XOR64ShiftRandom.java import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readLong; import java.util.List; import java.util.random.RandomGenerator; public XOR64ShiftRandom(final byte[] seed) { this(Param.DEFAULT, seed); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and the * given seed. * * @param seed the seed of the PRNG */ public XOR64ShiftRandom(final long seed) { this(Param.DEFAULT, Seeds.expandSeedToBytes(seed, SEED_BYTES)); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and safe * seed. */ public XOR64ShiftRandom() { this(Param.DEFAULT, Seeds.seed()); } private void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
x = toSafeSeed(readLong(seed, 0));
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/LCG64ShiftRandom.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // // Path: prngine/src/main/java/io/jenetics/prngine/IntMath.java // static long log2Floor(final long x) { // return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); // }
import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readLong; import static io.jenetics.prngine.IntMath.log2Floor; import java.util.random.RandomGenerator;
/* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * This class implements a linear congruential PRNG with additional bit-shift * transition. * * <em> * This is a port of the * <a href="https://github.com/rabauke/trng4/blob/master/src/lcg64_shift.hpp"> * trng::lcg64_shift</a> PRNG class of the * <a href="http://numbercrunch.de/trng/">TRNG</a> library created by Heiko * Bauke.</em> * * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * final long a, b = <params> * long r = <seed> * * long nextLong() { * r = q*r + b; * * long t = r; * t ^= t >>> 17; * t ^= t << 31; * t ^= t >>> 8; * return t; * } * }</pre> * * <p> * <strong>Not that the base implementation of the {@code LCG64ShiftRandom} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @see <a href="https://github.com/rabauke/trng4/blob/master/doc/trng.pdf">TRNG</a> * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class LCG64ShiftRandom implements RandomGenerator.ArbitrarilyJumpableGenerator { /* ************************************************************************* * Parameter classes. * ************************************************************************/ /** * Parameter class for the {@code LCG64ShiftRandom} generator, for the * parameters <i>a</i> and <i>b</i> of the LC recursion * <i>r<sub>i+1</sub> = a · r<sub>i</sub> + b</i> mod <i>2<sup>64</sup></i>. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.1 * @version 2.0.0 * * @param a the LEcuyer parameter a * @param b the LEcuyer parameter b */ public static final record Param(long a, long b) { /** * The default PRNG parameters: a = 0xFBD19FBBC5C07FF5L; b = 1 */ public static final Param DEFAULT = new Param(0xFBD19FBBC5C07FF5L, 1L); /** * LEcuyer 1 parameters: a = 0x27BB2EE687B0B0FDL; b = 1 */ public static final Param LECUYER1 = new Param(0x27BB2EE687B0B0FDL, 1L); /** * LEcuyer 2 parameters: a = 0x2C6FE96EE78B6955L; b = 1 */ public static final Param LECUYER2 = new Param(0x2C6FE96EE78B6955L, 1L); /** * LEcuyer 3 parameters: a = 0x369DEA0F31A53F85L; b = 1 */ public static final Param LECUYER3 = new Param(0x369DEA0F31A53F85L, 1L); } /** * Represents the state of this random engine */ private final static class State { static final int SEED_BYTES = 8; long r; private State(final State state) { this.r = state.r; } State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // // Path: prngine/src/main/java/io/jenetics/prngine/IntMath.java // static long log2Floor(final long x) { // return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); // } // Path: prngine/src/main/java/io/jenetics/prngine/LCG64ShiftRandom.java import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readLong; import static io.jenetics.prngine.IntMath.log2Floor; import java.util.random.RandomGenerator; /* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * This class implements a linear congruential PRNG with additional bit-shift * transition. * * <em> * This is a port of the * <a href="https://github.com/rabauke/trng4/blob/master/src/lcg64_shift.hpp"> * trng::lcg64_shift</a> PRNG class of the * <a href="http://numbercrunch.de/trng/">TRNG</a> library created by Heiko * Bauke.</em> * * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * final long a, b = <params> * long r = <seed> * * long nextLong() { * r = q*r + b; * * long t = r; * t ^= t >>> 17; * t ^= t << 31; * t ^= t >>> 8; * return t; * } * }</pre> * * <p> * <strong>Not that the base implementation of the {@code LCG64ShiftRandom} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @see <a href="https://github.com/rabauke/trng4/blob/master/doc/trng.pdf">TRNG</a> * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class LCG64ShiftRandom implements RandomGenerator.ArbitrarilyJumpableGenerator { /* ************************************************************************* * Parameter classes. * ************************************************************************/ /** * Parameter class for the {@code LCG64ShiftRandom} generator, for the * parameters <i>a</i> and <i>b</i> of the LC recursion * <i>r<sub>i+1</sub> = a · r<sub>i</sub> + b</i> mod <i>2<sup>64</sup></i>. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.1 * @version 2.0.0 * * @param a the LEcuyer parameter a * @param b the LEcuyer parameter b */ public static final record Param(long a, long b) { /** * The default PRNG parameters: a = 0xFBD19FBBC5C07FF5L; b = 1 */ public static final Param DEFAULT = new Param(0xFBD19FBBC5C07FF5L, 1L); /** * LEcuyer 1 parameters: a = 0x27BB2EE687B0B0FDL; b = 1 */ public static final Param LECUYER1 = new Param(0x27BB2EE687B0B0FDL, 1L); /** * LEcuyer 2 parameters: a = 0x2C6FE96EE78B6955L; b = 1 */ public static final Param LECUYER2 = new Param(0x2C6FE96EE78B6955L, 1L); /** * LEcuyer 3 parameters: a = 0x369DEA0F31A53F85L; b = 1 */ public static final Param LECUYER3 = new Param(0x369DEA0F31A53F85L, 1L); } /** * Represents the state of this random engine */ private final static class State { static final int SEED_BYTES = 8; long r; private State(final State state) { this.r = state.r; } State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
r = readLong(seed, 0);
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/LCG64ShiftRandom.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // // Path: prngine/src/main/java/io/jenetics/prngine/IntMath.java // static long log2Floor(final long x) { // return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); // }
import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readLong; import static io.jenetics.prngine.IntMath.log2Floor; import java.util.random.RandomGenerator;
public static byte[] seedBytes() { return Seeds.seedBytes(SEED_BYTES); } /* ************************************************************************* * Some static helper methods ***************************************************************************/ /** * Compute prod(1+a^(2^i), i=0..l-1). */ private static long g(final int l, final long a) { long p = a; long res = 1; for (int i = 0; i < l; ++i) { res *= 1 + p; p *= p; } return res; } /** * Compute sum(a^i, i=0..s-1). */ private static long f(final long s, final long a) { long y = 0; if (s != 0) {
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // // Path: prngine/src/main/java/io/jenetics/prngine/IntMath.java // static long log2Floor(final long x) { // return Long.SIZE - 1 - Long.numberOfLeadingZeros(x); // } // Path: prngine/src/main/java/io/jenetics/prngine/LCG64ShiftRandom.java import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readLong; import static io.jenetics.prngine.IntMath.log2Floor; import java.util.random.RandomGenerator; public static byte[] seedBytes() { return Seeds.seedBytes(SEED_BYTES); } /* ************************************************************************* * Some static helper methods ***************************************************************************/ /** * Compute prod(1+a^(2^i), i=0..l-1). */ private static long g(final int l, final long a) { long p = a; long res = 1; for (int i = 0; i < l; ++i) { res *= 1 + p; p *= p; } return res; } /** * Compute sum(a^i, i=0..s-1). */ private static long f(final long s, final long a) { long y = 0; if (s != 0) {
long e = log2Floor(s);
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/KISS32Random.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // }
import java.util.Random; import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt;
/* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * Implementation of an simple PRNG as proposed in * <a href="http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf"> * Good Practice in (Pseudo) Random Number Generation for Bioinformatics * Applications</a> (JKISS32, page 3) by <em><a href="mailto:d.jones@cs.ucl.ac.uk"> * David Jones</a>, UCL Bioinformatics Group</em>. * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * private int x, y, z, w = <seed> * private int c = 0; * * int nextInt() { * int t; * y ^= y << 5; * y ^= y >>> 7; * y ^= y << 22; * * t = z + w + c; * z = w; * c = t >>> 31; * w = t & 2147483647; * x += 1411392427; * * return x + y + w; * } * }</pre> * * <p> * The period of this <i>PRNG</i> is &asymp; 2<sup>121</sup> * &asymp; 2.6&sdot;10<sup>36</sup> * * <p> * <strong>Not that the base implementation of the {@code KISS32Random} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class KISS32Random extends Random32 implements SplittableRandom { /** * The internal state of random engine. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ private static final class State { private static final int SEED_BYTES = 16; int x, y, z, w, c; State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // } // Path: prngine/src/main/java/io/jenetics/prngine/KISS32Random.java import java.util.Random; import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt; /* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * Implementation of an simple PRNG as proposed in * <a href="http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf"> * Good Practice in (Pseudo) Random Number Generation for Bioinformatics * Applications</a> (JKISS32, page 3) by <em><a href="mailto:d.jones@cs.ucl.ac.uk"> * David Jones</a>, UCL Bioinformatics Group</em>. * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * private int x, y, z, w = <seed> * private int c = 0; * * int nextInt() { * int t; * y ^= y << 5; * y ^= y >>> 7; * y ^= y << 22; * * t = z + w + c; * z = w; * c = t >>> 31; * w = t & 2147483647; * x += 1411392427; * * return x + y + w; * } * }</pre> * * <p> * The period of this <i>PRNG</i> is &asymp; 2<sup>121</sup> * &asymp; 2.6&sdot;10<sup>36</sup> * * <p> * <strong>Not that the base implementation of the {@code KISS32Random} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class KISS32Random extends Random32 implements SplittableRandom { /** * The internal state of random engine. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ private static final class State { private static final int SEED_BYTES = 16; int x, y, z, w, c; State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
x = readInt(seed, 0);
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/MT19937_32Random.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // }
import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt;
/* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * This is a 32-bit version of Mersenne Twister pseudorandom number generator. * <p> * <i> * References: M. Matsumoto and T. Nishimura, "Mersenne Twister: a * 623-dimensionally equidistributed uniform pseudorandom number generator". * ACM Transactions on Modeling and Computer Simulation 8. (Jan. 1998) 3--30. * </i> * <p> * <em> * This is a port of the * <a href="https://github.com/rabauke/trng4/blob/master/src/mt19937.hpp"> * trng::mt19937</a> PRNG class of the * <a href="https://github.com/rabauke/trng4/blob/master/doc/trng.pdf">TRNG</a> library created by Heiko * Bauke.</em> * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class MT19937_32Random extends Random32 implements SplittableRandom { private static final int N = 624; private static final int M = 397; private static final int UM = 0x80000000; // most significant bit private static final int LM = 0x7FFFFFFF; // least significant 31 bits private static final int[] MAG01 = {0, 0x9908b0df}; /** * The internal state of this PRNG. */ private static final class State { int mti = 0; int[] mt = new int[N]; State(final byte[] seed) { setSeed(seed); } State(final long seed) { setSeed(seed); } void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); } for (mti = 0; mti < N; ++mti) {
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // } // Path: prngine/src/main/java/io/jenetics/prngine/MT19937_32Random.java import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt; /* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * This is a 32-bit version of Mersenne Twister pseudorandom number generator. * <p> * <i> * References: M. Matsumoto and T. Nishimura, "Mersenne Twister: a * 623-dimensionally equidistributed uniform pseudorandom number generator". * ACM Transactions on Modeling and Computer Simulation 8. (Jan. 1998) 3--30. * </i> * <p> * <em> * This is a port of the * <a href="https://github.com/rabauke/trng4/blob/master/src/mt19937.hpp"> * trng::mt19937</a> PRNG class of the * <a href="https://github.com/rabauke/trng4/blob/master/doc/trng.pdf">TRNG</a> library created by Heiko * Bauke.</em> * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class MT19937_32Random extends Random32 implements SplittableRandom { private static final int N = 624; private static final int M = 397; private static final int UM = 0x80000000; // most significant bit private static final int LM = 0x7FFFFFFF; // least significant 31 bits private static final int[] MAG01 = {0, 0x9908b0df}; /** * The internal state of this PRNG. */ private static final class State { int mti = 0; int[] mt = new int[N]; State(final byte[] seed) { setSeed(seed); } State(final long seed) { setSeed(seed); } void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); } for (mti = 0; mti < N; ++mti) {
mt[mti] = readInt(seed, mti);
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/XOR32ShiftRandom.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // }
import java.util.List; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readInt;
public XOR32ShiftRandom(final byte[] seed) { this(Param.DEFAULT, seed); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and the * given seed. * * @param seed the seed of the PRNG */ public XOR32ShiftRandom(final long seed) { this(Param.DEFAULT, Seeds.expandSeedToBytes(seed, SEED_BYTES)); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and safe * seed. */ public XOR32ShiftRandom() { this(Param.DEFAULT, Seeds.seed()); } private void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // } // Path: prngine/src/main/java/io/jenetics/prngine/XOR32ShiftRandom.java import java.util.List; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static io.jenetics.prngine.Bytes.readInt; public XOR32ShiftRandom(final byte[] seed) { this(Param.DEFAULT, seed); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and the * given seed. * * @param seed the seed of the PRNG */ public XOR32ShiftRandom(final long seed) { this(Param.DEFAULT, Seeds.expandSeedToBytes(seed, SEED_BYTES)); } /** * Create a new PRNG instance with {@link Param#DEFAULT} parameter and safe * seed. */ public XOR32ShiftRandom() { this(Param.DEFAULT, Seeds.seed()); } private void setSeed(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
x = toSafeSeed(readInt(seed, 0));
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/KISS64Random.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // } // // Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // }
import java.util.random.RandomGenerator; import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt; import static io.jenetics.prngine.Bytes.readLong;
/* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * Implementation of an simple PRNG as proposed in * <a href="http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf"> * Good Practice in (Pseudo) Random Number Generation for Bioinformatics * Applications</a> (JKISS64, page 10) by <em><a href="mailto:d.jones@cs.ucl.ac.uk"> * David Jones</a>, UCL Bioinformatics Group</em>. * * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * private long x, y = <seed> * private int z1, c1, z2, c2 = <seed> * * long nextLong() { * x = 0x14ADA13ED78492ADL*x + 123456789; * * y ^= y << 21; * y ^= y >>> 17; * y ^= y << 30; * * long t = 4294584393L*_z1 + _c1; * c1 = (int)(t >> 32); * z1 = (int)t; * * t = 4246477509L*z2 + c2; * c2 = (int)(t >> 32); * z2 = (int)t; * * return x + y + z1 + ((long)z2 << 32); * } * }</pre> * * <p> * The period of this <i>PRNG</i> is &asymp; 2<sup>250</sup> * &asymp; 1.8&sdot;10<sup>75</sup> * * <p> * <strong>Not that the base implementation of the {@code KISS64Random} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class KISS64Random implements SplittableRandom { /** * The internal state of this PRNG. */ private static final class State { static final int SEED_BYTES = 32; long x, y; int z1, c1, z2, c2; State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // } // // Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // Path: prngine/src/main/java/io/jenetics/prngine/KISS64Random.java import java.util.random.RandomGenerator; import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt; import static io.jenetics.prngine.Bytes.readLong; /* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * Implementation of an simple PRNG as proposed in * <a href="http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf"> * Good Practice in (Pseudo) Random Number Generation for Bioinformatics * Applications</a> (JKISS64, page 10) by <em><a href="mailto:d.jones@cs.ucl.ac.uk"> * David Jones</a>, UCL Bioinformatics Group</em>. * * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * private long x, y = <seed> * private int z1, c1, z2, c2 = <seed> * * long nextLong() { * x = 0x14ADA13ED78492ADL*x + 123456789; * * y ^= y << 21; * y ^= y >>> 17; * y ^= y << 30; * * long t = 4294584393L*_z1 + _c1; * c1 = (int)(t >> 32); * z1 = (int)t; * * t = 4246477509L*z2 + c2; * c2 = (int)(t >> 32); * z2 = (int)t; * * return x + y + z1 + ((long)z2 << 32); * } * }</pre> * * <p> * The period of this <i>PRNG</i> is &asymp; 2<sup>250</sup> * &asymp; 1.8&sdot;10<sup>75</sup> * * <p> * <strong>Not that the base implementation of the {@code KISS64Random} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class KISS64Random implements SplittableRandom { /** * The internal state of this PRNG. */ private static final class State { static final int SEED_BYTES = 32; long x, y; int z1, c1, z2, c2; State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); }
x = readLong(seed, 0);
jenetics/prngine
prngine/src/main/java/io/jenetics/prngine/KISS64Random.java
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // } // // Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // }
import java.util.random.RandomGenerator; import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt; import static io.jenetics.prngine.Bytes.readLong;
/* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * Implementation of an simple PRNG as proposed in * <a href="http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf"> * Good Practice in (Pseudo) Random Number Generation for Bioinformatics * Applications</a> (JKISS64, page 10) by <em><a href="mailto:d.jones@cs.ucl.ac.uk"> * David Jones</a>, UCL Bioinformatics Group</em>. * * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * private long x, y = <seed> * private int z1, c1, z2, c2 = <seed> * * long nextLong() { * x = 0x14ADA13ED78492ADL*x + 123456789; * * y ^= y << 21; * y ^= y >>> 17; * y ^= y << 30; * * long t = 4294584393L*_z1 + _c1; * c1 = (int)(t >> 32); * z1 = (int)t; * * t = 4246477509L*z2 + c2; * c2 = (int)(t >> 32); * z2 = (int)t; * * return x + y + z1 + ((long)z2 << 32); * } * }</pre> * * <p> * The period of this <i>PRNG</i> is &asymp; 2<sup>250</sup> * &asymp; 1.8&sdot;10<sup>75</sup> * * <p> * <strong>Not that the base implementation of the {@code KISS64Random} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class KISS64Random implements SplittableRandom { /** * The internal state of this PRNG. */ private static final class State { static final int SEED_BYTES = 32; long x, y; int z1, c1, z2, c2; State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); } x = readLong(seed, 0); y = readLong(seed, 1);
// Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static int readInt(final byte[] bytes, final int index) { // final int offset = index*Integer.BYTES; // if (offset + Integer.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read int value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((bytes[offset ] & 255) << 24) + // ((bytes[offset + 1] & 255) << 16) + // ((bytes[offset + 2] & 255) << 8) + // ((bytes[offset + 3] & 255)); // } // // Path: prngine/src/main/java/io/jenetics/prngine/Bytes.java // static long readLong(final byte[] bytes, final int index) { // final int offset = index*Long.BYTES; // if (offset + Long.BYTES > bytes.length) { // throw new IndexOutOfBoundsException(format( // "Not enough data to read long value (index=%d, bytes=%d).", // index, bytes.length // )); // } // // return // ((long)(bytes[offset ] & 255) << 56) + // ((long)(bytes[offset + 1] & 255) << 48) + // ((long)(bytes[offset + 2] & 255) << 40) + // ((long)(bytes[offset + 3] & 255) << 32) + // ((long)(bytes[offset + 4] & 255) << 24) + // ((bytes[offset + 5] & 255) << 16) + // ((bytes[offset + 6] & 255) << 8) + // (bytes[offset + 7] & 255); // } // Path: prngine/src/main/java/io/jenetics/prngine/KISS64Random.java import java.util.random.RandomGenerator; import static java.lang.String.format; import static io.jenetics.prngine.Bytes.readInt; import static io.jenetics.prngine.Bytes.readLong; /* * PRNGine - Java PRNG Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com) */ package io.jenetics.prngine; /** * Implementation of an simple PRNG as proposed in * <a href="http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf"> * Good Practice in (Pseudo) Random Number Generation for Bioinformatics * Applications</a> (JKISS64, page 10) by <em><a href="mailto:d.jones@cs.ucl.ac.uk"> * David Jones</a>, UCL Bioinformatics Group</em>. * * <p> * The following listing shows the actual PRNG implementation. * <pre>{@code * private long x, y = <seed> * private int z1, c1, z2, c2 = <seed> * * long nextLong() { * x = 0x14ADA13ED78492ADL*x + 123456789; * * y ^= y << 21; * y ^= y >>> 17; * y ^= y << 30; * * long t = 4294584393L*_z1 + _c1; * c1 = (int)(t >> 32); * z1 = (int)t; * * t = 4246477509L*z2 + c2; * c2 = (int)(t >> 32); * z2 = (int)t; * * return x + y + z1 + ((long)z2 << 32); * } * }</pre> * * <p> * The period of this <i>PRNG</i> is &asymp; 2<sup>250</sup> * &asymp; 1.8&sdot;10<sup>75</sup> * * <p> * <strong>Not that the base implementation of the {@code KISS64Random} * class is not thread-safe.</strong> If multiple threads requests random * numbers from this class, it <i>must</i> be synchronized externally. * * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a> * @since 1.0 * @version 2.0.0 */ public class KISS64Random implements SplittableRandom { /** * The internal state of this PRNG. */ private static final class State { static final int SEED_BYTES = 32; long x, y; int z1, c1, z2, c2; State(final byte[] seed) { if (seed.length < SEED_BYTES) { throw new IllegalArgumentException(format( "Required %d seed bytes, but got %d.", SEED_BYTES, seed.length )); } x = readLong(seed, 0); y = readLong(seed, 1);
z1 = readInt(seed, 4);
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SimpleVertexMemory.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // }
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SimpleVertexMemory extends AbstractVertexMemory { private final Map<Object, Map<String, Object>> memory;
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SimpleVertexMemory.java import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class SimpleVertexMemory extends AbstractVertexMemory { private final Map<Object, Map<String, Object>> memory;
public SimpleVertexMemory(final GraphComputer.Isolation isolation) {
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgramTest extends TestCase { public void testWeightedPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); WeightedPageRankProgram program = WeightedPageRankProgram.create().vertexCount(6).edgeWeightFunction(WeightedPageRankProgram.getEdgeWeightPropertyFunction("weight")).build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgramTest extends TestCase { public void testWeightedPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); WeightedPageRankProgram program = WeightedPageRankProgram.create().vertexCount(6).edgeWeightFunction(WeightedPageRankProgram.getEdgeWeightPropertyFunction("weight")).build();
SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgramTest extends TestCase { public void testWeightedPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); WeightedPageRankProgram program = WeightedPageRankProgram.create().vertexCount(6).edgeWeightFunction(WeightedPageRankProgram.getEdgeWeightPropertyFunction("weight")).build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgramTest extends TestCase { public void testWeightedPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); WeightedPageRankProgram program = WeightedPageRankProgram.create().vertexCount(6).edgeWeightFunction(WeightedPageRankProgram.getEdgeWeightPropertyFunction("weight")).build();
SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgramTest extends TestCase { public void testWeightedPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); WeightedPageRankProgram program = WeightedPageRankProgram.create().vertexCount(6).edgeWeightFunction(WeightedPageRankProgram.getEdgeWeightPropertyFunction("weight")).build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/WeightedPageRankProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class WeightedPageRankProgramTest extends TestCase { public void testWeightedPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); WeightedPageRankProgram program = WeightedPageRankProgram.create().vertexCount(6).edgeWeightFunction(WeightedPageRankProgram.getEdgeWeightPropertyFunction("weight")).build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
VertexMemory results = computer.getVertexMemory();
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/swarm/Particle.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // }
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import java.io.Serializable; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.swarm; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public interface Particle extends Serializable { public Map<String, VertexProgram.KeyType> getComputeKeys();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/swarm/Particle.java import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import java.io.Serializable; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.swarm; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public interface Particle extends Serializable { public Map<String, VertexProgram.KeyType> getComputeKeys();
public void execute(Vertex vertex, GraphMemory graphMemory, Long count, Map<Particle, Long> newParticles);
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/paths/ShortestPathProgram.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // }
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.paths; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ShortestPathProgram extends AbstractVertexProgram { private VertexQueryBuilder incomingQuery; private int diameter = 10; public static final String DEAD_PATHS = ShortestPathProgram.class.getName() + ".deadPaths"; public static final String LIVE_PATHS = ShortestPathProgram.class.getName() + ".livePaths";
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/AbstractVertexProgram.java // public abstract class AbstractVertexProgram implements VertexProgram { // // protected final Map<String, KeyType> computeKeys = new HashMap<String, KeyType>(); // // public Map<String, KeyType> getComputeKeys() { // return computeKeys; // } // // public void setup(final GraphMemory graphMemory) { // // } // // public String toString() { // return this.getClass().getSimpleName() + "[" + computeKeys.keySet() + "]"; // } // } // // Path: src/main/java/com/tinkerpop/furnace/util/VertexQueryBuilder.java // public class VertexQueryBuilder extends DefaultVertexQuery { // // public VertexQueryBuilder() { // super(null); // } // // public VertexQueryBuilder has(final String key) { // super.has(key); // return this; // } // // public VertexQueryBuilder hasNot(final String key) { // super.hasNot(key); // return this; // } // // public VertexQueryBuilder has(final String key, final Object value) { // super.has(key, value); // return this; // } // // public VertexQueryBuilder hasNot(final String key, final Object value) { // super.hasNot(key, value); // return this; // } // // @Deprecated // public <T extends Comparable<T>> VertexQueryBuilder has(final String key, final T value, final Query.Compare compare) { // return this.has(key, compare, value); // } // // public VertexQueryBuilder has(final String key, final Predicate compare, final Object value) { // super.has(key, compare, value); // return this; // } // // public <T extends Comparable<?>> VertexQueryBuilder interval(final String key, final T startValue, final T endValue) { // super.interval(key, startValue, endValue); // return this; // } // // public VertexQueryBuilder direction(final Direction direction) { // super.direction(direction); // return this; // } // // public VertexQueryBuilder labels(final String... labels) { // super.labels(labels); // return this; // } // // public VertexQueryBuilder limit(final int limit) { // super.limit(limit); // return this; // } // // public Iterable<Edge> edges() { // throw new UnsupportedOperationException(); // } // // public Iterable<Vertex> vertices() { // throw new UnsupportedOperationException(); // } // // public Object vertexIds() { // throw new UnsupportedOperationException(); // } // // public long count() { // throw new UnsupportedOperationException(); // } // // public VertexQuery build(final Vertex vertex) { // VertexQuery query = vertex.query(); // for (final HasContainer hasContainer : this.hasContainers) { // query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value); // } // return query.limit(this.limit).labels(this.labels).direction(this.direction); // } // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/paths/ShortestPathProgram.java import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.programs.AbstractVertexProgram; import com.tinkerpop.furnace.util.VertexQueryBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.paths; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class ShortestPathProgram extends AbstractVertexProgram { private VertexQueryBuilder incomingQuery; private int diameter = 10; public static final String DEAD_PATHS = ShortestPathProgram.class.getName() + ".deadPaths"; public static final String LIVE_PATHS = ShortestPathProgram.class.getName() + ".livePaths";
public void execute(final Vertex vertex, final GraphMemory graphMemory) {
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgramTest extends TestCase { public void testPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PageRankProgram program = PageRankProgram.create().vertexCount(6).iterations(3).build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgramTest extends TestCase { public void testPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PageRankProgram program = PageRankProgram.create().vertexCount(6).iterations(3).build();
SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgramTest extends TestCase { public void testPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PageRankProgram program = PageRankProgram.create().vertexCount(6).iterations(3).build();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgramTest extends TestCase { public void testPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PageRankProgram program = PageRankProgram.create().vertexCount(6).iterations(3).build();
SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP);
tinkerpop/furnace
src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgramTest.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // }
import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map;
package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgramTest extends TestCase { public void testPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PageRankProgram program = PageRankProgram.create().vertexCount(6).iterations(3).build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/SerialGraphComputer.java // public class SerialGraphComputer extends AbstractGraphComputer { // // public SerialGraphComputer(final Graph graph, final VertexProgram vertexProgram, final Isolation isolation) { // super(graph, vertexProgram, new SimpleGraphMemory(), new SimpleVertexMemory(isolation), isolation); // } // // public void execute() { // final long time = System.currentTimeMillis(); // this.vertexMemory.setComputeKeys(this.vertexProgram.getComputeKeys()); // this.vertexProgram.setup(this.graphMemory); // // final CoreShellVertex coreShellVertex = new CoreShellVertex(this.vertexMemory); // // Preconditions.checkArgument(this.graph.getFeatures().supportsVertexIteration); // // boolean done = false; // while (!done) { // for (final Vertex vertex : this.graph.getVertices()) { // coreShellVertex.setBaseVertex(vertex); // this.vertexProgram.execute(coreShellVertex, this.graphMemory); // } // this.vertexMemory.completeIteration(); // this.graphMemory.incrIteration(); // done = this.vertexProgram.terminate(this.graphMemory); // } // // this.graphMemory.setRuntime(System.currentTimeMillis() - time); // } // } // Path: src/test/java/com/tinkerpop/furnace/algorithms/vertexcentric/programs/ranking/PageRankProgramTest.java import com.google.common.collect.ImmutableSortedMap; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.impls.tg.TinkerGraphFactory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.computers.SerialGraphComputer; import junit.framework.TestCase; import java.util.Comparator; import java.util.HashMap; import java.util.Map; package com.tinkerpop.furnace.algorithms.vertexcentric.programs.ranking; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class PageRankProgramTest extends TestCase { public void testPageRankProgram() throws Exception { Graph graph = TinkerGraphFactory.createTinkerGraph(); //Graph graph = new TinkerGraph(); //GraphMLReader.inputGraph(graph, "/Users/marko/software/tinkerpop/gremlin/data/graph-example-2.xml"); PageRankProgram program = PageRankProgram.create().vertexCount(6).iterations(3).build(); SerialGraphComputer computer = new SerialGraphComputer(graph, program, GraphComputer.Isolation.BSP); computer.execute();
VertexMemory results = computer.getVertexMemory();
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph;
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph;
protected VertexProgram vertexProgram;
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram;
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram;
protected GraphSystemMemory graphMemory;
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram; protected GraphSystemMemory graphMemory;
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram; protected GraphSystemMemory graphMemory;
protected VertexSystemMemory vertexMemory;
tinkerpop/furnace
src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // }
import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory;
package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram; protected GraphSystemMemory graphMemory; protected VertexSystemMemory vertexMemory; protected Isolation isolation; public AbstractGraphComputer(final Graph graph, final VertexProgram vertexProgram, final GraphSystemMemory graphMemory, final VertexSystemMemory vertexMemory, final Isolation isolation) { this.graph = graph; this.vertexProgram = vertexProgram; this.graphMemory = graphMemory; this.vertexMemory = vertexMemory; this.isolation = isolation; }
// Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphComputer.java // public interface GraphComputer { // // public enum Isolation { // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are only visible after the round is complete. // */ // BSP, // /** // * Computations are carried out in a bulk synchronous manner. // * The results of a vertex property update are visible before the end of the round. // */ // DIRTY_BSP // } // // /** // * Execute the GraphComputer's VertexProgram against the GraphComputer's graph. // * The GraphComputer must have reference to a VertexProgram and Graph. // * The typical flow of execution is: // * 1. Set up the VertexMemory as necessary given the VertexProgram (e.g. set compute keys). // * 2. Set up the GraphMemory as necessary given the VertexProgram. // * 3. Execute the VertexProgram // */ // public void execute(); // // /** // * Get the VertexSystemMemory cast as a VertexMemory to hide system specific methods. // * // * @return the GraphComputer's VertexMemory // */ // public VertexMemory getVertexMemory(); // // /** // * Get the GraphSystemMemory cast as a GraphMemory to hide system specific methods. // * // * @return the GraphComputer's GraphMemory // */ // public GraphMemory getGraphMemory(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphMemory.java // public interface GraphMemory { // // public <R> R get(final String key); // // public void setIfAbsent(String key, Object value); // // public long increment(String key, long delta); // // public long decrement(String key, long delta); // // public int getIteration(); // // public long getRuntime(); // // public boolean isInitialIteration(); // // /*public void min(String key, double value); // // public void max(String key, double value); // // public void avg(String key, double value); // // public <V> void update(String key, Function<V, V> update, V defaultValue);*/ // // // public Map<String, Object> getCurrentState(); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/GraphSystemMemory.java // public interface GraphSystemMemory extends GraphMemory { // // public void incrIteration(); // // public void setRuntime(final long runtime); // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexMemory.java // public interface VertexMemory { // // public void setProperty(Vertex vertex, String key, Object value); // // public <T> T getProperty(Vertex vertex, String key); // // public <T> T removeProperty(Vertex vertex, String key); // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexProgram.java // public interface VertexProgram extends Serializable { // // public enum KeyType { // VARIABLE, // CONSTANT // } // // /** // * The method is called at the beginning of the computation. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // */ // public void setup(GraphMemory graphMemory); // // /** // * This method denotes the main body of computation. // * // * @param vertex the vertex to execute the VertexProgram on // * @param graphMemory the shared state between all vertices in the computation // */ // public void execute(Vertex vertex, GraphMemory graphMemory); // // /** // * The method is called at the end of a round to determine if the computation is complete. // * The method is global to the GraphComputer and as such, is not called for each vertex. // * // * @param graphMemory The global GraphMemory of the GraphComputer // * @return whether or not to halt the computation // */ // public boolean terminate(GraphMemory graphMemory); // // public Map<String, KeyType> getComputeKeys(); // // // } // // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/VertexSystemMemory.java // public interface VertexSystemMemory extends VertexMemory { // // public boolean isComputeKey(String key); // // public void completeIteration(); // // public void setComputeKeys(final Map<String, VertexProgram.KeyType> computeKeys); // // } // Path: src/main/java/com/tinkerpop/furnace/algorithms/vertexcentric/computers/AbstractGraphComputer.java import com.tinkerpop.blueprints.Graph; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphComputer; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.GraphSystemMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexMemory; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexProgram; import com.tinkerpop.furnace.algorithms.vertexcentric.VertexSystemMemory; package com.tinkerpop.furnace.algorithms.vertexcentric.computers; /** * AbstractGraphComputer provides the requisite fields/methods necessary for a GraphComputer. * This is a helper class that reduces the verbosity of a fully-written GraphComputer implementation. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public abstract class AbstractGraphComputer implements GraphComputer { protected final Graph graph; protected VertexProgram vertexProgram; protected GraphSystemMemory graphMemory; protected VertexSystemMemory vertexMemory; protected Isolation isolation; public AbstractGraphComputer(final Graph graph, final VertexProgram vertexProgram, final GraphSystemMemory graphMemory, final VertexSystemMemory vertexMemory, final Isolation isolation) { this.graph = graph; this.vertexProgram = vertexProgram; this.graphMemory = graphMemory; this.vertexMemory = vertexMemory; this.isolation = isolation; }
public VertexMemory getVertexMemory() {