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
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util;
*/ public EventHandlerGroup<T> then(final EventHandler<T>... handlers) { return handleEventsWith(handlers); } /** * Set up batch handlers to handleEventException events from the ring buffer. These handlers will only process events * after every {@link EventProcessor} in this group has processed the event. * * <p>This method is generally used as part of a chain. For example if the handler <code>A</code> must * process events before handler <code>B</code>:</p> * * <pre><code>dw.after(A).handleEventsWith(B);</code></pre> * * @param handlers the batch handlers that will process events. * @return a {@link EventHandlerGroup} that can be used to set up a event processor barrier over the created event processors. */ public EventHandlerGroup<T> handleEventsWith(final EventHandler<T>... handlers) { return disruptor.createEventProcessors(eventProcessors, handlers); } /** * Create a dependency barrier for the processors in this group. * This allows custom event processors to have dependencies on * {@link com.lmax.disruptor.BatchEventProcessor}s created by the disruptor. * * @return a {@link SequenceBarrier} including all the processors in this group. */
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util; */ public EventHandlerGroup<T> then(final EventHandler<T>... handlers) { return handleEventsWith(handlers); } /** * Set up batch handlers to handleEventException events from the ring buffer. These handlers will only process events * after every {@link EventProcessor} in this group has processed the event. * * <p>This method is generally used as part of a chain. For example if the handler <code>A</code> must * process events before handler <code>B</code>:</p> * * <pre><code>dw.after(A).handleEventsWith(B);</code></pre> * * @param handlers the batch handlers that will process events. * @return a {@link EventHandlerGroup} that can be used to set up a event processor barrier over the created event processors. */ public EventHandlerGroup<T> handleEventsWith(final EventHandler<T>... handlers) { return disruptor.createEventProcessors(eventProcessors, handlers); } /** * Create a dependency barrier for the processors in this group. * This allows custom event processors to have dependencies on * {@link com.lmax.disruptor.BatchEventProcessor}s created by the disruptor. * * @return a {@link SequenceBarrier} including all the processors in this group. */
public SequenceBarrier asSequenceBarrier()
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util;
{ return handleEventsWith(handlers); } /** * Set up batch handlers to handleEventException events from the ring buffer. These handlers will only process events * after every {@link EventProcessor} in this group has processed the event. * * <p>This method is generally used as part of a chain. For example if the handler <code>A</code> must * process events before handler <code>B</code>:</p> * * <pre><code>dw.after(A).handleEventsWith(B);</code></pre> * * @param handlers the batch handlers that will process events. * @return a {@link EventHandlerGroup} that can be used to set up a event processor barrier over the created event processors. */ public EventHandlerGroup<T> handleEventsWith(final EventHandler<T>... handlers) { return disruptor.createEventProcessors(eventProcessors, handlers); } /** * Create a dependency barrier for the processors in this group. * This allows custom event processors to have dependencies on * {@link com.lmax.disruptor.BatchEventProcessor}s created by the disruptor. * * @return a {@link SequenceBarrier} including all the processors in this group. */ public SequenceBarrier asSequenceBarrier() {
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/dsl/EventHandlerGroup.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.util.Util; { return handleEventsWith(handlers); } /** * Set up batch handlers to handleEventException events from the ring buffer. These handlers will only process events * after every {@link EventProcessor} in this group has processed the event. * * <p>This method is generally used as part of a chain. For example if the handler <code>A</code> must * process events before handler <code>B</code>:</p> * * <pre><code>dw.after(A).handleEventsWith(B);</code></pre> * * @param handlers the batch handlers that will process events. * @return a {@link EventHandlerGroup} that can be used to set up a event processor barrier over the created event processors. */ public EventHandlerGroup<T> handleEventsWith(final EventHandler<T>... handlers) { return disruptor.createEventProcessors(eventProcessors, handlers); } /** * Create a dependency barrier for the processors in this group. * This allows custom event processors to have dependencies on * {@link com.lmax.disruptor.BatchEventProcessor}s created by the disruptor. * * @return a {@link SequenceBarrier} including all the processors in this group. */ public SequenceBarrier asSequenceBarrier() {
return disruptor.getRingBuffer().newBarrier(Util.getSequencesFor(eventProcessors));
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/OnePublisherToThreeProcessorDiamondThroughputTest.java
// Path: src/performance/java/com/lmax/disruptor/support/FizzBuzzEvent.java // public final class FizzBuzzEvent // { // private boolean fizz = false; // private boolean buzz = false; // private long value = 0; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // fizz = false; // buzz = false; // this.value = value; // } // // public boolean isFizz() // { // return fizz; // } // // public void setFizz(final boolean fizz) // { // this.fizz = fizz; // } // // public boolean isBuzz() // { // return buzz; // } // // public void setBuzz(final boolean buzz) // { // this.buzz = buzz; // } // // public final static EventFactory<FizzBuzzEvent> EVENT_FACTORY = new EventFactory<FizzBuzzEvent>() // { // public FizzBuzzEvent newInstance() // { // return new FizzBuzzEvent(); // } // }; // }
import com.lmax.disruptor.support.FizzBuzzEvent; import com.lmax.disruptor.support.FizzBuzzEventHandler; import com.lmax.disruptor.support.FizzBuzzQueueProcessor; import com.lmax.disruptor.support.FizzBuzzStep; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*;
boolean fizz = 0 == (i % 3L); boolean buzz = 0 == (i % 5L); if (fizz && buzz) { ++temp; } } expectedResult = temp; } /////////////////////////////////////////////////////////////////////////////////////////////// private final BlockingQueue<Long> fizzInputQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final BlockingQueue<Long> buzzInputQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final BlockingQueue<Boolean> fizzOutputQueue = new LinkedBlockingQueue<Boolean>(BUFFER_SIZE); private final BlockingQueue<Boolean> buzzOutputQueue = new LinkedBlockingQueue<Boolean>(BUFFER_SIZE); private final FizzBuzzQueueProcessor fizzQueueProcessor = new FizzBuzzQueueProcessor(FizzBuzzStep.FIZZ, fizzInputQueue, buzzInputQueue, fizzOutputQueue, buzzOutputQueue, ITERATIONS - 1); private final FizzBuzzQueueProcessor buzzQueueProcessor = new FizzBuzzQueueProcessor(FizzBuzzStep.BUZZ, fizzInputQueue, buzzInputQueue, fizzOutputQueue, buzzOutputQueue, ITERATIONS - 1); private final FizzBuzzQueueProcessor fizzBuzzQueueProcessor = new FizzBuzzQueueProcessor(FizzBuzzStep.FIZZ_BUZZ, fizzInputQueue, buzzInputQueue, fizzOutputQueue, buzzOutputQueue, ITERATIONS - 1); ///////////////////////////////////////////////////////////////////////////////////////////////
// Path: src/performance/java/com/lmax/disruptor/support/FizzBuzzEvent.java // public final class FizzBuzzEvent // { // private boolean fizz = false; // private boolean buzz = false; // private long value = 0; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // fizz = false; // buzz = false; // this.value = value; // } // // public boolean isFizz() // { // return fizz; // } // // public void setFizz(final boolean fizz) // { // this.fizz = fizz; // } // // public boolean isBuzz() // { // return buzz; // } // // public void setBuzz(final boolean buzz) // { // this.buzz = buzz; // } // // public final static EventFactory<FizzBuzzEvent> EVENT_FACTORY = new EventFactory<FizzBuzzEvent>() // { // public FizzBuzzEvent newInstance() // { // return new FizzBuzzEvent(); // } // }; // } // Path: src/performance/java/com/lmax/disruptor/OnePublisherToThreeProcessorDiamondThroughputTest.java import com.lmax.disruptor.support.FizzBuzzEvent; import com.lmax.disruptor.support.FizzBuzzEventHandler; import com.lmax.disruptor.support.FizzBuzzQueueProcessor; import com.lmax.disruptor.support.FizzBuzzStep; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*; boolean fizz = 0 == (i % 3L); boolean buzz = 0 == (i % 5L); if (fizz && buzz) { ++temp; } } expectedResult = temp; } /////////////////////////////////////////////////////////////////////////////////////////////// private final BlockingQueue<Long> fizzInputQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final BlockingQueue<Long> buzzInputQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final BlockingQueue<Boolean> fizzOutputQueue = new LinkedBlockingQueue<Boolean>(BUFFER_SIZE); private final BlockingQueue<Boolean> buzzOutputQueue = new LinkedBlockingQueue<Boolean>(BUFFER_SIZE); private final FizzBuzzQueueProcessor fizzQueueProcessor = new FizzBuzzQueueProcessor(FizzBuzzStep.FIZZ, fizzInputQueue, buzzInputQueue, fizzOutputQueue, buzzOutputQueue, ITERATIONS - 1); private final FizzBuzzQueueProcessor buzzQueueProcessor = new FizzBuzzQueueProcessor(FizzBuzzStep.BUZZ, fizzInputQueue, buzzInputQueue, fizzOutputQueue, buzzOutputQueue, ITERATIONS - 1); private final FizzBuzzQueueProcessor fizzBuzzQueueProcessor = new FizzBuzzQueueProcessor(FizzBuzzStep.FIZZ_BUZZ, fizzInputQueue, buzzInputQueue, fizzOutputQueue, buzzOutputQueue, ITERATIONS - 1); ///////////////////////////////////////////////////////////////////////////////////////////////
private final RingBuffer<FizzBuzzEvent> ringBuffer =
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/Disruptor.java
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import com.lmax.disruptor.*; import com.lmax.disruptor.util.Util; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean;
{ for (EventProcessor processor : processors) { eventProcessorRepository.add(processor); } return new EventHandlerGroup<T>(this, eventProcessorRepository, processors); } /** * Publish an event to the ring buffer. * * @param eventTranslator the translator that will load data into the event. */ public void publishEvent(final EventTranslator<T> eventTranslator) { eventPublisher.publishEvent(eventTranslator); } /** * Starts the event processors and returns the fully configured ring buffer. * The ring buffer is set up to prevent overwriting any entry that is yet to * be processed by the slowest event processor. * This method must only be called once after all event processors have been added. * * @return the configured ring buffer. */ public RingBuffer<T> start() { EventProcessor[] gatingProcessors = eventProcessorRepository.getLastEventProcessorsInChain();
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/main/java/com/lmax/disruptor/dsl/Disruptor.java import com.lmax.disruptor.*; import com.lmax.disruptor.util.Util; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; { for (EventProcessor processor : processors) { eventProcessorRepository.add(processor); } return new EventHandlerGroup<T>(this, eventProcessorRepository, processors); } /** * Publish an event to the ring buffer. * * @param eventTranslator the translator that will load data into the event. */ public void publishEvent(final EventTranslator<T> eventTranslator) { eventPublisher.publishEvent(eventTranslator); } /** * Starts the event processors and returns the fully configured ring buffer. * The ring buffer is set up to prevent overwriting any entry that is yet to * be processed by the slowest event processor. * This method must only be called once after all event processors have been added. * * @return the configured ring buffer. */ public RingBuffer<T> start() { EventProcessor[] gatingProcessors = eventProcessorRepository.getLastEventProcessorsInChain();
ringBuffer.setGatingSequences(Util.getSequencesFor(gatingProcessors));
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/MultiThreadedClaimStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/MutableLong.java // public class MutableLong // { // private long value = 0L; // // /** // * Default constructor // */ // public MutableLong() // { // } // // /** // * Construct the holder with initial value. // * // * @param initialValue to be initially set. // */ // public MutableLong(final long initialValue) // { // this.value = initialValue; // } // // /** // * Get the long value. // * // * @return the long value. // */ // public long get() // { // return value; // } // // /** // * Set the long value. // * // * @param value to set. // */ // public void set(final long value) // { // this.value = value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import com.lmax.disruptor.util.MutableLong; import com.lmax.disruptor.util.PaddedAtomicLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Strategy to be used when there are multiple publisher threads claiming sequences. * * This strategy requires sufficient cores to allow multiple publishers to be concurrently claiming sequences. */ public final class MultiThreadedClaimStrategy implements ClaimStrategy { private final int bufferSize;
// Path: src/main/java/com/lmax/disruptor/util/MutableLong.java // public class MutableLong // { // private long value = 0L; // // /** // * Default constructor // */ // public MutableLong() // { // } // // /** // * Construct the holder with initial value. // * // * @param initialValue to be initially set. // */ // public MutableLong(final long initialValue) // { // this.value = initialValue; // } // // /** // * Get the long value. // * // * @return the long value. // */ // public long get() // { // return value; // } // // /** // * Set the long value. // * // * @param value to set. // */ // public void set(final long value) // { // this.value = value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/MultiThreadedClaimStrategy.java import com.lmax.disruptor.util.MutableLong; import com.lmax.disruptor.util.PaddedAtomicLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Strategy to be used when there are multiple publisher threads claiming sequences. * * This strategy requires sufficient cores to allow multiple publishers to be concurrently claiming sequences. */ public final class MultiThreadedClaimStrategy implements ClaimStrategy { private final int bufferSize;
private final PaddedAtomicLong claimSequence = new PaddedAtomicLong(Sequencer.INITIAL_CURSOR_VALUE);
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/MultiThreadedClaimStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/MutableLong.java // public class MutableLong // { // private long value = 0L; // // /** // * Default constructor // */ // public MutableLong() // { // } // // /** // * Construct the holder with initial value. // * // * @param initialValue to be initially set. // */ // public MutableLong(final long initialValue) // { // this.value = initialValue; // } // // /** // * Get the long value. // * // * @return the long value. // */ // public long get() // { // return value; // } // // /** // * Set the long value. // * // * @param value to set. // */ // public void set(final long value) // { // this.value = value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import com.lmax.disruptor.util.MutableLong; import com.lmax.disruptor.util.PaddedAtomicLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Strategy to be used when there are multiple publisher threads claiming sequences. * * This strategy requires sufficient cores to allow multiple publishers to be concurrently claiming sequences. */ public final class MultiThreadedClaimStrategy implements ClaimStrategy { private final int bufferSize; private final PaddedAtomicLong claimSequence = new PaddedAtomicLong(Sequencer.INITIAL_CURSOR_VALUE);
// Path: src/main/java/com/lmax/disruptor/util/MutableLong.java // public class MutableLong // { // private long value = 0L; // // /** // * Default constructor // */ // public MutableLong() // { // } // // /** // * Construct the holder with initial value. // * // * @param initialValue to be initially set. // */ // public MutableLong(final long initialValue) // { // this.value = initialValue; // } // // /** // * Get the long value. // * // * @return the long value. // */ // public long get() // { // return value; // } // // /** // * Set the long value. // * // * @param value to set. // */ // public void set(final long value) // { // this.value = value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/MultiThreadedClaimStrategy.java import com.lmax.disruptor.util.MutableLong; import com.lmax.disruptor.util.PaddedAtomicLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Strategy to be used when there are multiple publisher threads claiming sequences. * * This strategy requires sufficient cores to allow multiple publishers to be concurrently claiming sequences. */ public final class MultiThreadedClaimStrategy implements ClaimStrategy { private final int bufferSize; private final PaddedAtomicLong claimSequence = new PaddedAtomicLong(Sequencer.INITIAL_CURSOR_VALUE);
private final ThreadLocal<MutableLong> minGatingSequenceThreadLocal = new ThreadLocal<MutableLong>()
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/MultiThreadedClaimStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/MutableLong.java // public class MutableLong // { // private long value = 0L; // // /** // * Default constructor // */ // public MutableLong() // { // } // // /** // * Construct the holder with initial value. // * // * @param initialValue to be initially set. // */ // public MutableLong(final long initialValue) // { // this.value = initialValue; // } // // /** // * Get the long value. // * // * @return the long value. // */ // public long get() // { // return value; // } // // /** // * Set the long value. // * // * @param value to set. // */ // public void set(final long value) // { // this.value = value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import com.lmax.disruptor.util.MutableLong; import com.lmax.disruptor.util.PaddedAtomicLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence;
/** * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. */ public MultiThreadedClaimStrategy(final int bufferSize) { this.bufferSize = bufferSize; } @Override public int getBufferSize() { return bufferSize; } @Override public long getSequence() { return claimSequence.get(); } @Override public boolean hasAvailableCapacity(final int availableCapacity, final Sequence[] dependentSequences) { final long wrapPoint = (claimSequence.get() + availableCapacity) - bufferSize; final MutableLong minGatingSequence = minGatingSequenceThreadLocal.get(); if (wrapPoint > minGatingSequence.get()) {
// Path: src/main/java/com/lmax/disruptor/util/MutableLong.java // public class MutableLong // { // private long value = 0L; // // /** // * Default constructor // */ // public MutableLong() // { // } // // /** // * Construct the holder with initial value. // * // * @param initialValue to be initially set. // */ // public MutableLong(final long initialValue) // { // this.value = initialValue; // } // // /** // * Get the long value. // * // * @return the long value. // */ // public long get() // { // return value; // } // // /** // * Set the long value. // * // * @param value to set. // */ // public void set(final long value) // { // this.value = value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/PaddedAtomicLong.java // public class PaddedAtomicLong extends AtomicLong // { // public volatile long p1, p2, p3, p4, p5, p6 = 7L; // // /** // * Default constructor // */ // public PaddedAtomicLong() // { // } // // /** // * Construct with an initial value. // * // * @param initialValue for initialisation // */ // public PaddedAtomicLong(final long initialValue) // { // super(initialValue); // } // // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/MultiThreadedClaimStrategy.java import com.lmax.disruptor.util.MutableLong; import com.lmax.disruptor.util.PaddedAtomicLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence; /** * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. */ public MultiThreadedClaimStrategy(final int bufferSize) { this.bufferSize = bufferSize; } @Override public int getBufferSize() { return bufferSize; } @Override public long getSequence() { return claimSequence.get(); } @Override public boolean hasAvailableCapacity(final int availableCapacity, final Sequence[] dependentSequences) { final long wrapPoint = (claimSequence.get() + availableCapacity) - bufferSize; final MutableLong minGatingSequence = minGatingSequenceThreadLocal.get(); if (wrapPoint > minGatingSequence.get()) {
long minSequence = getMinimumSequence(dependentSequences);
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/LifecycleAwareTest.java
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // }
import com.lmax.disruptor.support.StubEvent; import org.junit.Test; import java.util.concurrent.CountDownLatch; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public final class LifecycleAwareTest { private final CountDownLatch startLatch = new CountDownLatch(1); private final CountDownLatch shutdownLatch = new CountDownLatch(1);
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // Path: src/test/java/com/lmax/disruptor/LifecycleAwareTest.java import com.lmax.disruptor.support.StubEvent; import org.junit.Test; import java.util.concurrent.CountDownLatch; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public final class LifecycleAwareTest { private final CountDownLatch startLatch = new CountDownLatch(1); private final CountDownLatch shutdownLatch = new CountDownLatch(1);
private final RingBuffer<StubEvent> ringBuffer = new RingBuffer<StubEvent>(StubEvent.EVENT_FACTORY, 16);
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/BusySpinWaitStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import java.util.concurrent.TimeUnit; import static com.lmax.disruptor.util.Util.getMinimumSequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Busy Spin strategy that uses a busy spin loop for {@link com.lmax.disruptor.EventProcessor}s waiting on a barrier. * * This strategy will use CPU resource to avoid syscalls which can introduce latency jitter. It is best * used when threads can be bound to specific CPU cores. */ public final class BusySpinWaitStrategy implements WaitStrategy { @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; if (0 == dependents.length) { while ((availableSequence = cursor.get()) < sequence) { barrier.checkAlert(); } } else {
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/BusySpinWaitStrategy.java import java.util.concurrent.TimeUnit; import static com.lmax.disruptor.util.Util.getMinimumSequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Busy Spin strategy that uses a busy spin loop for {@link com.lmax.disruptor.EventProcessor}s waiting on a barrier. * * This strategy will use CPU resource to avoid syscalls which can introduce latency jitter. It is best * used when threads can be bound to specific CPU cores. */ public final class BusySpinWaitStrategy implements WaitStrategy { @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; if (0 == dependents.length) { while ((availableSequence = cursor.get()) < sequence) { barrier.checkAlert(); } } else {
while ((availableSequence = getMinimumSequence(dependents)) < sequence)
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/support/FunctionEvent.java
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // }
import com.lmax.disruptor.EventFactory;
public long getOperandTwo() { return operandTwo; } public void setOperandTwo(final long operandTwo) { this.operandTwo = operandTwo; } public long getStepOneResult() { return stepOneResult; } public void setStepOneResult(final long stepOneResult) { this.stepOneResult = stepOneResult; } public long getStepTwoResult() { return stepTwoResult; } public void setStepTwoResult(final long stepTwoResult) { this.stepTwoResult = stepTwoResult; }
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // } // Path: src/performance/java/com/lmax/disruptor/support/FunctionEvent.java import com.lmax.disruptor.EventFactory; public long getOperandTwo() { return operandTwo; } public void setOperandTwo(final long operandTwo) { this.operandTwo = operandTwo; } public long getStepOneResult() { return stepOneResult; } public void setStepOneResult(final long stepOneResult) { this.stepOneResult = stepOneResult; } public long getStepTwoResult() { return stepTwoResult; } public void setStepTwoResult(final long stepTwoResult) { this.stepTwoResult = stepTwoResult; }
public final static EventFactory<FunctionEvent> EVENT_FACTORY = new EventFactory<FunctionEvent>()
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/util/UtilTest.java
// Path: src/main/java/com/lmax/disruptor/Sequence.java // public class Sequence // { // private static final AtomicLongFieldUpdater<Sequence> updater = AtomicLongFieldUpdater.newUpdater(Sequence.class, "value"); // // private volatile long p1 = 7L, p2 = 7L, p3 = 7L, p4 = 7L, p5 = 7L, p6 = 7L, p7 = 7L, // value = Sequencer.INITIAL_CURSOR_VALUE, // q1 = 7L, q2 = 7L, q3 = 7L, q4 = 7L, q5 = 7L, q6 = 7L, q7 = 7L; // // /** // * Default Constructor that uses an initial value of {@link Sequencer#INITIAL_CURSOR_VALUE}. // */ // public Sequence() // { // } // // /** // * Construct a sequence counter that can be tracked across threads. // * // * @param initialValue for the counter. // */ // public Sequence(final long initialValue) // { // set(initialValue); // } // // /** // * Get the current value of the {@link Sequence} // * // * @return the current value. // */ // public long get() // { // return value; // } // // /** // * Set the {@link Sequence} to a value. // * // * @param value to which the {@link Sequence} will be set. // */ // public void set(final long value) // { // updater.lazySet(this, value); // } // // /** // * Value of the {@link Sequence} as a String. // * // * @return String representation of the sequence. // */ // public String toString() // { // return Long.toString(value); // } // // /** // * Here to help make sure false sharing prevention padding is not optimised away. // * // * @return sum of padding. // */ // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6 + p7 + value + q1 + q2 + q3 + q4 + q5 + q6 + q7; // } // // public void setPaddingValue(final long value) // { // p1 = p2 = p3 = p4 = p5 = p6 = p7 = q1 = q2 = q3 = q4 = q5 = q6 = q7 = value; // } // // public boolean compareAndSet(long expectedSequence, long nextSequence) // { // return updater.compareAndSet(this, expectedSequence, nextSequence); // } // }
import com.lmax.disruptor.Sequence; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.util; @RunWith(JMock.class) public final class UtilTest { private final Mockery context = new Mockery(); @Test public void shouldReturnNextPowerOfTwo() { int powerOfTwo = Util.ceilingNextPowerOfTwo(1000); Assert.assertEquals(1024, powerOfTwo); } @Test public void shouldReturnExactPowerOfTwo() { int powerOfTwo = Util.ceilingNextPowerOfTwo(1024); Assert.assertEquals(1024, powerOfTwo); } @Test public void shouldReturnMinimumSequence() {
// Path: src/main/java/com/lmax/disruptor/Sequence.java // public class Sequence // { // private static final AtomicLongFieldUpdater<Sequence> updater = AtomicLongFieldUpdater.newUpdater(Sequence.class, "value"); // // private volatile long p1 = 7L, p2 = 7L, p3 = 7L, p4 = 7L, p5 = 7L, p6 = 7L, p7 = 7L, // value = Sequencer.INITIAL_CURSOR_VALUE, // q1 = 7L, q2 = 7L, q3 = 7L, q4 = 7L, q5 = 7L, q6 = 7L, q7 = 7L; // // /** // * Default Constructor that uses an initial value of {@link Sequencer#INITIAL_CURSOR_VALUE}. // */ // public Sequence() // { // } // // /** // * Construct a sequence counter that can be tracked across threads. // * // * @param initialValue for the counter. // */ // public Sequence(final long initialValue) // { // set(initialValue); // } // // /** // * Get the current value of the {@link Sequence} // * // * @return the current value. // */ // public long get() // { // return value; // } // // /** // * Set the {@link Sequence} to a value. // * // * @param value to which the {@link Sequence} will be set. // */ // public void set(final long value) // { // updater.lazySet(this, value); // } // // /** // * Value of the {@link Sequence} as a String. // * // * @return String representation of the sequence. // */ // public String toString() // { // return Long.toString(value); // } // // /** // * Here to help make sure false sharing prevention padding is not optimised away. // * // * @return sum of padding. // */ // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6 + p7 + value + q1 + q2 + q3 + q4 + q5 + q6 + q7; // } // // public void setPaddingValue(final long value) // { // p1 = p2 = p3 = p4 = p5 = p6 = p7 = q1 = q2 = q3 = q4 = q5 = q6 = q7 = value; // } // // public boolean compareAndSet(long expectedSequence, long nextSequence) // { // return updater.compareAndSet(this, expectedSequence, nextSequence); // } // } // Path: src/test/java/com/lmax/disruptor/util/UtilTest.java import com.lmax.disruptor.Sequence; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.util; @RunWith(JMock.class) public final class UtilTest { private final Mockery context = new Mockery(); @Test public void shouldReturnNextPowerOfTwo() { int powerOfTwo = Util.ceilingNextPowerOfTwo(1000); Assert.assertEquals(1024, powerOfTwo); } @Test public void shouldReturnExactPowerOfTwo() { int powerOfTwo = Util.ceilingNextPowerOfTwo(1024); Assert.assertEquals(1024, powerOfTwo); } @Test public void shouldReturnMinimumSequence() {
final Sequence[] sequences = new Sequence[3];
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventProcessorRepository.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import java.util.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorRepository<T> implements Iterable<EventProcessorInfo<T>> {
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // Path: src/main/java/com/lmax/disruptor/dsl/EventProcessorRepository.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import java.util.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorRepository<T> implements Iterable<EventProcessorInfo<T>> {
private final Map<EventHandler<?>, EventProcessorInfo<T>> eventProcessorInfoByHandler = new IdentityHashMap<EventHandler<?>, EventProcessorInfo<T>>();
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventProcessorRepository.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import java.util.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorRepository<T> implements Iterable<EventProcessorInfo<T>> { private final Map<EventHandler<?>, EventProcessorInfo<T>> eventProcessorInfoByHandler = new IdentityHashMap<EventHandler<?>, EventProcessorInfo<T>>();
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // Path: src/main/java/com/lmax/disruptor/dsl/EventProcessorRepository.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import java.util.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorRepository<T> implements Iterable<EventProcessorInfo<T>> { private final Map<EventHandler<?>, EventProcessorInfo<T>> eventProcessorInfoByHandler = new IdentityHashMap<EventHandler<?>, EventProcessorInfo<T>>();
private final Map<EventProcessor, EventProcessorInfo<T>> eventProcessorInfoByEventProcessor = new IdentityHashMap<EventProcessor, EventProcessorInfo<T>>();
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventProcessorRepository.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import java.util.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorRepository<T> implements Iterable<EventProcessorInfo<T>> { private final Map<EventHandler<?>, EventProcessorInfo<T>> eventProcessorInfoByHandler = new IdentityHashMap<EventHandler<?>, EventProcessorInfo<T>>(); private final Map<EventProcessor, EventProcessorInfo<T>> eventProcessorInfoByEventProcessor = new IdentityHashMap<EventProcessor, EventProcessorInfo<T>>(); public void add(final EventProcessor eventprocessor, final EventHandler<T> handler,
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // Path: src/main/java/com/lmax/disruptor/dsl/EventProcessorRepository.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; import java.util.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorRepository<T> implements Iterable<EventProcessorInfo<T>> { private final Map<EventHandler<?>, EventProcessorInfo<T>> eventProcessorInfoByHandler = new IdentityHashMap<EventHandler<?>, EventProcessorInfo<T>>(); private final Map<EventProcessor, EventProcessorInfo<T>> eventProcessorInfoByEventProcessor = new IdentityHashMap<EventProcessor, EventProcessorInfo<T>>(); public void add(final EventProcessor eventprocessor, final EventHandler<T> handler,
final SequenceBarrier barrier)
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventProcessorInfo.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorInfo<T> {
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // Path: src/main/java/com/lmax/disruptor/dsl/EventProcessorInfo.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorInfo<T> {
private final EventProcessor eventprocessor;
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventProcessorInfo.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorInfo<T> { private final EventProcessor eventprocessor;
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // Path: src/main/java/com/lmax/disruptor/dsl/EventProcessorInfo.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorInfo<T> { private final EventProcessor eventprocessor;
private final EventHandler<T> handler;
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/dsl/EventProcessorInfo.java
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // }
import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorInfo<T> { private final EventProcessor eventprocessor; private final EventHandler<T> handler;
// Path: src/main/java/com/lmax/disruptor/EventHandler.java // public interface EventHandler<T> // { // /** // * Called when a publisher has published an event to the {@link RingBuffer} // * // * @param event published to the {@link RingBuffer} // * @param sequence of the event being processed // * @param endOfBatch flag to indicate if this is the last event in a batch from the {@link RingBuffer} // * @throws Exception if the EventHandler would like the exception handled further up the chain. // */ // void onEvent(T event, long sequence, boolean endOfBatch) throws Exception; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // Path: src/main/java/com/lmax/disruptor/dsl/EventProcessorInfo.java import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.SequenceBarrier; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; class EventProcessorInfo<T> { private final EventProcessor eventprocessor; private final EventHandler<T> handler;
private final SequenceBarrier barrier;
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/util/Util.java
// Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/Sequence.java // public class Sequence // { // private static final AtomicLongFieldUpdater<Sequence> updater = AtomicLongFieldUpdater.newUpdater(Sequence.class, "value"); // // private volatile long p1 = 7L, p2 = 7L, p3 = 7L, p4 = 7L, p5 = 7L, p6 = 7L, p7 = 7L, // value = Sequencer.INITIAL_CURSOR_VALUE, // q1 = 7L, q2 = 7L, q3 = 7L, q4 = 7L, q5 = 7L, q6 = 7L, q7 = 7L; // // /** // * Default Constructor that uses an initial value of {@link Sequencer#INITIAL_CURSOR_VALUE}. // */ // public Sequence() // { // } // // /** // * Construct a sequence counter that can be tracked across threads. // * // * @param initialValue for the counter. // */ // public Sequence(final long initialValue) // { // set(initialValue); // } // // /** // * Get the current value of the {@link Sequence} // * // * @return the current value. // */ // public long get() // { // return value; // } // // /** // * Set the {@link Sequence} to a value. // * // * @param value to which the {@link Sequence} will be set. // */ // public void set(final long value) // { // updater.lazySet(this, value); // } // // /** // * Value of the {@link Sequence} as a String. // * // * @return String representation of the sequence. // */ // public String toString() // { // return Long.toString(value); // } // // /** // * Here to help make sure false sharing prevention padding is not optimised away. // * // * @return sum of padding. // */ // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6 + p7 + value + q1 + q2 + q3 + q4 + q5 + q6 + q7; // } // // public void setPaddingValue(final long value) // { // p1 = p2 = p3 = p4 = p5 = p6 = p7 = q1 = q2 = q3 = q4 = q5 = q6 = q7 = value; // } // // public boolean compareAndSet(long expectedSequence, long nextSequence) // { // return updater.compareAndSet(this, expectedSequence, nextSequence); // } // }
import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.Sequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.util; /** * Set of common functions used by the Disruptor */ public final class Util { /** * Calculate the next power of 2, greater than or equal to x.<p> * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. * * @param x Value to round up * @return The next power of 2 from x inclusive */ public static int ceilingNextPowerOfTwo(final int x) { return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); } /** * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. * * @param sequences to compare. * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. */
// Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/Sequence.java // public class Sequence // { // private static final AtomicLongFieldUpdater<Sequence> updater = AtomicLongFieldUpdater.newUpdater(Sequence.class, "value"); // // private volatile long p1 = 7L, p2 = 7L, p3 = 7L, p4 = 7L, p5 = 7L, p6 = 7L, p7 = 7L, // value = Sequencer.INITIAL_CURSOR_VALUE, // q1 = 7L, q2 = 7L, q3 = 7L, q4 = 7L, q5 = 7L, q6 = 7L, q7 = 7L; // // /** // * Default Constructor that uses an initial value of {@link Sequencer#INITIAL_CURSOR_VALUE}. // */ // public Sequence() // { // } // // /** // * Construct a sequence counter that can be tracked across threads. // * // * @param initialValue for the counter. // */ // public Sequence(final long initialValue) // { // set(initialValue); // } // // /** // * Get the current value of the {@link Sequence} // * // * @return the current value. // */ // public long get() // { // return value; // } // // /** // * Set the {@link Sequence} to a value. // * // * @param value to which the {@link Sequence} will be set. // */ // public void set(final long value) // { // updater.lazySet(this, value); // } // // /** // * Value of the {@link Sequence} as a String. // * // * @return String representation of the sequence. // */ // public String toString() // { // return Long.toString(value); // } // // /** // * Here to help make sure false sharing prevention padding is not optimised away. // * // * @return sum of padding. // */ // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6 + p7 + value + q1 + q2 + q3 + q4 + q5 + q6 + q7; // } // // public void setPaddingValue(final long value) // { // p1 = p2 = p3 = p4 = p5 = p6 = p7 = q1 = q2 = q3 = q4 = q5 = q6 = q7 = value; // } // // public boolean compareAndSet(long expectedSequence, long nextSequence) // { // return updater.compareAndSet(this, expectedSequence, nextSequence); // } // } // Path: src/main/java/com/lmax/disruptor/util/Util.java import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.Sequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.util; /** * Set of common functions used by the Disruptor */ public final class Util { /** * Calculate the next power of 2, greater than or equal to x.<p> * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. * * @param x Value to round up * @return The next power of 2 from x inclusive */ public static int ceilingNextPowerOfTwo(final int x) { return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); } /** * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. * * @param sequences to compare. * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. */
public static long getMinimumSequence(final Sequence[] sequences)
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/util/Util.java
// Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/Sequence.java // public class Sequence // { // private static final AtomicLongFieldUpdater<Sequence> updater = AtomicLongFieldUpdater.newUpdater(Sequence.class, "value"); // // private volatile long p1 = 7L, p2 = 7L, p3 = 7L, p4 = 7L, p5 = 7L, p6 = 7L, p7 = 7L, // value = Sequencer.INITIAL_CURSOR_VALUE, // q1 = 7L, q2 = 7L, q3 = 7L, q4 = 7L, q5 = 7L, q6 = 7L, q7 = 7L; // // /** // * Default Constructor that uses an initial value of {@link Sequencer#INITIAL_CURSOR_VALUE}. // */ // public Sequence() // { // } // // /** // * Construct a sequence counter that can be tracked across threads. // * // * @param initialValue for the counter. // */ // public Sequence(final long initialValue) // { // set(initialValue); // } // // /** // * Get the current value of the {@link Sequence} // * // * @return the current value. // */ // public long get() // { // return value; // } // // /** // * Set the {@link Sequence} to a value. // * // * @param value to which the {@link Sequence} will be set. // */ // public void set(final long value) // { // updater.lazySet(this, value); // } // // /** // * Value of the {@link Sequence} as a String. // * // * @return String representation of the sequence. // */ // public String toString() // { // return Long.toString(value); // } // // /** // * Here to help make sure false sharing prevention padding is not optimised away. // * // * @return sum of padding. // */ // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6 + p7 + value + q1 + q2 + q3 + q4 + q5 + q6 + q7; // } // // public void setPaddingValue(final long value) // { // p1 = p2 = p3 = p4 = p5 = p6 = p7 = q1 = q2 = q3 = q4 = q5 = q6 = q7 = value; // } // // public boolean compareAndSet(long expectedSequence, long nextSequence) // { // return updater.compareAndSet(this, expectedSequence, nextSequence); // } // }
import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.Sequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.util; /** * Set of common functions used by the Disruptor */ public final class Util { /** * Calculate the next power of 2, greater than or equal to x.<p> * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. * * @param x Value to round up * @return The next power of 2 from x inclusive */ public static int ceilingNextPowerOfTwo(final int x) { return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); } /** * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. * * @param sequences to compare. * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. */ public static long getMinimumSequence(final Sequence[] sequences) { long minimum = Long.MAX_VALUE; for (Sequence sequence : sequences) { long value = sequence.get(); minimum = minimum < value ? minimum : value; } return minimum; } /** * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s * * @param processors for which to get the sequences * @return the array of {@link Sequence}s */
// Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/main/java/com/lmax/disruptor/Sequence.java // public class Sequence // { // private static final AtomicLongFieldUpdater<Sequence> updater = AtomicLongFieldUpdater.newUpdater(Sequence.class, "value"); // // private volatile long p1 = 7L, p2 = 7L, p3 = 7L, p4 = 7L, p5 = 7L, p6 = 7L, p7 = 7L, // value = Sequencer.INITIAL_CURSOR_VALUE, // q1 = 7L, q2 = 7L, q3 = 7L, q4 = 7L, q5 = 7L, q6 = 7L, q7 = 7L; // // /** // * Default Constructor that uses an initial value of {@link Sequencer#INITIAL_CURSOR_VALUE}. // */ // public Sequence() // { // } // // /** // * Construct a sequence counter that can be tracked across threads. // * // * @param initialValue for the counter. // */ // public Sequence(final long initialValue) // { // set(initialValue); // } // // /** // * Get the current value of the {@link Sequence} // * // * @return the current value. // */ // public long get() // { // return value; // } // // /** // * Set the {@link Sequence} to a value. // * // * @param value to which the {@link Sequence} will be set. // */ // public void set(final long value) // { // updater.lazySet(this, value); // } // // /** // * Value of the {@link Sequence} as a String. // * // * @return String representation of the sequence. // */ // public String toString() // { // return Long.toString(value); // } // // /** // * Here to help make sure false sharing prevention padding is not optimised away. // * // * @return sum of padding. // */ // public long sumPaddingToPreventOptimisation() // { // return p1 + p2 + p3 + p4 + p5 + p6 + p7 + value + q1 + q2 + q3 + q4 + q5 + q6 + q7; // } // // public void setPaddingValue(final long value) // { // p1 = p2 = p3 = p4 = p5 = p6 = p7 = q1 = q2 = q3 = q4 = q5 = q6 = q7 = value; // } // // public boolean compareAndSet(long expectedSequence, long nextSequence) // { // return updater.compareAndSet(this, expectedSequence, nextSequence); // } // } // Path: src/main/java/com/lmax/disruptor/util/Util.java import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.Sequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.util; /** * Set of common functions used by the Disruptor */ public final class Util { /** * Calculate the next power of 2, greater than or equal to x.<p> * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. * * @param x Value to round up * @return The next power of 2 from x inclusive */ public static int ceilingNextPowerOfTwo(final int x) { return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); } /** * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. * * @param sequences to compare. * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. */ public static long getMinimumSequence(final Sequence[] sequences) { long minimum = Long.MAX_VALUE; for (Sequence sequence : sequences) { long value = sequence.get(); minimum = minimum < value ? minimum : value; } return minimum; } /** * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s * * @param processors for which to get the sequences * @return the array of {@link Sequence}s */
public static Sequence[] getSequencesFor(final EventProcessor... processors)
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/YieldingWaitStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import java.util.concurrent.TimeUnit; import static com.lmax.disruptor.util.Util.getMinimumSequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Yielding strategy that uses a Thread.yield() for {@link com.lmax.disruptor.EventProcessor}s waiting on a barrier * after an initially spinning. * * This strategy is a good compromise between performance and CPU resource without incurring significant latency spikes. */ public final class YieldingWaitStrategy implements WaitStrategy { private static final int SPIN_TRIES = 100; @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; int counter = SPIN_TRIES; if (0 == dependents.length) { while ((availableSequence = cursor.get()) < sequence) { counter = applyWaitMethod(barrier, counter); } } else {
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/YieldingWaitStrategy.java import java.util.concurrent.TimeUnit; import static com.lmax.disruptor.util.Util.getMinimumSequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Yielding strategy that uses a Thread.yield() for {@link com.lmax.disruptor.EventProcessor}s waiting on a barrier * after an initially spinning. * * This strategy is a good compromise between performance and CPU resource without incurring significant latency spikes. */ public final class YieldingWaitStrategy implements WaitStrategy { private static final int SPIN_TRIES = 100; @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; int counter = SPIN_TRIES; if (0 == dependents.length) { while ((availableSequence = cursor.get()) < sequence) { counter = applyWaitMethod(barrier, counter); } } else {
while ((availableSequence = getMinimumSequence(dependents)) < sequence)
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/support/TestEvent.java
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // }
import com.lmax.disruptor.EventFactory;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.support; public final class TestEvent { @Override public String toString() { return "Test Event"; }
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // } // Path: src/test/java/com/lmax/disruptor/support/TestEvent.java import com.lmax.disruptor.EventFactory; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.support; public final class TestEvent { @Override public String toString() { return "Test Event"; }
public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>()
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/support/LongEvent.java
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // }
import com.lmax.disruptor.EventFactory;
package com.lmax.disruptor.support; public class LongEvent { private long value; public void set(long value) { this.value = value; } public long get() { return value; }
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // } // Path: src/test/java/com/lmax/disruptor/support/LongEvent.java import com.lmax.disruptor.EventFactory; package com.lmax.disruptor.support; public class LongEvent { private long value; public void set(long value) { this.value = value; } public long get() { return value; }
public static final EventFactory<LongEvent> FACTORY = new EventFactory<LongEvent>()
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/OnePublisherToThreeProcessorPipelineThroughputTest.java
// Path: src/performance/java/com/lmax/disruptor/support/FunctionEvent.java // public final class FunctionEvent // { // private long operandOne; // private long operandTwo; // private long stepOneResult; // private long stepTwoResult; // // public long getOperandOne() // { // return operandOne; // } // // public void setOperandOne(final long operandOne) // { // this.operandOne = operandOne; // } // // public long getOperandTwo() // { // return operandTwo; // } // // public void setOperandTwo(final long operandTwo) // { // this.operandTwo = operandTwo; // } // // public long getStepOneResult() // { // return stepOneResult; // } // // public void setStepOneResult(final long stepOneResult) // { // this.stepOneResult = stepOneResult; // } // // public long getStepTwoResult() // { // return stepTwoResult; // } // // public void setStepTwoResult(final long stepTwoResult) // { // this.stepTwoResult = stepTwoResult; // } // // public final static EventFactory<FunctionEvent> EVENT_FACTORY = new EventFactory<FunctionEvent>() // { // public FunctionEvent newInstance() // { // return new FunctionEvent(); // } // }; // }
import com.lmax.disruptor.support.FunctionEvent; import com.lmax.disruptor.support.FunctionEventHandler; import com.lmax.disruptor.support.FunctionQueueProcessor; import com.lmax.disruptor.support.FunctionStep; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*;
for (long i = 0; i < ITERATIONS; i++) { long stepOneResult = i + operandTwo--; long stepTwoResult = stepOneResult + 3; if ((stepTwoResult & 4L) == 4L) { ++temp; } } expectedResult = temp; } /////////////////////////////////////////////////////////////////////////////////////////////// private final BlockingQueue<long[]> stepOneQueue = new LinkedBlockingQueue<long[]>(BUFFER_SIZE); private final BlockingQueue<Long> stepTwoQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final BlockingQueue<Long> stepThreeQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final FunctionQueueProcessor stepOneQueueProcessor = new FunctionQueueProcessor(FunctionStep.ONE, stepOneQueue, stepTwoQueue, stepThreeQueue, ITERATIONS - 1); private final FunctionQueueProcessor stepTwoQueueProcessor = new FunctionQueueProcessor(FunctionStep.TWO, stepOneQueue, stepTwoQueue, stepThreeQueue, ITERATIONS - 1); private final FunctionQueueProcessor stepThreeQueueProcessor = new FunctionQueueProcessor(FunctionStep.THREE, stepOneQueue, stepTwoQueue, stepThreeQueue, ITERATIONS - 1); ///////////////////////////////////////////////////////////////////////////////////////////////
// Path: src/performance/java/com/lmax/disruptor/support/FunctionEvent.java // public final class FunctionEvent // { // private long operandOne; // private long operandTwo; // private long stepOneResult; // private long stepTwoResult; // // public long getOperandOne() // { // return operandOne; // } // // public void setOperandOne(final long operandOne) // { // this.operandOne = operandOne; // } // // public long getOperandTwo() // { // return operandTwo; // } // // public void setOperandTwo(final long operandTwo) // { // this.operandTwo = operandTwo; // } // // public long getStepOneResult() // { // return stepOneResult; // } // // public void setStepOneResult(final long stepOneResult) // { // this.stepOneResult = stepOneResult; // } // // public long getStepTwoResult() // { // return stepTwoResult; // } // // public void setStepTwoResult(final long stepTwoResult) // { // this.stepTwoResult = stepTwoResult; // } // // public final static EventFactory<FunctionEvent> EVENT_FACTORY = new EventFactory<FunctionEvent>() // { // public FunctionEvent newInstance() // { // return new FunctionEvent(); // } // }; // } // Path: src/performance/java/com/lmax/disruptor/OnePublisherToThreeProcessorPipelineThroughputTest.java import com.lmax.disruptor.support.FunctionEvent; import com.lmax.disruptor.support.FunctionEventHandler; import com.lmax.disruptor.support.FunctionQueueProcessor; import com.lmax.disruptor.support.FunctionStep; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*; for (long i = 0; i < ITERATIONS; i++) { long stepOneResult = i + operandTwo--; long stepTwoResult = stepOneResult + 3; if ((stepTwoResult & 4L) == 4L) { ++temp; } } expectedResult = temp; } /////////////////////////////////////////////////////////////////////////////////////////////// private final BlockingQueue<long[]> stepOneQueue = new LinkedBlockingQueue<long[]>(BUFFER_SIZE); private final BlockingQueue<Long> stepTwoQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final BlockingQueue<Long> stepThreeQueue = new LinkedBlockingQueue<Long>(BUFFER_SIZE); private final FunctionQueueProcessor stepOneQueueProcessor = new FunctionQueueProcessor(FunctionStep.ONE, stepOneQueue, stepTwoQueue, stepThreeQueue, ITERATIONS - 1); private final FunctionQueueProcessor stepTwoQueueProcessor = new FunctionQueueProcessor(FunctionStep.TWO, stepOneQueue, stepTwoQueue, stepThreeQueue, ITERATIONS - 1); private final FunctionQueueProcessor stepThreeQueueProcessor = new FunctionQueueProcessor(FunctionStep.THREE, stepOneQueue, stepTwoQueue, stepThreeQueue, ITERATIONS - 1); ///////////////////////////////////////////////////////////////////////////////////////////////
private final RingBuffer<FunctionEvent> ringBuffer =
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/BatchEventProcessorTest.java
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // }
import com.lmax.disruptor.support.StubEvent; import org.hamcrest.Description; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import static com.lmax.disruptor.support.Actions.countDown; import static org.junit.Assert.assertEquals;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; @RunWith(JMock.class) public final class BatchEventProcessorTest { private final Mockery context = new Mockery(); private final Sequence lifecycleSequence = context.sequence("lifecycleSequence"); private final CountDownLatch latch = new CountDownLatch(1);
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // Path: src/test/java/com/lmax/disruptor/BatchEventProcessorTest.java import com.lmax.disruptor.support.StubEvent; import org.hamcrest.Description; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.api.Action; import org.jmock.api.Invocation; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import static com.lmax.disruptor.support.Actions.countDown; import static org.junit.Assert.assertEquals; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; @RunWith(JMock.class) public final class BatchEventProcessorTest { private final Mockery context = new Mockery(); private final Sequence lifecycleSequence = context.sequence("lifecycleSequence"); private final CountDownLatch latch = new CountDownLatch(1);
private final RingBuffer<StubEvent> ringBuffer = new RingBuffer<StubEvent>(StubEvent.EVENT_FACTORY, 16);
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/support/ValueEvent.java
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // }
import com.lmax.disruptor.EventFactory;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.support; public final class ValueEvent { private long value; public long getValue() { return value; } public void setValue(final long value) { this.value = value; }
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // } // Path: src/performance/java/com/lmax/disruptor/support/ValueEvent.java import com.lmax.disruptor.EventFactory; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.support; public final class ValueEvent { private long value; public long getValue() { return value; } public void setValue(final long value) { this.value = value; }
public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>()
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/support/StubEvent.java
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // }
import com.lmax.disruptor.EventFactory;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.support; public final class StubEvent { private int value; private String testString; public StubEvent(int i) { this.value = i; } public void copy(StubEvent event) { value = event.value; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String getTestString() { return testString; } public void setTestString(final String testString) { this.testString = testString; }
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // } // Path: src/test/java/com/lmax/disruptor/support/StubEvent.java import com.lmax.disruptor.EventFactory; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.support; public final class StubEvent { private int value; private String testString; public StubEvent(int i) { this.value = i; } public void copy(StubEvent event) { value = event.value; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public String getTestString() { return testString; } public void setTestString(final String testString) { this.testString = testString; }
public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>()
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/dsl/stubs/StubExecutor.java
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // }
import com.lmax.disruptor.support.DaemonThreadFactory; import org.junit.Assert; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl.stubs; public class StubExecutor implements Executor {
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // Path: src/test/java/com/lmax/disruptor/dsl/stubs/StubExecutor.java import com.lmax.disruptor.support.DaemonThreadFactory; import org.junit.Assert; import java.util.Collection; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl.stubs; public class StubExecutor implements Executor {
private final DaemonThreadFactory threadFactory = new DaemonThreadFactory();
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/BatchPublisherTest.java
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // }
import com.lmax.disruptor.support.StubEvent; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public final class BatchPublisherTest {
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // Path: src/test/java/com/lmax/disruptor/BatchPublisherTest.java import com.lmax.disruptor.support.StubEvent; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public final class BatchPublisherTest {
private final RingBuffer<StubEvent> ringBuffer = new RingBuffer<StubEvent>(StubEvent.EVENT_FACTORY, 32);
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/SleepingWaitStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Sleeping strategy that initially spins, then uses a Thread.yield(), and eventually for the minimum number of nanos * the OS and JVM will allow while the {@link com.lmax.disruptor.EventProcessor}s are waiting on a barrier. * * This strategy is a good compromise between performance and CPU resource. Latency spikes can occur after quiet periods. */ public final class SleepingWaitStrategy implements WaitStrategy { private static final int RETRIES = 200; @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; int counter = RETRIES; if (0 == dependents.length) { while ((availableSequence = cursor.get()) < sequence) { counter = applyWaitMethod(barrier, counter); } } else {
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/SleepingWaitStrategy.java import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Sleeping strategy that initially spins, then uses a Thread.yield(), and eventually for the minimum number of nanos * the OS and JVM will allow while the {@link com.lmax.disruptor.EventProcessor}s are waiting on a barrier. * * This strategy is a good compromise between performance and CPU resource. Latency spikes can occur after quiet periods. */ public final class SleepingWaitStrategy implements WaitStrategy { private static final int RETRIES = 200; @Override public long waitFor(final long sequence, final Sequence cursor, final Sequence[] dependents, final SequenceBarrier barrier) throws AlertException, InterruptedException { long availableSequence; int counter = RETRIES; if (0 == dependents.length) { while ((availableSequence = cursor.get()) < sequence) { counter = applyWaitMethod(barrier, counter); } } else {
while ((availableSequence = getMinimumSequence(dependents)) < sequence)
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/EventTranslatorTest.java
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // }
import com.lmax.disruptor.support.StubEvent; import org.junit.Assert; import org.junit.Test;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public final class EventTranslatorTest { private static final String TEST_VALUE = "Wibble"; @Test public void shouldTranslateOtherDataIntoAnEvent() {
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // Path: src/test/java/com/lmax/disruptor/EventTranslatorTest.java import com.lmax.disruptor.support.StubEvent; import org.junit.Assert; import org.junit.Test; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public final class EventTranslatorTest { private static final String TEST_VALUE = "Wibble"; @Test public void shouldTranslateOtherDataIntoAnEvent() {
StubEvent event = StubEvent.EVENT_FACTORY.newInstance();
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/RingBufferTest.java
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // // Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java // public final class TestWaiter implements Callable<List<StubEvent>> // { // private final long toWaitForSequence; // private final long initialSequence; // private final CyclicBarrier cyclicBarrier; // private final SequenceBarrier sequenceBarrier; // private final RingBuffer<StubEvent> ringBuffer; // // public TestWaiter(final CyclicBarrier cyclicBarrier, // final SequenceBarrier sequenceBarrier, // final RingBuffer<StubEvent> ringBuffer, // final long initialSequence, // final long toWaitForSequence) // { // this.cyclicBarrier = cyclicBarrier; // this.initialSequence = initialSequence; // this.ringBuffer = ringBuffer; // this.toWaitForSequence = toWaitForSequence; // this.sequenceBarrier = sequenceBarrier; // } // // @Override // public List<StubEvent> call() throws Exception // { // cyclicBarrier.await(); // sequenceBarrier.waitFor(toWaitForSequence); // // final List<StubEvent> messages = new ArrayList<StubEvent>(); // for (long l = initialSequence; l <= toWaitForSequence; l++) // { // messages.add(ringBuffer.get(l)); // } // // return messages; // } // }
import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import com.lmax.disruptor.support.DaemonThreadFactory; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.support.TestWaiter; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public class RingBufferTest {
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // // Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java // public final class TestWaiter implements Callable<List<StubEvent>> // { // private final long toWaitForSequence; // private final long initialSequence; // private final CyclicBarrier cyclicBarrier; // private final SequenceBarrier sequenceBarrier; // private final RingBuffer<StubEvent> ringBuffer; // // public TestWaiter(final CyclicBarrier cyclicBarrier, // final SequenceBarrier sequenceBarrier, // final RingBuffer<StubEvent> ringBuffer, // final long initialSequence, // final long toWaitForSequence) // { // this.cyclicBarrier = cyclicBarrier; // this.initialSequence = initialSequence; // this.ringBuffer = ringBuffer; // this.toWaitForSequence = toWaitForSequence; // this.sequenceBarrier = sequenceBarrier; // } // // @Override // public List<StubEvent> call() throws Exception // { // cyclicBarrier.await(); // sequenceBarrier.waitFor(toWaitForSequence); // // final List<StubEvent> messages = new ArrayList<StubEvent>(); // for (long l = initialSequence; l <= toWaitForSequence; l++) // { // messages.add(ringBuffer.get(l)); // } // // return messages; // } // } // Path: src/test/java/com/lmax/disruptor/RingBufferTest.java import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import com.lmax.disruptor.support.DaemonThreadFactory; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.support.TestWaiter; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public class RingBufferTest {
private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/RingBufferTest.java
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // // Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java // public final class TestWaiter implements Callable<List<StubEvent>> // { // private final long toWaitForSequence; // private final long initialSequence; // private final CyclicBarrier cyclicBarrier; // private final SequenceBarrier sequenceBarrier; // private final RingBuffer<StubEvent> ringBuffer; // // public TestWaiter(final CyclicBarrier cyclicBarrier, // final SequenceBarrier sequenceBarrier, // final RingBuffer<StubEvent> ringBuffer, // final long initialSequence, // final long toWaitForSequence) // { // this.cyclicBarrier = cyclicBarrier; // this.initialSequence = initialSequence; // this.ringBuffer = ringBuffer; // this.toWaitForSequence = toWaitForSequence; // this.sequenceBarrier = sequenceBarrier; // } // // @Override // public List<StubEvent> call() throws Exception // { // cyclicBarrier.await(); // sequenceBarrier.waitFor(toWaitForSequence); // // final List<StubEvent> messages = new ArrayList<StubEvent>(); // for (long l = initialSequence; l <= toWaitForSequence; l++) // { // messages.add(ringBuffer.get(l)); // } // // return messages; // } // }
import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import com.lmax.disruptor.support.DaemonThreadFactory; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.support.TestWaiter; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public class RingBufferTest { private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // // Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java // public final class TestWaiter implements Callable<List<StubEvent>> // { // private final long toWaitForSequence; // private final long initialSequence; // private final CyclicBarrier cyclicBarrier; // private final SequenceBarrier sequenceBarrier; // private final RingBuffer<StubEvent> ringBuffer; // // public TestWaiter(final CyclicBarrier cyclicBarrier, // final SequenceBarrier sequenceBarrier, // final RingBuffer<StubEvent> ringBuffer, // final long initialSequence, // final long toWaitForSequence) // { // this.cyclicBarrier = cyclicBarrier; // this.initialSequence = initialSequence; // this.ringBuffer = ringBuffer; // this.toWaitForSequence = toWaitForSequence; // this.sequenceBarrier = sequenceBarrier; // } // // @Override // public List<StubEvent> call() throws Exception // { // cyclicBarrier.await(); // sequenceBarrier.waitFor(toWaitForSequence); // // final List<StubEvent> messages = new ArrayList<StubEvent>(); // for (long l = initialSequence; l <= toWaitForSequence; l++) // { // messages.add(ringBuffer.get(l)); // } // // return messages; // } // } // Path: src/test/java/com/lmax/disruptor/RingBufferTest.java import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import com.lmax.disruptor.support.DaemonThreadFactory; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.support.TestWaiter; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; public class RingBufferTest { private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
private final RingBuffer<StubEvent> ringBuffer = new RingBuffer<StubEvent>(StubEvent.EVENT_FACTORY, 32);
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/RingBufferTest.java
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // // Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java // public final class TestWaiter implements Callable<List<StubEvent>> // { // private final long toWaitForSequence; // private final long initialSequence; // private final CyclicBarrier cyclicBarrier; // private final SequenceBarrier sequenceBarrier; // private final RingBuffer<StubEvent> ringBuffer; // // public TestWaiter(final CyclicBarrier cyclicBarrier, // final SequenceBarrier sequenceBarrier, // final RingBuffer<StubEvent> ringBuffer, // final long initialSequence, // final long toWaitForSequence) // { // this.cyclicBarrier = cyclicBarrier; // this.initialSequence = initialSequence; // this.ringBuffer = ringBuffer; // this.toWaitForSequence = toWaitForSequence; // this.sequenceBarrier = sequenceBarrier; // } // // @Override // public List<StubEvent> call() throws Exception // { // cyclicBarrier.await(); // sequenceBarrier.waitFor(toWaitForSequence); // // final List<StubEvent> messages = new ArrayList<StubEvent>(); // for (long l = initialSequence; l <= toWaitForSequence; l++) // { // messages.add(ringBuffer.get(l)); // } // // return messages; // } // }
import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import com.lmax.disruptor.support.DaemonThreadFactory; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.support.TestWaiter; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat;
for (int i = 0; i <= ringBufferSize; i++) { long sequence = ringBuffer.next(); StubEvent event = ringBuffer.get(sequence); event.setValue(i); ringBuffer.publish(sequence); latch.countDown(); } publisherComplete.set(true); } }); thread.start(); latch.await(); assertThat(Long.valueOf(ringBuffer.getCursor()), is(Long.valueOf(ringBufferSize - 1))); assertFalse(publisherComplete.get()); processor.run(); thread.join(); assertTrue(publisherComplete.get()); } private Future<List<StubEvent>> getMessages(final long initial, final long toWaitFor) throws InterruptedException, BrokenBarrierException { final CyclicBarrier cyclicBarrier = new CyclicBarrier(2); final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
// Path: src/test/java/com/lmax/disruptor/support/DaemonThreadFactory.java // public final class DaemonThreadFactory implements ThreadFactory // { // @Override // public Thread newThread(final Runnable r) // { // Thread t = new Thread(r); // t.setDaemon(true); // return t; // } // } // // Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/test/java/com/lmax/disruptor/support/TestWaiter.java // public final class TestWaiter implements Callable<List<StubEvent>> // { // private final long toWaitForSequence; // private final long initialSequence; // private final CyclicBarrier cyclicBarrier; // private final SequenceBarrier sequenceBarrier; // private final RingBuffer<StubEvent> ringBuffer; // // public TestWaiter(final CyclicBarrier cyclicBarrier, // final SequenceBarrier sequenceBarrier, // final RingBuffer<StubEvent> ringBuffer, // final long initialSequence, // final long toWaitForSequence) // { // this.cyclicBarrier = cyclicBarrier; // this.initialSequence = initialSequence; // this.ringBuffer = ringBuffer; // this.toWaitForSequence = toWaitForSequence; // this.sequenceBarrier = sequenceBarrier; // } // // @Override // public List<StubEvent> call() throws Exception // { // cyclicBarrier.await(); // sequenceBarrier.waitFor(toWaitForSequence); // // final List<StubEvent> messages = new ArrayList<StubEvent>(); // for (long l = initialSequence; l <= toWaitForSequence; l++) // { // messages.add(ringBuffer.get(l)); // } // // return messages; // } // } // Path: src/test/java/com/lmax/disruptor/RingBufferTest.java import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import com.lmax.disruptor.support.DaemonThreadFactory; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.support.TestWaiter; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; for (int i = 0; i <= ringBufferSize; i++) { long sequence = ringBuffer.next(); StubEvent event = ringBuffer.get(sequence); event.setValue(i); ringBuffer.publish(sequence); latch.countDown(); } publisherComplete.set(true); } }); thread.start(); latch.await(); assertThat(Long.valueOf(ringBuffer.getCursor()), is(Long.valueOf(ringBufferSize - 1))); assertFalse(publisherComplete.get()); processor.run(); thread.join(); assertTrue(publisherComplete.get()); } private Future<List<StubEvent>> getMessages(final long initial, final long toWaitFor) throws InterruptedException, BrokenBarrierException { final CyclicBarrier cyclicBarrier = new CyclicBarrier(2); final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
final Future<List<StubEvent>> f = EXECUTOR.submit(new TestWaiter(cyclicBarrier, sequenceBarrier, ringBuffer, initial, toWaitFor));
jbrisbin/disruptor
src/main/java/com/lmax/disruptor/SingleThreadedClaimStrategy.java
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // }
import com.lmax.disruptor.util.PaddedLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Optimised strategy can be used when there is a single publisher thread claiming sequences. * * This strategy must <b>not</b> be used when multiple threads are used for publishing concurrently on the same {@link Sequencer} */ public final class SingleThreadedClaimStrategy implements ClaimStrategy { private final int bufferSize; private final PaddedLong minGatingSequence = new PaddedLong(Sequencer.INITIAL_CURSOR_VALUE); private final PaddedLong claimSequence = new PaddedLong(Sequencer.INITIAL_CURSOR_VALUE); /** * Construct a new single threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. */ public SingleThreadedClaimStrategy(final int bufferSize) { this.bufferSize = bufferSize; } @Override public int getBufferSize() { return bufferSize; } @Override public long getSequence() { return claimSequence.get(); } @Override public boolean hasAvailableCapacity(final int availableCapacity, final Sequence[] dependentSequences) { final long wrapPoint = (claimSequence.get() + availableCapacity) - bufferSize; if (wrapPoint > minGatingSequence.get()) {
// Path: src/main/java/com/lmax/disruptor/util/Util.java // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // Path: src/main/java/com/lmax/disruptor/SingleThreadedClaimStrategy.java import com.lmax.disruptor.util.PaddedLong; import java.util.concurrent.locks.LockSupport; import static com.lmax.disruptor.util.Util.getMinimumSequence; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * Optimised strategy can be used when there is a single publisher thread claiming sequences. * * This strategy must <b>not</b> be used when multiple threads are used for publishing concurrently on the same {@link Sequencer} */ public final class SingleThreadedClaimStrategy implements ClaimStrategy { private final int bufferSize; private final PaddedLong minGatingSequence = new PaddedLong(Sequencer.INITIAL_CURSOR_VALUE); private final PaddedLong claimSequence = new PaddedLong(Sequencer.INITIAL_CURSOR_VALUE); /** * Construct a new single threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. */ public SingleThreadedClaimStrategy(final int bufferSize) { this.bufferSize = bufferSize; } @Override public int getBufferSize() { return bufferSize; } @Override public long getSequence() { return claimSequence.get(); } @Override public boolean hasAvailableCapacity(final int availableCapacity, final Sequence[] dependentSequences) { final long wrapPoint = (claimSequence.get() + availableCapacity) - bufferSize; if (wrapPoint > minGatingSequence.get()) {
long minSequence = getMinimumSequence(dependentSequences);
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/OnePublisherToOneProcessorUniCastBatchThroughputTest.java
// Path: src/performance/java/com/lmax/disruptor/support/ValueAdditionEventHandler.java // public final class ValueAdditionEventHandler implements EventHandler<ValueEvent> // { // private final PaddedLong value = new PaddedLong(); // private long count; // private CountDownLatch latch; // // public long getValue() // { // return value.get(); // } // // public void reset(final CountDownLatch latch, final long expectedCount) // { // value.set(0L); // this.latch = latch; // count = expectedCount; // } // // @Override // public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception // { // value.set(value.get() + event.getValue()); // // if (count == sequence) // { // latch.countDown(); // } // } // } // // Path: src/performance/java/com/lmax/disruptor/support/ValueEvent.java // public final class ValueEvent // { // private long value; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // this.value = value; // } // // public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() // { // public ValueEvent newInstance() // { // return new ValueEvent(); // } // }; // }
import com.lmax.disruptor.support.PerfTestUtil; import com.lmax.disruptor.support.ValueAdditionEventHandler; import com.lmax.disruptor.support.ValueEvent; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * <pre> * UniCast a series of items between 1 publisher and 1 event processor. * This test illustrates the benefits of writing batches of 10 events * for exchange at a time. * * +----+ +-----+ * | P1 |--->| EP1 | * +----+ +-----+ * * * Queue Based: * ============ * * put take * +----+ +====+ +-----+ * | P1 |--->| Q1 |<---| EP1 | * +----+ +====+ +-----+ * * P1 - Publisher 1 * Q1 - Queue 1 * EP1 - EventProcessor 1 * * * Disruptor: * ========== * track to prevent wrap * +------------------+ * | | * | v * +----+ +====+ +====+ +-----+ * | P1 |--->| RB |<---| SB | | EP1 | * +----+ +====+ +====+ +-----+ * claim get ^ | * | | * +--------+ * waitFor * * P1 - Publisher 1 * RB - RingBuffer * SB - SequenceBarrier * EP1 - EventProcessor 1 * </pre> */ public final class OnePublisherToOneProcessorUniCastBatchThroughputTest extends AbstractPerfTestQueueVsDisruptor { private static final int BUFFER_SIZE = 1024 * 8; private static final long ITERATIONS = 1000L * 1000L * 100L; private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(); private final long expectedResult = PerfTestUtil.accumulatedAddition(ITERATIONS); ///////////////////////////////////////////////////////////////////////////////////////////////
// Path: src/performance/java/com/lmax/disruptor/support/ValueAdditionEventHandler.java // public final class ValueAdditionEventHandler implements EventHandler<ValueEvent> // { // private final PaddedLong value = new PaddedLong(); // private long count; // private CountDownLatch latch; // // public long getValue() // { // return value.get(); // } // // public void reset(final CountDownLatch latch, final long expectedCount) // { // value.set(0L); // this.latch = latch; // count = expectedCount; // } // // @Override // public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception // { // value.set(value.get() + event.getValue()); // // if (count == sequence) // { // latch.countDown(); // } // } // } // // Path: src/performance/java/com/lmax/disruptor/support/ValueEvent.java // public final class ValueEvent // { // private long value; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // this.value = value; // } // // public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() // { // public ValueEvent newInstance() // { // return new ValueEvent(); // } // }; // } // Path: src/performance/java/com/lmax/disruptor/OnePublisherToOneProcessorUniCastBatchThroughputTest.java import com.lmax.disruptor.support.PerfTestUtil; import com.lmax.disruptor.support.ValueAdditionEventHandler; import com.lmax.disruptor.support.ValueEvent; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * <pre> * UniCast a series of items between 1 publisher and 1 event processor. * This test illustrates the benefits of writing batches of 10 events * for exchange at a time. * * +----+ +-----+ * | P1 |--->| EP1 | * +----+ +-----+ * * * Queue Based: * ============ * * put take * +----+ +====+ +-----+ * | P1 |--->| Q1 |<---| EP1 | * +----+ +====+ +-----+ * * P1 - Publisher 1 * Q1 - Queue 1 * EP1 - EventProcessor 1 * * * Disruptor: * ========== * track to prevent wrap * +------------------+ * | | * | v * +----+ +====+ +====+ +-----+ * | P1 |--->| RB |<---| SB | | EP1 | * +----+ +====+ +====+ +-----+ * claim get ^ | * | | * +--------+ * waitFor * * P1 - Publisher 1 * RB - RingBuffer * SB - SequenceBarrier * EP1 - EventProcessor 1 * </pre> */ public final class OnePublisherToOneProcessorUniCastBatchThroughputTest extends AbstractPerfTestQueueVsDisruptor { private static final int BUFFER_SIZE = 1024 * 8; private static final long ITERATIONS = 1000L * 1000L * 100L; private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(); private final long expectedResult = PerfTestUtil.accumulatedAddition(ITERATIONS); ///////////////////////////////////////////////////////////////////////////////////////////////
private final RingBuffer<ValueEvent> ringBuffer =
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/OnePublisherToOneProcessorUniCastBatchThroughputTest.java
// Path: src/performance/java/com/lmax/disruptor/support/ValueAdditionEventHandler.java // public final class ValueAdditionEventHandler implements EventHandler<ValueEvent> // { // private final PaddedLong value = new PaddedLong(); // private long count; // private CountDownLatch latch; // // public long getValue() // { // return value.get(); // } // // public void reset(final CountDownLatch latch, final long expectedCount) // { // value.set(0L); // this.latch = latch; // count = expectedCount; // } // // @Override // public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception // { // value.set(value.get() + event.getValue()); // // if (count == sequence) // { // latch.countDown(); // } // } // } // // Path: src/performance/java/com/lmax/disruptor/support/ValueEvent.java // public final class ValueEvent // { // private long value; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // this.value = value; // } // // public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() // { // public ValueEvent newInstance() // { // return new ValueEvent(); // } // }; // }
import com.lmax.disruptor.support.PerfTestUtil; import com.lmax.disruptor.support.ValueAdditionEventHandler; import com.lmax.disruptor.support.ValueEvent; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * <pre> * UniCast a series of items between 1 publisher and 1 event processor. * This test illustrates the benefits of writing batches of 10 events * for exchange at a time. * * +----+ +-----+ * | P1 |--->| EP1 | * +----+ +-----+ * * * Queue Based: * ============ * * put take * +----+ +====+ +-----+ * | P1 |--->| Q1 |<---| EP1 | * +----+ +====+ +-----+ * * P1 - Publisher 1 * Q1 - Queue 1 * EP1 - EventProcessor 1 * * * Disruptor: * ========== * track to prevent wrap * +------------------+ * | | * | v * +----+ +====+ +====+ +-----+ * | P1 |--->| RB |<---| SB | | EP1 | * +----+ +====+ +====+ +-----+ * claim get ^ | * | | * +--------+ * waitFor * * P1 - Publisher 1 * RB - RingBuffer * SB - SequenceBarrier * EP1 - EventProcessor 1 * </pre> */ public final class OnePublisherToOneProcessorUniCastBatchThroughputTest extends AbstractPerfTestQueueVsDisruptor { private static final int BUFFER_SIZE = 1024 * 8; private static final long ITERATIONS = 1000L * 1000L * 100L; private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(); private final long expectedResult = PerfTestUtil.accumulatedAddition(ITERATIONS); /////////////////////////////////////////////////////////////////////////////////////////////// private final RingBuffer<ValueEvent> ringBuffer = new RingBuffer<ValueEvent>(ValueEvent.EVENT_FACTORY, new SingleThreadedClaimStrategy(BUFFER_SIZE), new YieldingWaitStrategy()); private final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
// Path: src/performance/java/com/lmax/disruptor/support/ValueAdditionEventHandler.java // public final class ValueAdditionEventHandler implements EventHandler<ValueEvent> // { // private final PaddedLong value = new PaddedLong(); // private long count; // private CountDownLatch latch; // // public long getValue() // { // return value.get(); // } // // public void reset(final CountDownLatch latch, final long expectedCount) // { // value.set(0L); // this.latch = latch; // count = expectedCount; // } // // @Override // public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception // { // value.set(value.get() + event.getValue()); // // if (count == sequence) // { // latch.countDown(); // } // } // } // // Path: src/performance/java/com/lmax/disruptor/support/ValueEvent.java // public final class ValueEvent // { // private long value; // // public long getValue() // { // return value; // } // // public void setValue(final long value) // { // this.value = value; // } // // public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() // { // public ValueEvent newInstance() // { // return new ValueEvent(); // } // }; // } // Path: src/performance/java/com/lmax/disruptor/OnePublisherToOneProcessorUniCastBatchThroughputTest.java import com.lmax.disruptor.support.PerfTestUtil; import com.lmax.disruptor.support.ValueAdditionEventHandler; import com.lmax.disruptor.support.ValueEvent; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; /** * <pre> * UniCast a series of items between 1 publisher and 1 event processor. * This test illustrates the benefits of writing batches of 10 events * for exchange at a time. * * +----+ +-----+ * | P1 |--->| EP1 | * +----+ +-----+ * * * Queue Based: * ============ * * put take * +----+ +====+ +-----+ * | P1 |--->| Q1 |<---| EP1 | * +----+ +====+ +-----+ * * P1 - Publisher 1 * Q1 - Queue 1 * EP1 - EventProcessor 1 * * * Disruptor: * ========== * track to prevent wrap * +------------------+ * | | * | v * +----+ +====+ +====+ +-----+ * | P1 |--->| RB |<---| SB | | EP1 | * +----+ +====+ +====+ +-----+ * claim get ^ | * | | * +--------+ * waitFor * * P1 - Publisher 1 * RB - RingBuffer * SB - SequenceBarrier * EP1 - EventProcessor 1 * </pre> */ public final class OnePublisherToOneProcessorUniCastBatchThroughputTest extends AbstractPerfTestQueueVsDisruptor { private static final int BUFFER_SIZE = 1024 * 8; private static final long ITERATIONS = 1000L * 1000L * 100L; private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(); private final long expectedResult = PerfTestUtil.accumulatedAddition(ITERATIONS); /////////////////////////////////////////////////////////////////////////////////////////////// private final RingBuffer<ValueEvent> ringBuffer = new RingBuffer<ValueEvent>(ValueEvent.EVENT_FACTORY, new SingleThreadedClaimStrategy(BUFFER_SIZE), new YieldingWaitStrategy()); private final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
private final ValueAdditionEventHandler handler = new ValueAdditionEventHandler();
jbrisbin/disruptor
src/performance/java/com/lmax/disruptor/support/FizzBuzzEvent.java
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // }
import com.lmax.disruptor.EventFactory;
return value; } public void setValue(final long value) { fizz = false; buzz = false; this.value = value; } public boolean isFizz() { return fizz; } public void setFizz(final boolean fizz) { this.fizz = fizz; } public boolean isBuzz() { return buzz; } public void setBuzz(final boolean buzz) { this.buzz = buzz; }
// Path: src/main/java/com/lmax/disruptor/EventFactory.java // public interface EventFactory<T> // { // T newInstance(); // } // Path: src/performance/java/com/lmax/disruptor/support/FizzBuzzEvent.java import com.lmax.disruptor.EventFactory; return value; } public void setValue(final long value) { fizz = false; buzz = false; this.value = value; } public boolean isFizz() { return fizz; } public void setFizz(final boolean fizz) { this.fizz = fizz; } public boolean isBuzz() { return buzz; } public void setBuzz(final boolean buzz) { this.buzz = buzz; }
public final static EventFactory<FizzBuzzEvent> EVENT_FACTORY = new EventFactory<FizzBuzzEvent>()
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/dsl/DisruptorTest.java
// Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.*; import com.lmax.disruptor.*; import com.lmax.disruptor.support.TestEvent; import com.lmax.disruptor.dsl.stubs.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; import static java.lang.Thread.yield; import static java.util.concurrent.TimeUnit.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; @SuppressWarnings(value = {"ThrowableResultOfMethodCallIgnored", "unchecked"}) public class DisruptorTest { private static final int TIMEOUT_IN_SECONDS = 2;
// Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // } // Path: src/test/java/com/lmax/disruptor/dsl/DisruptorTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.*; import com.lmax.disruptor.*; import com.lmax.disruptor.support.TestEvent; import com.lmax.disruptor.dsl.stubs.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; import static java.lang.Thread.yield; import static java.util.concurrent.TimeUnit.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; @SuppressWarnings(value = {"ThrowableResultOfMethodCallIgnored", "unchecked"}) public class DisruptorTest { private static final int TIMEOUT_IN_SECONDS = 2;
private Disruptor<TestEvent> disruptor;
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/SequenceBarrierTest.java
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.util.Util; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; @RunWith(JMock.class) public final class SequenceBarrierTest { private Mockery context = new Mockery();
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/test/java/com/lmax/disruptor/SequenceBarrierTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.util.Util; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor; @RunWith(JMock.class) public final class SequenceBarrierTest { private Mockery context = new Mockery();
private RingBuffer<StubEvent> ringBuffer = new RingBuffer<StubEvent>(StubEvent.EVENT_FACTORY, 64);
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/SequenceBarrierTest.java
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.util.Util; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
will(returnValue(sequence1)); one(eventProcessor2).getSequence(); will(returnValue(sequence2)); one(eventProcessor3).getSequence(); will(returnValue(sequence3)); } }); SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(eventProcessor1.getSequence(), eventProcessor2.getSequence(), eventProcessor3.getSequence()); long completedWorkSequence = sequenceBarrier.waitFor(expectedWorkSequence); assertTrue(completedWorkSequence >= expectedWorkSequence); } @Test public void shouldWaitForWorkCompleteWhereAllWorkersAreBlockedOnRingBuffer() throws Exception { long expectedNumberMessages = 10; fillRingBuffer(expectedNumberMessages); final StubEventProcessor[] workers = new StubEventProcessor[3]; for (int i = 0, size = workers.length; i < size; i++) { workers[i] = new StubEventProcessor(); workers[i].setSequence(expectedNumberMessages - 1); }
// Path: src/test/java/com/lmax/disruptor/support/StubEvent.java // public final class StubEvent // { // private int value; // private String testString; // // public StubEvent(int i) // { // this.value = i; // } // // public void copy(StubEvent event) // { // value = event.value; // } // // public int getValue() // { // return value; // } // // public void setValue(int value) // { // this.value = value; // } // // public String getTestString() // { // return testString; // } // // public void setTestString(final String testString) // { // this.testString = testString; // } // // public final static EventFactory<StubEvent> EVENT_FACTORY = new EventFactory<StubEvent>() // { // public StubEvent newInstance() // { // return new StubEvent(-1); // } // }; // // @Override // public int hashCode() // { // final int prime = 31; // int result = 1; // result = prime * result + value; // return result; // } // // @Override // public boolean equals(Object obj) // { // if (this == obj) return true; // if (obj == null) return false; // if (getClass() != obj.getClass()) return false; // StubEvent other = (StubEvent)obj; // // return value == other.value; // } // } // // Path: src/main/java/com/lmax/disruptor/util/Util.java // public final class Util // { // /** // * Calculate the next power of 2, greater than or equal to x.<p> // * From Hacker's Delight, Chapter 3, Harry S. Warren Jr. // * // * @param x Value to round up // * @return The next power of 2 from x inclusive // */ // public static int ceilingNextPowerOfTwo(final int x) // { // return 1 << (32 - Integer.numberOfLeadingZeros(x - 1)); // } // // /** // * Get the minimum sequence from an array of {@link com.lmax.disruptor.Sequence}s. // * // * @param sequences to compare. // * @return the minimum sequence found or Long.MAX_VALUE if the array is empty. // */ // public static long getMinimumSequence(final Sequence[] sequences) // { // long minimum = Long.MAX_VALUE; // // for (Sequence sequence : sequences) // { // long value = sequence.get(); // minimum = minimum < value ? minimum : value; // } // // return minimum; // } // // /** // * Get an array of {@link Sequence}s for the passed {@link EventProcessor}s // * // * @param processors for which to get the sequences // * @return the array of {@link Sequence}s // */ // public static Sequence[] getSequencesFor(final EventProcessor... processors) // { // Sequence[] sequences = new Sequence[processors.length]; // for (int i = 0; i < sequences.length; i++) // { // sequences[i] = processors[i].getSequence(); // } // // return sequences; // } // } // Path: src/test/java/com/lmax/disruptor/SequenceBarrierTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.lmax.disruptor.support.StubEvent; import com.lmax.disruptor.util.Util; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; will(returnValue(sequence1)); one(eventProcessor2).getSequence(); will(returnValue(sequence2)); one(eventProcessor3).getSequence(); will(returnValue(sequence3)); } }); SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(eventProcessor1.getSequence(), eventProcessor2.getSequence(), eventProcessor3.getSequence()); long completedWorkSequence = sequenceBarrier.waitFor(expectedWorkSequence); assertTrue(completedWorkSequence >= expectedWorkSequence); } @Test public void shouldWaitForWorkCompleteWhereAllWorkersAreBlockedOnRingBuffer() throws Exception { long expectedNumberMessages = 10; fillRingBuffer(expectedNumberMessages); final StubEventProcessor[] workers = new StubEventProcessor[3]; for (int i = 0, size = workers.length; i < size; i++) { workers[i] = new StubEventProcessor(); workers[i].setSequence(expectedNumberMessages - 1); }
final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier(Util.getSequencesFor(workers));
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/dsl/EventProcessorRepositoryTest.java
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // }
import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.dsl.stubs.SleepingEventHandler; import com.lmax.disruptor.support.TestEvent; import org.jmock.Mockery; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; public class EventProcessorRepositoryTest { private final Mockery mockery = new Mockery();
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // } // Path: src/test/java/com/lmax/disruptor/dsl/EventProcessorRepositoryTest.java import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.dsl.stubs.SleepingEventHandler; import com.lmax.disruptor.support.TestEvent; import org.jmock.Mockery; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; public class EventProcessorRepositoryTest { private final Mockery mockery = new Mockery();
private EventProcessorRepository<TestEvent> eventProcessorRepository;
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/dsl/EventProcessorRepositoryTest.java
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // }
import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.dsl.stubs.SleepingEventHandler; import com.lmax.disruptor.support.TestEvent; import org.jmock.Mockery; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; public class EventProcessorRepositoryTest { private final Mockery mockery = new Mockery(); private EventProcessorRepository<TestEvent> eventProcessorRepository;
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // } // Path: src/test/java/com/lmax/disruptor/dsl/EventProcessorRepositoryTest.java import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.dsl.stubs.SleepingEventHandler; import com.lmax.disruptor.support.TestEvent; import org.jmock.Mockery; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; public class EventProcessorRepositoryTest { private final Mockery mockery = new Mockery(); private EventProcessorRepository<TestEvent> eventProcessorRepository;
private EventProcessor eventProcessor1;
jbrisbin/disruptor
src/test/java/com/lmax/disruptor/dsl/EventProcessorRepositoryTest.java
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // }
import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.dsl.stubs.SleepingEventHandler; import com.lmax.disruptor.support.TestEvent; import org.jmock.Mockery; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*;
/* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; public class EventProcessorRepositoryTest { private final Mockery mockery = new Mockery(); private EventProcessorRepository<TestEvent> eventProcessorRepository; private EventProcessor eventProcessor1; private EventProcessor eventProcessor2; private SleepingEventHandler handler1; private SleepingEventHandler handler2;
// Path: src/main/java/com/lmax/disruptor/SequenceBarrier.java // public interface SequenceBarrier // { // /** // * Wait for the given sequence to be available for consumption. // * // * @param sequence to wait for // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence) throws AlertException, InterruptedException; // // /** // * Wait for the given sequence to be available for consumption with a time out. // * // * @param sequence to wait for // * @param timeout value // * @param units for the timeout value // * @return the sequence up to which is available // * @throws AlertException if a status change has occurred for the Disruptor // * @throws InterruptedException if the thread needs awaking on a condition variable. // */ // long waitFor(long sequence, long timeout, TimeUnit units) throws AlertException, InterruptedException; // // /** // * Delegate a call to the {@link Sequencer#getCursor()} // * // * @return value of the cursor for entries that have been published. // */ // long getCursor(); // // /** // * The current alert status for the barrier. // * // * @return true if in alert otherwise false. // */ // boolean isAlerted(); // // /** // * Alert the {@link EventProcessor}s of a status change and stay in this status until cleared. // */ // void alert(); // // /** // * Clear the current alert status. // */ // void clearAlert(); // // /** // * Check if an alert has been raised and throw an {@link AlertException} if it has. // * // * @throws AlertException if alert has been raised. // */ // void checkAlert() throws AlertException; // } // // Path: src/main/java/com/lmax/disruptor/EventProcessor.java // public interface EventProcessor extends Runnable // { // /** // * Get a reference to the {@link Sequence} being used by this {@link EventProcessor}. // * // * @return reference to the {@link Sequence} for this {@link EventProcessor} // */ // Sequence getSequence(); // // /** // * Signal that this EventProcessor should stop when it has finished consuming at the next clean break. // * It will call {@link SequenceBarrier#alert()} to notify the thread to check status. // */ // void halt(); // } // // Path: src/test/java/com/lmax/disruptor/support/TestEvent.java // public final class TestEvent // { // @Override // public String toString() // { // return "Test Event"; // } // // public final static EventFactory<TestEvent> EVENT_FACTORY = new EventFactory<TestEvent>() // { // public TestEvent newInstance() // { // return new TestEvent(); // } // }; // } // Path: src/test/java/com/lmax/disruptor/dsl/EventProcessorRepositoryTest.java import com.lmax.disruptor.SequenceBarrier; import com.lmax.disruptor.EventProcessor; import com.lmax.disruptor.dsl.stubs.SleepingEventHandler; import com.lmax.disruptor.support.TestEvent; import org.jmock.Mockery; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; /* * Copyright 2011 LMAX Ltd. * * 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 com.lmax.disruptor.dsl; public class EventProcessorRepositoryTest { private final Mockery mockery = new Mockery(); private EventProcessorRepository<TestEvent> eventProcessorRepository; private EventProcessor eventProcessor1; private EventProcessor eventProcessor2; private SleepingEventHandler handler1; private SleepingEventHandler handler2;
private SequenceBarrier barrier1;
frosenberg/elasticsearch-nvd-river
src/main/java/gov/nist/scap/schema/cce/_0/CceType.java
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // }
import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import gov.nist.scap.schema.scap_core._0.ReferenceType;
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.cce._0; /** * <p>Java class for cceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="cceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="definition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="parameter" type="{http://scap.nist.gov/schema/cce/0.1}cceParameterType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="technical-mechanisms" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="references" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://scap.nist.gov/schema/cce/0.1}cceNamePatternType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cceType", propOrder = { "definition", "parameter", "technicalMechanisms", "references" }) public class CceType { protected String definition; protected List<CceParameterType> parameter; @XmlElement(name = "technical-mechanisms") protected List<String> technicalMechanisms;
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // } // Path: src/main/java/gov/nist/scap/schema/cce/_0/CceType.java import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import gov.nist.scap.schema.scap_core._0.ReferenceType; // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.cce._0; /** * <p>Java class for cceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="cceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="definition" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="parameter" type="{http://scap.nist.gov/schema/cce/0.1}cceParameterType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="technical-mechanisms" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="references" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://scap.nist.gov/schema/cce/0.1}cceNamePatternType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cceType", propOrder = { "definition", "parameter", "technicalMechanisms", "references" }) public class CceType { protected String definition; protected List<CceParameterType> parameter; @XmlElement(name = "technical-mechanisms") protected List<String> technicalMechanisms;
protected List<ReferenceType> references;
frosenberg/elasticsearch-nvd-river
src/main/java/org/elasticsearch/plugin/river/nvd/NvdRiverPlugin.java
// Path: src/main/java/org/elasticsearch/river/nvd/NvdRiverModule.java // public class NvdRiverModule extends AbstractModule { // // @Override // protected void configure() { // bind(River.class).to(NvdRiver.class).asEagerSingleton(); // } // // }
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Module; import org.elasticsearch.plugins.AbstractPlugin; import org.elasticsearch.river.RiversModule; import org.elasticsearch.river.nvd.NvdRiverModule;
package org.elasticsearch.plugin.river.nvd; /** * @author Florian Rosenberg */ public class NvdRiverPlugin extends AbstractPlugin { @Inject public NvdRiverPlugin() { } @Override public String name() { return "river-nvd"; } @Override public String description() { return "River NVD Plugin"; } @Override public void processModule(Module module) { if (module instanceof RiversModule) {
// Path: src/main/java/org/elasticsearch/river/nvd/NvdRiverModule.java // public class NvdRiverModule extends AbstractModule { // // @Override // protected void configure() { // bind(River.class).to(NvdRiver.class).asEagerSingleton(); // } // // } // Path: src/main/java/org/elasticsearch/plugin/river/nvd/NvdRiverPlugin.java import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Module; import org.elasticsearch.plugins.AbstractPlugin; import org.elasticsearch.river.RiversModule; import org.elasticsearch.river.nvd.NvdRiverModule; package org.elasticsearch.plugin.river.nvd; /** * @author Florian Rosenberg */ public class NvdRiverPlugin extends AbstractPlugin { @Inject public NvdRiverPlugin() { } @Override public String name() { return "river-nvd"; } @Override public String description() { return "River NVD Plugin"; } @Override public void processModule(Module module) { if (module instanceof RiversModule) {
((RiversModule) module).registerRiver("nvd", NvdRiverModule.class);
frosenberg/elasticsearch-nvd-river
src/main/java/gov/nist/scap/schema/vulnerability/_0/ToolConfigurationType.java
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/CheckReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "checkReferenceType") // public class CheckReferenceType { // // @XmlAttribute(name = "system", required = true) // @XmlSchemaType(name = "anyURI") // protected String system; // @XmlAttribute(name = "href", required = true) // @XmlSchemaType(name = "anyURI") // protected String href; // @XmlAttribute(name = "name") // @XmlJavaTypeAdapter(CollapsedStringAdapter.class) // @XmlSchemaType(name = "token") // protected String name; // // /** // * Gets the value of the system property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getSystem() { // return system; // } // // /** // * Sets the value of the system property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setSystem(String value) { // this.system = value; // } // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // /** // * Gets the value of the name property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getName() { // return name; // } // // /** // * Sets the value of the name property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setName(String value) { // this.name = value; // } // // }
import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import gov.nist.scap.schema.scap_core._0.CheckReferenceType;
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.vulnerability._0; /** * <p>Java class for toolConfigurationType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="toolConfigurationType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name" type="{http://scap.nist.gov/schema/scap-core/0.1}cpeNamePatternType" minOccurs="0"/> * &lt;element name="definition" type="{http://scap.nist.gov/schema/scap-core/0.1}checkReferenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "toolConfigurationType", propOrder = { "name", "definition" }) public class ToolConfigurationType { @XmlSchemaType(name = "anyURI") protected String name;
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/CheckReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "checkReferenceType") // public class CheckReferenceType { // // @XmlAttribute(name = "system", required = true) // @XmlSchemaType(name = "anyURI") // protected String system; // @XmlAttribute(name = "href", required = true) // @XmlSchemaType(name = "anyURI") // protected String href; // @XmlAttribute(name = "name") // @XmlJavaTypeAdapter(CollapsedStringAdapter.class) // @XmlSchemaType(name = "token") // protected String name; // // /** // * Gets the value of the system property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getSystem() { // return system; // } // // /** // * Sets the value of the system property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setSystem(String value) { // this.system = value; // } // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // /** // * Gets the value of the name property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getName() { // return name; // } // // /** // * Sets the value of the name property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setName(String value) { // this.name = value; // } // // } // Path: src/main/java/gov/nist/scap/schema/vulnerability/_0/ToolConfigurationType.java import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import gov.nist.scap.schema.scap_core._0.CheckReferenceType; // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.vulnerability._0; /** * <p>Java class for toolConfigurationType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="toolConfigurationType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="name" type="{http://scap.nist.gov/schema/scap-core/0.1}cpeNamePatternType" minOccurs="0"/> * &lt;element name="definition" type="{http://scap.nist.gov/schema/scap-core/0.1}checkReferenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "toolConfigurationType", propOrder = { "name", "definition" }) public class ToolConfigurationType { @XmlSchemaType(name = "anyURI") protected String name;
protected List<CheckReferenceType> definition;
frosenberg/elasticsearch-nvd-river
src/main/java/gov/nist/scap/schema/vulnerability/_0/VulnerabilityReferenceType.java
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/NotesType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "notesType", propOrder = { // "note" // }) // public class NotesType { // // @XmlElement(required = true) // protected List<TextType> note; // // /** // * Gets the value of the note property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the note property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getNote().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link TextType } // * // * // */ // public List<TextType> getNote() { // if (note == null) { // note = new ArrayList<TextType>(); // } // return this.note; // } // // } // // Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import gov.nist.scap.schema.scap_core._0.NotesType; import gov.nist.scap.schema.scap_core._0.ReferenceType;
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.vulnerability._0; /** * Extends the base "reference" class by adding the ability to specify which kind (within the vulnerability model) of reference it is. See "Vulnerability_Reference_Category_List" enumeration. * * <p>Java class for vulnerabilityReferenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="vulnerabilityReferenceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="source" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="reference" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType"/> * &lt;element name="notes" type="{http://scap.nist.gov/schema/scap-core/0.1}notesType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute ref="{http://www.w3.org/XML/1998/namespace}lang default="en""/> * &lt;attribute name="reference_type" use="required" type="{http://scap.nist.gov/schema/vulnerability/0.4}vulnerabilityReferenceCategoryEnumType" /> * &lt;attribute name="deprecated" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "vulnerabilityReferenceType", propOrder = { "source", "reference", "notes" }) public class VulnerabilityReferenceType { protected String source; @XmlElement(required = true)
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/NotesType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "notesType", propOrder = { // "note" // }) // public class NotesType { // // @XmlElement(required = true) // protected List<TextType> note; // // /** // * Gets the value of the note property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the note property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getNote().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link TextType } // * // * // */ // public List<TextType> getNote() { // if (note == null) { // note = new ArrayList<TextType>(); // } // return this.note; // } // // } // // Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // } // Path: src/main/java/gov/nist/scap/schema/vulnerability/_0/VulnerabilityReferenceType.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import gov.nist.scap.schema.scap_core._0.NotesType; import gov.nist.scap.schema.scap_core._0.ReferenceType; // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.vulnerability._0; /** * Extends the base "reference" class by adding the ability to specify which kind (within the vulnerability model) of reference it is. See "Vulnerability_Reference_Category_List" enumeration. * * <p>Java class for vulnerabilityReferenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="vulnerabilityReferenceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="source" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="reference" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType"/> * &lt;element name="notes" type="{http://scap.nist.gov/schema/scap-core/0.1}notesType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute ref="{http://www.w3.org/XML/1998/namespace}lang default="en""/> * &lt;attribute name="reference_type" use="required" type="{http://scap.nist.gov/schema/vulnerability/0.4}vulnerabilityReferenceCategoryEnumType" /> * &lt;attribute name="deprecated" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "vulnerabilityReferenceType", propOrder = { "source", "reference", "notes" }) public class VulnerabilityReferenceType { protected String source; @XmlElement(required = true)
protected ReferenceType reference;
frosenberg/elasticsearch-nvd-river
src/main/java/gov/nist/scap/schema/vulnerability/_0/VulnerabilityReferenceType.java
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/NotesType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "notesType", propOrder = { // "note" // }) // public class NotesType { // // @XmlElement(required = true) // protected List<TextType> note; // // /** // * Gets the value of the note property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the note property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getNote().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link TextType } // * // * // */ // public List<TextType> getNote() { // if (note == null) { // note = new ArrayList<TextType>(); // } // return this.note; // } // // } // // Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import gov.nist.scap.schema.scap_core._0.NotesType; import gov.nist.scap.schema.scap_core._0.ReferenceType;
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.vulnerability._0; /** * Extends the base "reference" class by adding the ability to specify which kind (within the vulnerability model) of reference it is. See "Vulnerability_Reference_Category_List" enumeration. * * <p>Java class for vulnerabilityReferenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="vulnerabilityReferenceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="source" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="reference" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType"/> * &lt;element name="notes" type="{http://scap.nist.gov/schema/scap-core/0.1}notesType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute ref="{http://www.w3.org/XML/1998/namespace}lang default="en""/> * &lt;attribute name="reference_type" use="required" type="{http://scap.nist.gov/schema/vulnerability/0.4}vulnerabilityReferenceCategoryEnumType" /> * &lt;attribute name="deprecated" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "vulnerabilityReferenceType", propOrder = { "source", "reference", "notes" }) public class VulnerabilityReferenceType { protected String source; @XmlElement(required = true) protected ReferenceType reference;
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/NotesType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "notesType", propOrder = { // "note" // }) // public class NotesType { // // @XmlElement(required = true) // protected List<TextType> note; // // /** // * Gets the value of the note property. // * // * <p> // * This accessor method returns a reference to the live list, // * not a snapshot. Therefore any modification you make to the // * returned list will be present inside the JAXB object. // * This is why there is not a <CODE>set</CODE> method for the note property. // * // * <p> // * For example, to add a new item, do as follows: // * <pre> // * getNote().add(newItem); // * </pre> // * // * // * <p> // * Objects of the following type(s) are allowed in the list // * {@link TextType } // * // * // */ // public List<TextType> getNote() { // if (note == null) { // note = new ArrayList<TextType>(); // } // return this.note; // } // // } // // Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // } // Path: src/main/java/gov/nist/scap/schema/vulnerability/_0/VulnerabilityReferenceType.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import gov.nist.scap.schema.scap_core._0.NotesType; import gov.nist.scap.schema.scap_core._0.ReferenceType; // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.vulnerability._0; /** * Extends the base "reference" class by adding the ability to specify which kind (within the vulnerability model) of reference it is. See "Vulnerability_Reference_Category_List" enumeration. * * <p>Java class for vulnerabilityReferenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="vulnerabilityReferenceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="source" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="reference" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType"/> * &lt;element name="notes" type="{http://scap.nist.gov/schema/scap-core/0.1}notesType" minOccurs="0"/> * &lt;/sequence> * &lt;attribute ref="{http://www.w3.org/XML/1998/namespace}lang default="en""/> * &lt;attribute name="reference_type" use="required" type="{http://scap.nist.gov/schema/vulnerability/0.4}vulnerabilityReferenceCategoryEnumType" /> * &lt;attribute name="deprecated" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "vulnerabilityReferenceType", propOrder = { "source", "reference", "notes" }) public class VulnerabilityReferenceType { protected String source; @XmlElement(required = true) protected ReferenceType reference;
protected NotesType notes;
frosenberg/elasticsearch-nvd-river
src/main/java/gov/nist/scap/schema/cve/_0/CveType.java
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // }
import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import gov.nist.scap.schema.scap_core._0.ReferenceType;
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.cve._0; /** * <p>Java class for cveType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="cveType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="status" type="{http://scap.nist.gov/schema/cve/0.1}cveStatus" minOccurs="0"/> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="references" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://scap.nist.gov/schema/cve/0.1}cveNamePatternType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cveType", propOrder = { "status", "description", "references" }) public class CveType { @XmlSchemaType(name = "token") protected CveStatus status; protected String description;
// Path: src/main/java/gov/nist/scap/schema/scap_core/_0/ReferenceType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "referenceType") // public class ReferenceType // extends TextType // { // // @XmlAttribute(name = "href") // @XmlSchemaType(name = "anyURI") // protected String href; // // /** // * Gets the value of the href property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getHref() { // return href; // } // // /** // * Sets the value of the href property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setHref(String value) { // this.href = value; // } // // } // Path: src/main/java/gov/nist/scap/schema/cve/_0/CveType.java import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import gov.nist.scap.schema.scap_core._0.ReferenceType; // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.cve._0; /** * <p>Java class for cveType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="cveType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="status" type="{http://scap.nist.gov/schema/cve/0.1}cveStatus" minOccurs="0"/> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="references" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://scap.nist.gov/schema/cve/0.1}cveNamePatternType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cveType", propOrder = { "status", "description", "references" }) public class CveType { @XmlSchemaType(name = "token") protected CveStatus status; protected String description;
protected List<ReferenceType> references;
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/data/MessageHandlerInfoBMPBean.java
// Path: src/java/is/idega/idegaweb/egov/message/business/MessagePdfHandler.java // public interface MessagePdfHandler{ // // /** // * Creates the content of the open document referenced by the context // * @param dpc // * @throws ContentCreationException // */ // public void createMessageContent(DocumentPrintContext dpc) throws ContentCreationException; // /** // * Returns a unique code name identifying this handler // * @return // */ // public String getHandlerCode(); // // }
import com.idega.data.GenericEntity; import is.idega.idegaweb.egov.message.business.MessagePdfHandler; import com.idega.core.component.data.ICObject;
addAttribute(HANDLER_CODE, "Code", String.class, 20); this.setAsPrimaryKey(HANDLER_CODE, true); addManyToOneRelationship(OBJECT_ID, ICObject.class); } public Class getPrimaryKeyClass() { return String.class; } public String getIDColumnName() { return HANDLER_CODE; } public ICObject getICObject() { return (ICObject) this.getColumnValue(OBJECT_ID); } public void setICObject(ICObject object) { setColumn(OBJECT_ID, object); } public String getHandlerCode() { return getStringColumnValue(HANDLER_CODE); } public void setHandlerCode(String code) { this.setColumn(HANDLER_CODE, code); }
// Path: src/java/is/idega/idegaweb/egov/message/business/MessagePdfHandler.java // public interface MessagePdfHandler{ // // /** // * Creates the content of the open document referenced by the context // * @param dpc // * @throws ContentCreationException // */ // public void createMessageContent(DocumentPrintContext dpc) throws ContentCreationException; // /** // * Returns a unique code name identifying this handler // * @return // */ // public String getHandlerCode(); // // } // Path: src/java/is/idega/idegaweb/egov/message/data/MessageHandlerInfoBMPBean.java import com.idega.data.GenericEntity; import is.idega.idegaweb.egov.message.business.MessagePdfHandler; import com.idega.core.component.data.ICObject; addAttribute(HANDLER_CODE, "Code", String.class, 20); this.setAsPrimaryKey(HANDLER_CODE, true); addManyToOneRelationship(OBJECT_ID, ICObject.class); } public Class getPrimaryKeyClass() { return String.class; } public String getIDColumnName() { return HANDLER_CODE; } public ICObject getICObject() { return (ICObject) this.getColumnValue(OBJECT_ID); } public void setICObject(ICObject object) { setColumn(OBJECT_ID, object); } public String getHandlerCode() { return getStringColumnValue(HANDLER_CODE); } public void setHandlerCode(String code) { this.setColumn(HANDLER_CODE, code); }
public MessagePdfHandler getHandler() {
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/business/MessageContentServiceBean.java
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageContent.java // public interface MessageContent extends IDOEntity { // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCategory // */ // public void setCategory(String category); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCategory // */ // public String getCategory(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setContentName // */ // public void setContentName(String name); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getContentName // */ // public String getContentName(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setContentBody // */ // public void setContentBody(String body); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getContentBody // */ // public String getContentBody(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCreated // */ // public void setCreated(Timestamp stamp); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCreated // */ // public Timestamp getCreated(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setUpdated // */ // public void setUpdated(Timestamp stamp); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getUpdated // */ // public Timestamp getUpdated(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCreator // */ // public void setCreator(User user); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCreator // */ // public void setCreator(Integer userID); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCreatorID // */ // public Integer getCreatorID(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCreator // */ // public User getCreator(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setLocale // */ // public void setLocale(ICLocale locale); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setLocaleId // */ // public void setLocaleId(Locale locale); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getLocaleString // */ // public String getLocaleString(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getLocale // */ // public Locale getLocale(); // // } // // Path: src/java/is/idega/idegaweb/egov/message/data/MessageContentHome.java // public interface MessageContentHome extends IDOHome { // // public MessageContent create() throws javax.ejb.CreateException; // // public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindAll // */ // public Collection findAll() throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategory // */ // public Collection findByCategory(String category) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategoryAndLocale // */ // public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByValue // */ // public Collection findByValue(MessageContentValue value) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbHomeGetFindQuery // */ // public SelectQuery getFindQuery(MessageContentValue value); // // }
import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import is.idega.idegaweb.egov.message.data.MessageContent; import is.idega.idegaweb.egov.message.data.MessageContentHome; import com.idega.business.IBOServiceBean; import com.idega.util.IWTimestamp;
/* * $Id$ Created on 7.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.business; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public class MessageContentServiceBean extends IBOServiceBean implements MessageContentService { public Collection getValues(MessageContentValue value) throws RemoteException, FinderException { Collection contents = getHome().findByValue(value); ArrayList values = new ArrayList(contents.size()); for (Iterator iter = contents.iterator(); iter.hasNext();) {
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageContent.java // public interface MessageContent extends IDOEntity { // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCategory // */ // public void setCategory(String category); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCategory // */ // public String getCategory(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setContentName // */ // public void setContentName(String name); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getContentName // */ // public String getContentName(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setContentBody // */ // public void setContentBody(String body); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getContentBody // */ // public String getContentBody(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCreated // */ // public void setCreated(Timestamp stamp); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCreated // */ // public Timestamp getCreated(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setUpdated // */ // public void setUpdated(Timestamp stamp); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getUpdated // */ // public Timestamp getUpdated(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCreator // */ // public void setCreator(User user); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setCreator // */ // public void setCreator(Integer userID); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCreatorID // */ // public Integer getCreatorID(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getCreator // */ // public User getCreator(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setLocale // */ // public void setLocale(ICLocale locale); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#setLocaleId // */ // public void setLocaleId(Locale locale); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getLocaleString // */ // public String getLocaleString(); // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#getLocale // */ // public Locale getLocale(); // // } // // Path: src/java/is/idega/idegaweb/egov/message/data/MessageContentHome.java // public interface MessageContentHome extends IDOHome { // // public MessageContent create() throws javax.ejb.CreateException; // // public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindAll // */ // public Collection findAll() throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategory // */ // public Collection findByCategory(String category) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategoryAndLocale // */ // public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByValue // */ // public Collection findByValue(MessageContentValue value) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbHomeGetFindQuery // */ // public SelectQuery getFindQuery(MessageContentValue value); // // } // Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentServiceBean.java import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import is.idega.idegaweb.egov.message.data.MessageContent; import is.idega.idegaweb.egov.message.data.MessageContentHome; import com.idega.business.IBOServiceBean; import com.idega.util.IWTimestamp; /* * $Id$ Created on 7.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.business; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public class MessageContentServiceBean extends IBOServiceBean implements MessageContentService { public Collection getValues(MessageContentValue value) throws RemoteException, FinderException { Collection contents = getHome().findByValue(value); ArrayList values = new ArrayList(contents.size()); for (Iterator iter = contents.iterator(); iter.hasNext();) {
values.add(getValue((MessageContent) iter.next()));
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/data/MessageContentHome.java
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentValue.java // public class MessageContentValue { // // public static final String PARAMETER_TYPE = "msgctp"; // public static final String PARAMETER_LOCALE = "msgctl"; // public static final String PARAMETER_ID = "msgctid"; // // public Integer ID; // public String type; // public String name; // public String body; // public Integer creatorID; // public Date updated; // public Date created; // public Locale locale; // // /** // * Gets a String:String map of parameters neccessary to delete a MessageContent // * @param value // * @return // */ // public Map getDeleteParameters() { // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to edit a MessageContent // * @param value // * @return // */ // public Map getEditParameters(){ // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to create a MessageContent // * @param value // * @return // */ // public Map getCreateParameters(){ // HashMap map = new HashMap(1); // map.put(PARAMETER_TYPE,this.type); // return map; // } // }
import java.util.Collection; import javax.ejb.FinderException; import is.idega.idegaweb.egov.message.business.MessageContentValue; import com.idega.data.IDOHome; import com.idega.data.query.SelectQuery;
/* * $Id$ Created on 8.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.data; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public interface MessageContentHome extends IDOHome { public MessageContent create() throws javax.ejb.CreateException; public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindAll */ public Collection findAll() throws FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategory */ public Collection findByCategory(String category) throws FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategoryAndLocale */ public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByValue */
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentValue.java // public class MessageContentValue { // // public static final String PARAMETER_TYPE = "msgctp"; // public static final String PARAMETER_LOCALE = "msgctl"; // public static final String PARAMETER_ID = "msgctid"; // // public Integer ID; // public String type; // public String name; // public String body; // public Integer creatorID; // public Date updated; // public Date created; // public Locale locale; // // /** // * Gets a String:String map of parameters neccessary to delete a MessageContent // * @param value // * @return // */ // public Map getDeleteParameters() { // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to edit a MessageContent // * @param value // * @return // */ // public Map getEditParameters(){ // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to create a MessageContent // * @param value // * @return // */ // public Map getCreateParameters(){ // HashMap map = new HashMap(1); // map.put(PARAMETER_TYPE,this.type); // return map; // } // } // Path: src/java/is/idega/idegaweb/egov/message/data/MessageContentHome.java import java.util.Collection; import javax.ejb.FinderException; import is.idega.idegaweb.egov.message.business.MessageContentValue; import com.idega.data.IDOHome; import com.idega.data.query.SelectQuery; /* * $Id$ Created on 8.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.data; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public interface MessageContentHome extends IDOHome { public MessageContent create() throws javax.ejb.CreateException; public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindAll */ public Collection findAll() throws FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategory */ public Collection findByCategory(String category) throws FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategoryAndLocale */ public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException; /** * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByValue */
public Collection findByValue(MessageContentValue value) throws FinderException;
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/data/MessageContentHomeImpl.java
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentValue.java // public class MessageContentValue { // // public static final String PARAMETER_TYPE = "msgctp"; // public static final String PARAMETER_LOCALE = "msgctl"; // public static final String PARAMETER_ID = "msgctid"; // // public Integer ID; // public String type; // public String name; // public String body; // public Integer creatorID; // public Date updated; // public Date created; // public Locale locale; // // /** // * Gets a String:String map of parameters neccessary to delete a MessageContent // * @param value // * @return // */ // public Map getDeleteParameters() { // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to edit a MessageContent // * @param value // * @return // */ // public Map getEditParameters(){ // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to create a MessageContent // * @param value // * @return // */ // public Map getCreateParameters(){ // HashMap map = new HashMap(1); // map.put(PARAMETER_TYPE,this.type); // return map; // } // }
import java.util.Collection; import javax.ejb.FinderException; import is.idega.idegaweb.egov.message.business.MessageContentValue; import com.idega.data.IDOFactory; import com.idega.data.query.SelectQuery;
/* * $Id$ Created on 8.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.data; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public class MessageContentHomeImpl extends IDOFactory implements MessageContentHome { protected Class getEntityInterfaceClass() { return MessageContent.class; } public MessageContent create() throws javax.ejb.CreateException { return (MessageContent) super.createIDO(); } public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException { return (MessageContent) super.findByPrimaryKeyIDO(pk); } public Collection findAll() throws FinderException { com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((MessageContentBMPBean) entity).ejbFindAll(); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public Collection findByCategory(String category) throws FinderException { com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((MessageContentBMPBean) entity).ejbFindByCategory(category); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException { com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((MessageContentBMPBean) entity).ejbFindByCategoryAndLocale(category, locale); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); }
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentValue.java // public class MessageContentValue { // // public static final String PARAMETER_TYPE = "msgctp"; // public static final String PARAMETER_LOCALE = "msgctl"; // public static final String PARAMETER_ID = "msgctid"; // // public Integer ID; // public String type; // public String name; // public String body; // public Integer creatorID; // public Date updated; // public Date created; // public Locale locale; // // /** // * Gets a String:String map of parameters neccessary to delete a MessageContent // * @param value // * @return // */ // public Map getDeleteParameters() { // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to edit a MessageContent // * @param value // * @return // */ // public Map getEditParameters(){ // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to create a MessageContent // * @param value // * @return // */ // public Map getCreateParameters(){ // HashMap map = new HashMap(1); // map.put(PARAMETER_TYPE,this.type); // return map; // } // } // Path: src/java/is/idega/idegaweb/egov/message/data/MessageContentHomeImpl.java import java.util.Collection; import javax.ejb.FinderException; import is.idega.idegaweb.egov.message.business.MessageContentValue; import com.idega.data.IDOFactory; import com.idega.data.query.SelectQuery; /* * $Id$ Created on 8.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.data; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public class MessageContentHomeImpl extends IDOFactory implements MessageContentHome { protected Class getEntityInterfaceClass() { return MessageContent.class; } public MessageContent create() throws javax.ejb.CreateException { return (MessageContent) super.createIDO(); } public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException { return (MessageContent) super.findByPrimaryKeyIDO(pk); } public Collection findAll() throws FinderException { com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((MessageContentBMPBean) entity).ejbFindAll(); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public Collection findByCategory(String category) throws FinderException { com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((MessageContentBMPBean) entity).ejbFindByCategory(category); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); } public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException { com.idega.data.IDOEntity entity = this.idoCheckOutPooledEntity(); java.util.Collection ids = ((MessageContentBMPBean) entity).ejbFindByCategoryAndLocale(category, locale); this.idoCheckInPooledEntity(entity); return this.getEntityCollectionForPrimaryKeys(ids); }
public Collection findByValue(MessageContentValue value) throws FinderException {
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/printing/business/DocumentPrintContext.java
// Path: src/java/is/idega/idegaweb/egov/message/data/PrintMessage.java // public interface PrintMessage extends Message { // // public String getPrintType(); // // /** // * Returns a reference code for message content used by content generators // * // * @return // */ // public void setMessageData(com.idega.core.file.data.ICFile p0); // // public void setMessageData(int p0); // // public void setMessageBulkData(com.idega.core.file.data.ICFile p0); // // public void setMessageBulkData(int p0); // // public int getMessageDataFileID(); // // public int getMessageBulkDataFileID(); // // public boolean isPrinted(); // }
import is.idega.idegaweb.egov.message.data.PrintMessage; import java.util.Locale; import java.util.Map; import com.idega.idegaweb.IWApplicationContext; import com.idega.user.data.User; import com.lowagie.text.Document; import com.lowagie.text.pdf.PdfWriter;
/* * Created on Jan 8, 2004 * */ package is.idega.idegaweb.egov.printing.business; /** * DocumentPrintContext * * @author aron * @version 1.0 */ public class DocumentPrintContext { private Document document = null; private PdfWriter pdfWriter = null; private Locale locale = null;
// Path: src/java/is/idega/idegaweb/egov/message/data/PrintMessage.java // public interface PrintMessage extends Message { // // public String getPrintType(); // // /** // * Returns a reference code for message content used by content generators // * // * @return // */ // public void setMessageData(com.idega.core.file.data.ICFile p0); // // public void setMessageData(int p0); // // public void setMessageBulkData(com.idega.core.file.data.ICFile p0); // // public void setMessageBulkData(int p0); // // public int getMessageDataFileID(); // // public int getMessageBulkDataFileID(); // // public boolean isPrinted(); // } // Path: src/java/is/idega/idegaweb/egov/printing/business/DocumentPrintContext.java import is.idega.idegaweb.egov.message.data.PrintMessage; import java.util.Locale; import java.util.Map; import com.idega.idegaweb.IWApplicationContext; import com.idega.user.data.User; import com.lowagie.text.Document; import com.lowagie.text.pdf.PdfWriter; /* * Created on Jan 8, 2004 * */ package is.idega.idegaweb.egov.printing.business; /** * DocumentPrintContext * * @author aron * @version 1.0 */ public class DocumentPrintContext { private Document document = null; private PdfWriter pdfWriter = null; private Locale locale = null;
private PrintMessage msg = null;
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/printing/business/MessageLetterContext.java
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageConstants.java // public class MessageConstants { // // public final static String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.message"; // // public static final String TYPE_USER_MESSAGE = "SYMEDAN"; // public static final String TYPE_SYSTEM_PRINT_MAIL_MESSAGE = "SYMEBRV"; // // public static final String CAN_SEND_EMAIL = "can_send_email"; // }
import is.idega.idegaweb.egov.message.business.MessageConstants; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.idega.block.pdf.business.PrintingContext; import com.idega.block.pdf.business.PrintingContextImpl; import com.idega.block.process.message.data.Message; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.core.location.data.Address; import com.idega.idegaweb.IWApplicationContext; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.idegaweb.IWUserContext; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.util.text.TextSoap; import com.idega.xml.XMLDocument; import com.idega.xml.XMLElement; import com.idega.xml.XMLOutput;
} protected XMLDocument getTemplateXMLDocument() { XMLDocument doc = getBasicXMLDocument(); XMLElement document = doc.getRootElement(); XMLElement subject = new XMLElement("paragraph"); subject.addContent("${msg.subject}"); document.addContent(subject); XMLElement body = new XMLElement("paragraph"); body.setAttribute("halign", "justified"); body.addContent("${msg.body}"); document.addContent(body); return doc; } protected XMLDocument getBasicXMLDocument() { XMLElement document = new XMLElement("document"); document.setAttribute("size", "A4"); document.setAttribute("margin-left", "25"); document.setAttribute("margin-right", "25"); document.setAttribute("margin-top", "25"); document.setAttribute("margin-bottom", "25"); XMLDocument doc = new XMLDocument(document); return doc; } protected String getBundleIdentifier() {
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageConstants.java // public class MessageConstants { // // public final static String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.message"; // // public static final String TYPE_USER_MESSAGE = "SYMEDAN"; // public static final String TYPE_SYSTEM_PRINT_MAIL_MESSAGE = "SYMEBRV"; // // public static final String CAN_SEND_EMAIL = "can_send_email"; // } // Path: src/java/is/idega/idegaweb/egov/printing/business/MessageLetterContext.java import is.idega.idegaweb.egov.message.business.MessageConstants; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.idega.block.pdf.business.PrintingContext; import com.idega.block.pdf.business.PrintingContextImpl; import com.idega.block.process.message.data.Message; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.core.location.data.Address; import com.idega.idegaweb.IWApplicationContext; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.idegaweb.IWUserContext; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.util.text.TextSoap; import com.idega.xml.XMLDocument; import com.idega.xml.XMLElement; import com.idega.xml.XMLOutput; } protected XMLDocument getTemplateXMLDocument() { XMLDocument doc = getBasicXMLDocument(); XMLElement document = doc.getRootElement(); XMLElement subject = new XMLElement("paragraph"); subject.addContent("${msg.subject}"); document.addContent(subject); XMLElement body = new XMLElement("paragraph"); body.setAttribute("halign", "justified"); body.addContent("${msg.body}"); document.addContent(body); return doc; } protected XMLDocument getBasicXMLDocument() { XMLElement document = new XMLElement("document"); document.setAttribute("size", "A4"); document.setAttribute("margin-left", "25"); document.setAttribute("margin-right", "25"); document.setAttribute("margin-top", "25"); document.setAttribute("margin-bottom", "25"); XMLDocument doc = new XMLDocument(document); return doc; } protected String getBundleIdentifier() {
return MessageConstants.IW_BUNDLE_IDENTIFIER;
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/business/MessageContentService.java
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageContentHome.java // public interface MessageContentHome extends IDOHome { // // public MessageContent create() throws javax.ejb.CreateException; // // public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindAll // */ // public Collection findAll() throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategory // */ // public Collection findByCategory(String category) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategoryAndLocale // */ // public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByValue // */ // public Collection findByValue(MessageContentValue value) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbHomeGetFindQuery // */ // public SelectQuery getFindQuery(MessageContentValue value); // // }
import java.rmi.RemoteException; import java.util.Collection; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import is.idega.idegaweb.egov.message.data.MessageContentHome; import com.idega.business.IBOService;
/* * $Id$ Created on 8.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.business; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public interface MessageContentService extends IBOService { /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#getValues */ public Collection getValues(MessageContentValue value) throws RemoteException, FinderException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#storeValue */ public MessageContentValue storeValue(MessageContentValue value) throws FinderException, RemoteException, CreateException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#removeValue */ public void removeValue(Integer ID) throws RemoteException, RemoveException, FinderException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#getValue */ public MessageContentValue getValue(Integer valueID) throws RemoteException, FinderException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#getHome */
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageContentHome.java // public interface MessageContentHome extends IDOHome { // // public MessageContent create() throws javax.ejb.CreateException; // // public MessageContent findByPrimaryKey(Object pk) throws javax.ejb.FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindAll // */ // public Collection findAll() throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategory // */ // public Collection findByCategory(String category) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByCategoryAndLocale // */ // public Collection findByCategoryAndLocale(String category, Integer locale) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbFindByValue // */ // public Collection findByValue(MessageContentValue value) throws FinderException; // // /** // * @see se.idega.idegaweb.commune.message.data.MessageContentBMPBean#ejbHomeGetFindQuery // */ // public SelectQuery getFindQuery(MessageContentValue value); // // } // Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentService.java import java.rmi.RemoteException; import java.util.Collection; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import is.idega.idegaweb.egov.message.data.MessageContentHome; import com.idega.business.IBOService; /* * $Id$ Created on 8.10.2004 * * Copyright (C) 2004 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.message.business; /** * * Last modified: $Date$ by $Author$ * * @author <a href="mailto:aron@idega.com">aron</a> * @version $Revision$ */ public interface MessageContentService extends IBOService { /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#getValues */ public Collection getValues(MessageContentValue value) throws RemoteException, FinderException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#storeValue */ public MessageContentValue storeValue(MessageContentValue value) throws FinderException, RemoteException, CreateException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#removeValue */ public void removeValue(Integer ID) throws RemoteException, RemoveException, FinderException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#getValue */ public MessageContentValue getValue(Integer valueID) throws RemoteException, FinderException; /** * @see se.idega.idegaweb.commune.message.business.MessageContentServiceBean#getHome */
public MessageContentHome getHome() throws RemoteException;
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/business/MessageSessionBean.java
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiver.java // public interface MessageReceiver extends IDOEntity, User { // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveEmails // */ // public boolean receiveEmails(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveEmails // */ // public void setReceiveEmails(boolean receiveEmails); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveMessagesToBox // */ // public boolean receiveMessagesToBox(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveMessagesToBox // */ // public void setReceiveMessagesToBox(boolean receiveMessages); // } // // Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiverHome.java // public interface MessageReceiverHome extends IDOHome { // // public MessageReceiver create() throws CreateException; // // public MessageReceiver findByPrimaryKey(Object pk) throws FinderException; // }
import is.idega.idegaweb.egov.message.data.MessageReceiver; import is.idega.idegaweb.egov.message.data.MessageReceiverHome; import java.util.Collection; import javax.ejb.FinderException; import com.idega.business.IBOSessionBean; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWPropertyList; import com.idega.user.business.UserProperties; import com.idega.user.data.User;
package is.idega.idegaweb.egov.message.business; /** * @author Laddi * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. To enable and disable the creation of type * comments go to Window>Preferences>Java>Code Generation. */ public class MessageSessionBean extends IBOSessionBean implements MessageSession { public static final String MESSAGE_PROPERTIES = "message_properties"; public static final String USER_PROP_SEND_TO_MESSAGE_BOX = "msg_send_box"; public static final String USER_PROP_SEND_TO_EMAIL = "msg_send_email"; public boolean getIfUserCanReceiveEmails(User user) { return hasEmail(user) && getIfUserPreferesMessageByEmail(); } private boolean hasEmail(User user) { Collection emails = user.getEmails(); return emails != null && !emails.isEmpty(); } protected UserProperties getUserPreferences() throws Exception { UserProperties property = getUserContext().getUserProperties(); return property; } protected IWPropertyList getUserMessagePreferences() { try { return getUserPreferences().getProperties(MESSAGE_PROPERTIES); } catch (Exception e) { e.printStackTrace(); return null; } } public boolean getIfUserPreferesMessageByEmail() {
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiver.java // public interface MessageReceiver extends IDOEntity, User { // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveEmails // */ // public boolean receiveEmails(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveEmails // */ // public void setReceiveEmails(boolean receiveEmails); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveMessagesToBox // */ // public boolean receiveMessagesToBox(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveMessagesToBox // */ // public void setReceiveMessagesToBox(boolean receiveMessages); // } // // Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiverHome.java // public interface MessageReceiverHome extends IDOHome { // // public MessageReceiver create() throws CreateException; // // public MessageReceiver findByPrimaryKey(Object pk) throws FinderException; // } // Path: src/java/is/idega/idegaweb/egov/message/business/MessageSessionBean.java import is.idega.idegaweb.egov.message.data.MessageReceiver; import is.idega.idegaweb.egov.message.data.MessageReceiverHome; import java.util.Collection; import javax.ejb.FinderException; import com.idega.business.IBOSessionBean; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWPropertyList; import com.idega.user.business.UserProperties; import com.idega.user.data.User; package is.idega.idegaweb.egov.message.business; /** * @author Laddi * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. To enable and disable the creation of type * comments go to Window>Preferences>Java>Code Generation. */ public class MessageSessionBean extends IBOSessionBean implements MessageSession { public static final String MESSAGE_PROPERTIES = "message_properties"; public static final String USER_PROP_SEND_TO_MESSAGE_BOX = "msg_send_box"; public static final String USER_PROP_SEND_TO_EMAIL = "msg_send_email"; public boolean getIfUserCanReceiveEmails(User user) { return hasEmail(user) && getIfUserPreferesMessageByEmail(); } private boolean hasEmail(User user) { Collection emails = user.getEmails(); return emails != null && !emails.isEmpty(); } protected UserProperties getUserPreferences() throws Exception { UserProperties property = getUserContext().getUserProperties(); return property; } protected IWPropertyList getUserMessagePreferences() { try { return getUserPreferences().getProperties(MESSAGE_PROPERTIES); } catch (Exception e) { e.printStackTrace(); return null; } } public boolean getIfUserPreferesMessageByEmail() {
MessageReceiver receiver = getMessageReceiver();
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/business/MessageSessionBean.java
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiver.java // public interface MessageReceiver extends IDOEntity, User { // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveEmails // */ // public boolean receiveEmails(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveEmails // */ // public void setReceiveEmails(boolean receiveEmails); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveMessagesToBox // */ // public boolean receiveMessagesToBox(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveMessagesToBox // */ // public void setReceiveMessagesToBox(boolean receiveMessages); // } // // Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiverHome.java // public interface MessageReceiverHome extends IDOHome { // // public MessageReceiver create() throws CreateException; // // public MessageReceiver findByPrimaryKey(Object pk) throws FinderException; // }
import is.idega.idegaweb.egov.message.data.MessageReceiver; import is.idega.idegaweb.egov.message.data.MessageReceiverHome; import java.util.Collection; import javax.ejb.FinderException; import com.idega.business.IBOSessionBean; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWPropertyList; import com.idega.user.business.UserProperties; import com.idega.user.data.User;
} return true; } public void setIfUserPreferesMessageByEmail(boolean preference) { MessageReceiver receiver = getMessageReceiver(); if (receiver != null) { receiver.setReceiveEmails(preference); receiver.store(); } else { IWPropertyList propertyList = getUserMessagePreferences(); propertyList.setProperty(USER_PROP_SEND_TO_EMAIL, new Boolean(preference)); } } public void setIfUserPreferesMessageInMessageBox(boolean preference) { MessageReceiver receiver = getMessageReceiver(); if (receiver != null) { receiver.setReceiveMessagesToBox(preference); receiver.store(); } else { IWPropertyList propertyList = getUserMessagePreferences(); propertyList.setProperty(USER_PROP_SEND_TO_MESSAGE_BOX, new Boolean(preference)); } } private MessageReceiver getMessageReceiver() { try {
// Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiver.java // public interface MessageReceiver extends IDOEntity, User { // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveEmails // */ // public boolean receiveEmails(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveEmails // */ // public void setReceiveEmails(boolean receiveEmails); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#receiveMessagesToBox // */ // public boolean receiveMessagesToBox(); // // /** // * @see is.idega.idegaweb.egov.message.data.MessageReceiverBMPBean#setReceiveMessagesToBox // */ // public void setReceiveMessagesToBox(boolean receiveMessages); // } // // Path: src/java/is/idega/idegaweb/egov/message/data/MessageReceiverHome.java // public interface MessageReceiverHome extends IDOHome { // // public MessageReceiver create() throws CreateException; // // public MessageReceiver findByPrimaryKey(Object pk) throws FinderException; // } // Path: src/java/is/idega/idegaweb/egov/message/business/MessageSessionBean.java import is.idega.idegaweb.egov.message.data.MessageReceiver; import is.idega.idegaweb.egov.message.data.MessageReceiverHome; import java.util.Collection; import javax.ejb.FinderException; import com.idega.business.IBOSessionBean; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWPropertyList; import com.idega.user.business.UserProperties; import com.idega.user.data.User; } return true; } public void setIfUserPreferesMessageByEmail(boolean preference) { MessageReceiver receiver = getMessageReceiver(); if (receiver != null) { receiver.setReceiveEmails(preference); receiver.store(); } else { IWPropertyList propertyList = getUserMessagePreferences(); propertyList.setProperty(USER_PROP_SEND_TO_EMAIL, new Boolean(preference)); } } public void setIfUserPreferesMessageInMessageBox(boolean preference) { MessageReceiver receiver = getMessageReceiver(); if (receiver != null) { receiver.setReceiveMessagesToBox(preference); receiver.store(); } else { IWPropertyList propertyList = getUserMessagePreferences(); propertyList.setProperty(USER_PROP_SEND_TO_MESSAGE_BOX, new Boolean(preference)); } } private MessageReceiver getMessageReceiver() { try {
MessageReceiverHome home = (MessageReceiverHome) IDOLookup.getHome(MessageReceiver.class);
idega/is.idega.idegaweb.egov.message
src/java/is/idega/idegaweb/egov/message/data/MessageContentBMPBean.java
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentValue.java // public class MessageContentValue { // // public static final String PARAMETER_TYPE = "msgctp"; // public static final String PARAMETER_LOCALE = "msgctl"; // public static final String PARAMETER_ID = "msgctid"; // // public Integer ID; // public String type; // public String name; // public String body; // public Integer creatorID; // public Date updated; // public Date created; // public Locale locale; // // /** // * Gets a String:String map of parameters neccessary to delete a MessageContent // * @param value // * @return // */ // public Map getDeleteParameters() { // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to edit a MessageContent // * @param value // * @return // */ // public Map getEditParameters(){ // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to create a MessageContent // * @param value // * @return // */ // public Map getCreateParameters(){ // HashMap map = new HashMap(1); // map.put(PARAMETER_TYPE,this.type); // return map; // } // }
import java.sql.Timestamp; import java.util.Collection; import java.util.Locale; import javax.ejb.FinderException; import is.idega.idegaweb.egov.message.business.MessageContentValue; import com.idega.core.localisation.data.ICLocale; import com.idega.data.GenericEntity; import com.idega.data.query.MatchCriteria; import com.idega.data.query.SelectQuery; import com.idega.data.query.Table; import com.idega.data.query.WildCardColumn; import com.idega.user.data.User;
if (loc != null) { return new Locale(loc); } return null; } public Collection ejbFindAll() throws FinderException { Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); return idoFindPKsByQuery(query); } public Collection ejbFindByCategory(String category) throws FinderException { Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table, CATEGORY, MatchCriteria.EQUALS, category, true)); return idoFindPKsByQuery(query); } public Collection ejbFindByCategoryAndLocale(String category, Integer locale) throws FinderException { Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table, CATEGORY, MatchCriteria.EQUALS, category, true)); query.addCriteria(new MatchCriteria(table, LOCALE, MatchCriteria.EQUALS, locale)); return idoFindPKsByQuery(query); }
// Path: src/java/is/idega/idegaweb/egov/message/business/MessageContentValue.java // public class MessageContentValue { // // public static final String PARAMETER_TYPE = "msgctp"; // public static final String PARAMETER_LOCALE = "msgctl"; // public static final String PARAMETER_ID = "msgctid"; // // public Integer ID; // public String type; // public String name; // public String body; // public Integer creatorID; // public Date updated; // public Date created; // public Locale locale; // // /** // * Gets a String:String map of parameters neccessary to delete a MessageContent // * @param value // * @return // */ // public Map getDeleteParameters() { // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to edit a MessageContent // * @param value // * @return // */ // public Map getEditParameters(){ // HashMap map = new HashMap(2); // map.put(PARAMETER_ID,this.ID.toString()); // map.put(PARAMETER_TYPE,this.type); // return map; // } // // /** // * Gets a String:String map of parameters neccessary to create a MessageContent // * @param value // * @return // */ // public Map getCreateParameters(){ // HashMap map = new HashMap(1); // map.put(PARAMETER_TYPE,this.type); // return map; // } // } // Path: src/java/is/idega/idegaweb/egov/message/data/MessageContentBMPBean.java import java.sql.Timestamp; import java.util.Collection; import java.util.Locale; import javax.ejb.FinderException; import is.idega.idegaweb.egov.message.business.MessageContentValue; import com.idega.core.localisation.data.ICLocale; import com.idega.data.GenericEntity; import com.idega.data.query.MatchCriteria; import com.idega.data.query.SelectQuery; import com.idega.data.query.Table; import com.idega.data.query.WildCardColumn; import com.idega.user.data.User; if (loc != null) { return new Locale(loc); } return null; } public Collection ejbFindAll() throws FinderException { Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); return idoFindPKsByQuery(query); } public Collection ejbFindByCategory(String category) throws FinderException { Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table, CATEGORY, MatchCriteria.EQUALS, category, true)); return idoFindPKsByQuery(query); } public Collection ejbFindByCategoryAndLocale(String category, Integer locale) throws FinderException { Table table = new Table(this); SelectQuery query = new SelectQuery(table); query.addColumn(new WildCardColumn()); query.addCriteria(new MatchCriteria(table, CATEGORY, MatchCriteria.EQUALS, category, true)); query.addCriteria(new MatchCriteria(table, LOCALE, MatchCriteria.EQUALS, locale)); return idoFindPKsByQuery(query); }
public Collection ejbFindByValue(MessageContentValue value) throws FinderException {
googleads/adwords-scripts-linkchecker
src/main/java/com/google/adwords/scripts/solutions/linkchecker/model/BatchSubOperation.java
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/urlcheck/UrlCheckStatus.java // @Cache // @Entity // public class UrlCheckStatus { // /** // * Represents the status of the job. Initial state is always NOT_STARTED, with the other states // * representing final states. // */ // public enum Status { // SUCCESS, // FAILURE, // NOT_STARTED // } // // @Id private final String id = UUID.randomUUID().toString(); // private String url; // // @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) // private Status status; // // private String message; // private int httpStatusCode; // // public UrlCheckStatus() {}; // // private UrlCheckStatus(String url, String message) { // this.url = url; // this.status = Status.NOT_STARTED; // this.message = message; // } // // /** // * Creates a new instance to hold the status based on URL. // * // * @param url The URL to check. // * @return a new {@code UrlCheckStatus} object. // */ // public static UrlCheckStatus fromUrl(String url) { // return new UrlCheckStatus(url, "unchecked-error"); // } // // public Status getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getUrl() { // return url; // } // // public int getHttpStatusCode() { // return httpStatusCode; // } // // public void setStatus(Status status, int httpStatusCode, String message) { // this.status = status; // this.httpStatusCode = httpStatusCode; // this.message = message; // } // }
import com.google.adwords.scripts.solutions.linkchecker.urlcheck.UrlCheckStatus; import com.googlecode.objectify.Ref; import com.googlecode.objectify.annotation.Cache; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Load; import com.googlecode.objectify.annotation.Parent; import java.util.ArrayList; import java.util.List; import java.util.UUID;
// Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.model; /** * Class to represent a sub operation. This unit of work is taken on by a single TaskQueue entry. */ @Cache @Entity public class BatchSubOperation { public static final int MAX_URLS = 100; @Id private String id;
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/urlcheck/UrlCheckStatus.java // @Cache // @Entity // public class UrlCheckStatus { // /** // * Represents the status of the job. Initial state is always NOT_STARTED, with the other states // * representing final states. // */ // public enum Status { // SUCCESS, // FAILURE, // NOT_STARTED // } // // @Id private final String id = UUID.randomUUID().toString(); // private String url; // // @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) // private Status status; // // private String message; // private int httpStatusCode; // // public UrlCheckStatus() {}; // // private UrlCheckStatus(String url, String message) { // this.url = url; // this.status = Status.NOT_STARTED; // this.message = message; // } // // /** // * Creates a new instance to hold the status based on URL. // * // * @param url The URL to check. // * @return a new {@code UrlCheckStatus} object. // */ // public static UrlCheckStatus fromUrl(String url) { // return new UrlCheckStatus(url, "unchecked-error"); // } // // public Status getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getUrl() { // return url; // } // // public int getHttpStatusCode() { // return httpStatusCode; // } // // public void setStatus(Status status, int httpStatusCode, String message) { // this.status = status; // this.httpStatusCode = httpStatusCode; // this.message = message; // } // } // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/model/BatchSubOperation.java import com.google.adwords.scripts.solutions.linkchecker.urlcheck.UrlCheckStatus; import com.googlecode.objectify.Ref; import com.googlecode.objectify.annotation.Cache; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Load; import com.googlecode.objectify.annotation.Parent; import java.util.ArrayList; import java.util.List; import java.util.UUID; // Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.model; /** * Class to represent a sub operation. This unit of work is taken on by a single TaskQueue entry. */ @Cache @Entity public class BatchSubOperation { public static final int MAX_URLS = 100; @Id private String id;
private List<UrlCheckStatus> urlStatuses;
googleads/adwords-scripts-linkchecker
src/main/java/com/google/adwords/scripts/solutions/linkchecker/endpoint/SettingsEndpoint.java
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/model/Settings.java // @Cache // @Entity // public class Settings { // public static final int DEFAULT_CHECKS_PER_MINUTE = 60; // public static final String DEFAULT_USER_AGENT = "GAE Link Checker"; // // @Id private String id; // private Integer rateInChecksPerMinute; // private String userAgentString; // // public Settings() { // this.id = "settings"; // } // // public Settings(int rateInChecksPerMinute, String userAgent) { // this(); // this.rateInChecksPerMinute = rateInChecksPerMinute; // this.userAgentString = userAgent; // } // // public int getRateInChecksPerMinute() { // return rateInChecksPerMinute; // } // // public String getUserAgentString() { // return userAgentString; // } // // public static Settings createDefaultSettings() { // return new Settings(DEFAULT_CHECKS_PER_MINUTE, DEFAULT_USER_AGENT); // } // } // // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/SettingsService.java // public class SettingsService { // private static final Logger LOG = Logger.getLogger(SettingsService.class.getName()); // private final Datastore datastore; // // @Inject // public SettingsService(Datastore datastore) { // this.datastore = datastore; // } // // public Settings getSettings() { // Settings settings; // try { // settings = datastore.getSettings(); // if (settings == null) { // settings = datastore.createDefaultSettings(); // } // } catch (NotFoundException e) { // settings = datastore.createDefaultSettings(); // } // return settings; // } // // /** // * Updates the settings in Datastore with the settings provides via the REST call. Only properties // * with non-null values are updated, allowing the caller to send partial settings updates, as if // * "PATCH" were supported by GAE. // * // * @param update // * @return // */ // public Settings updateSettings(Settings update) { // Settings current = getSettings(); // // for (Field field : update.getClass().getDeclaredFields()) { // field.setAccessible(true); // if (!Modifier.isFinal(field.getModifiers())) { // try { // if (field.get(update) != null) { // Field updateField = current.getClass().getDeclaredField(field.getName()); // updateField.setAccessible(true); // updateField.set(current, field.get(update)); // } // } catch (IllegalAccessException | NoSuchFieldException e) { // // If the partial update contains a field that is not in the definition of Settings, a // // NoSuchFieldException will be thrown. // LOG.log(Level.WARNING, "Settings update contained unknown property {0}", field.getName()); // } // } // } // return datastore.updateSettings(current); // } // }
import com.google.adwords.scripts.solutions.linkchecker.annotation.Authorize; import com.google.adwords.scripts.solutions.linkchecker.annotation.Authorize.Type; import com.google.adwords.scripts.solutions.linkchecker.model.Settings; import com.google.adwords.scripts.solutions.linkchecker.service.SettingsService; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.inject.Inject;
// Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.endpoint; /** Defines v1 of a BatchLinkChecker API */ @Api(name = "batchLinkChecker", version = "v1", title = "Batch Link Checker API") public class SettingsEndpoint { private final SettingsService settingsService; @Inject public SettingsEndpoint(SettingsService settingsService) { this.settingsService = settingsService; } /** * Retrieves the user-modifiable global settings. * * @return The settings object. */ @Authorize(value = Type.SHARED_KEY) @ApiMethod(httpMethod = ApiMethod.HttpMethod.GET, path = "settings")
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/model/Settings.java // @Cache // @Entity // public class Settings { // public static final int DEFAULT_CHECKS_PER_MINUTE = 60; // public static final String DEFAULT_USER_AGENT = "GAE Link Checker"; // // @Id private String id; // private Integer rateInChecksPerMinute; // private String userAgentString; // // public Settings() { // this.id = "settings"; // } // // public Settings(int rateInChecksPerMinute, String userAgent) { // this(); // this.rateInChecksPerMinute = rateInChecksPerMinute; // this.userAgentString = userAgent; // } // // public int getRateInChecksPerMinute() { // return rateInChecksPerMinute; // } // // public String getUserAgentString() { // return userAgentString; // } // // public static Settings createDefaultSettings() { // return new Settings(DEFAULT_CHECKS_PER_MINUTE, DEFAULT_USER_AGENT); // } // } // // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/SettingsService.java // public class SettingsService { // private static final Logger LOG = Logger.getLogger(SettingsService.class.getName()); // private final Datastore datastore; // // @Inject // public SettingsService(Datastore datastore) { // this.datastore = datastore; // } // // public Settings getSettings() { // Settings settings; // try { // settings = datastore.getSettings(); // if (settings == null) { // settings = datastore.createDefaultSettings(); // } // } catch (NotFoundException e) { // settings = datastore.createDefaultSettings(); // } // return settings; // } // // /** // * Updates the settings in Datastore with the settings provides via the REST call. Only properties // * with non-null values are updated, allowing the caller to send partial settings updates, as if // * "PATCH" were supported by GAE. // * // * @param update // * @return // */ // public Settings updateSettings(Settings update) { // Settings current = getSettings(); // // for (Field field : update.getClass().getDeclaredFields()) { // field.setAccessible(true); // if (!Modifier.isFinal(field.getModifiers())) { // try { // if (field.get(update) != null) { // Field updateField = current.getClass().getDeclaredField(field.getName()); // updateField.setAccessible(true); // updateField.set(current, field.get(update)); // } // } catch (IllegalAccessException | NoSuchFieldException e) { // // If the partial update contains a field that is not in the definition of Settings, a // // NoSuchFieldException will be thrown. // LOG.log(Level.WARNING, "Settings update contained unknown property {0}", field.getName()); // } // } // } // return datastore.updateSettings(current); // } // } // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/endpoint/SettingsEndpoint.java import com.google.adwords.scripts.solutions.linkchecker.annotation.Authorize; import com.google.adwords.scripts.solutions.linkchecker.annotation.Authorize.Type; import com.google.adwords.scripts.solutions.linkchecker.model.Settings; import com.google.adwords.scripts.solutions.linkchecker.service.SettingsService; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import com.google.inject.Inject; // Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.endpoint; /** Defines v1 of a BatchLinkChecker API */ @Api(name = "batchLinkChecker", version = "v1", title = "Batch Link Checker API") public class SettingsEndpoint { private final SettingsService settingsService; @Inject public SettingsEndpoint(SettingsService settingsService) { this.settingsService = settingsService; } /** * Retrieves the user-modifiable global settings. * * @return The settings object. */ @Authorize(value = Type.SHARED_KEY) @ApiMethod(httpMethod = ApiMethod.HttpMethod.GET, path = "settings")
public Settings get() {
googleads/adwords-scripts-linkchecker
src/main/java/com/google/adwords/scripts/solutions/linkchecker/interceptor/AuthorizeInterceptor.java
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/SharedKeyService.java // public class SharedKeyService { // Datastore datastore; // // @Inject // public SharedKeyService(Datastore datastore) { // this.datastore = datastore; // } // // public SharedKey getKey() { // SharedKey key; // try { // key = datastore.getKey(); // if (key == null) { // key = datastore.createKey(); // } // } catch (NotFoundException e) { // key = datastore.createKey(); // } // return key; // } // }
import com.google.adwords.scripts.solutions.linkchecker.service.SharedKeyService; import com.google.api.server.spi.response.UnauthorizedException; import com.google.appengine.api.utils.SystemProperty; import com.google.inject.Inject; import com.google.inject.Provider; import javax.servlet.http.HttpServletRequest; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation;
// Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.interceptor; /** * A class to apply to BatchLinkChecker API methods to ensure that the requesting client is * supplying the valid shared key. The shared key is not required when deployed as a development * instance. */ public class AuthorizeInterceptor implements MethodInterceptor { private final Provider<HttpServletRequest> httpServletRequestProvider;
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/SharedKeyService.java // public class SharedKeyService { // Datastore datastore; // // @Inject // public SharedKeyService(Datastore datastore) { // this.datastore = datastore; // } // // public SharedKey getKey() { // SharedKey key; // try { // key = datastore.getKey(); // if (key == null) { // key = datastore.createKey(); // } // } catch (NotFoundException e) { // key = datastore.createKey(); // } // return key; // } // } // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/interceptor/AuthorizeInterceptor.java import com.google.adwords.scripts.solutions.linkchecker.service.SharedKeyService; import com.google.api.server.spi.response.UnauthorizedException; import com.google.appengine.api.utils.SystemProperty; import com.google.inject.Inject; import com.google.inject.Provider; import javax.servlet.http.HttpServletRequest; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; // Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.interceptor; /** * A class to apply to BatchLinkChecker API methods to ensure that the requesting client is * supplying the valid shared key. The shared key is not required when deployed as a development * instance. */ public class AuthorizeInterceptor implements MethodInterceptor { private final Provider<HttpServletRequest> httpServletRequestProvider;
private final Provider<SharedKeyService> sharedKeyService;
googleads/adwords-scripts-linkchecker
src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/UrlCheckerService.java
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/urlcheck/UrlCheckStatus.java // @Cache // @Entity // public class UrlCheckStatus { // /** // * Represents the status of the job. Initial state is always NOT_STARTED, with the other states // * representing final states. // */ // public enum Status { // SUCCESS, // FAILURE, // NOT_STARTED // } // // @Id private final String id = UUID.randomUUID().toString(); // private String url; // // @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) // private Status status; // // private String message; // private int httpStatusCode; // // public UrlCheckStatus() {}; // // private UrlCheckStatus(String url, String message) { // this.url = url; // this.status = Status.NOT_STARTED; // this.message = message; // } // // /** // * Creates a new instance to hold the status based on URL. // * // * @param url The URL to check. // * @return a new {@code UrlCheckStatus} object. // */ // public static UrlCheckStatus fromUrl(String url) { // return new UrlCheckStatus(url, "unchecked-error"); // } // // public Status getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getUrl() { // return url; // } // // public int getHttpStatusCode() { // return httpStatusCode; // } // // public void setStatus(Status status, int httpStatusCode, String message) { // this.status = status; // this.httpStatusCode = httpStatusCode; // this.message = message; // } // }
import com.google.adwords.scripts.solutions.linkchecker.urlcheck.UrlCheckStatus; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.zip.GZIPInputStream;
// Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.service; /** * Provides the means to request web pages and check the returning HTTP status code, or determine * whether text indicative of a failure is in the page (e.g. "out of stock"). */ public class UrlCheckerService { private static final int DEFAULT_TIMEOUT_MILLIS = 15000; private static final String DEFAULT_USER_AGENT = "GAE Link Checker"; /** * Fetches a URL and updates the status to whether the fetch was a success or a failure. * * @param urlCheckStatus The details and status of the URL to be checked. Note that this object is * modified in place with the results of the check. * @param failureMatchTexts Optional list of strings to search for on the retrieved page that * indicate failure (e.g. "Out of stock"). * @param userAgent The user-agent to set with each request. */ public void check(
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/urlcheck/UrlCheckStatus.java // @Cache // @Entity // public class UrlCheckStatus { // /** // * Represents the status of the job. Initial state is always NOT_STARTED, with the other states // * representing final states. // */ // public enum Status { // SUCCESS, // FAILURE, // NOT_STARTED // } // // @Id private final String id = UUID.randomUUID().toString(); // private String url; // // @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) // private Status status; // // private String message; // private int httpStatusCode; // // public UrlCheckStatus() {}; // // private UrlCheckStatus(String url, String message) { // this.url = url; // this.status = Status.NOT_STARTED; // this.message = message; // } // // /** // * Creates a new instance to hold the status based on URL. // * // * @param url The URL to check. // * @return a new {@code UrlCheckStatus} object. // */ // public static UrlCheckStatus fromUrl(String url) { // return new UrlCheckStatus(url, "unchecked-error"); // } // // public Status getStatus() { // return status; // } // // public String getMessage() { // return message; // } // // public String getUrl() { // return url; // } // // public int getHttpStatusCode() { // return httpStatusCode; // } // // public void setStatus(Status status, int httpStatusCode, String message) { // this.status = status; // this.httpStatusCode = httpStatusCode; // this.message = message; // } // } // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/UrlCheckerService.java import com.google.adwords.scripts.solutions.linkchecker.urlcheck.UrlCheckStatus; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.zip.GZIPInputStream; // Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker.service; /** * Provides the means to request web pages and check the returning HTTP status code, or determine * whether text indicative of a failure is in the page (e.g. "out of stock"). */ public class UrlCheckerService { private static final int DEFAULT_TIMEOUT_MILLIS = 15000; private static final String DEFAULT_USER_AGENT = "GAE Link Checker"; /** * Fetches a URL and updates the status to whether the fetch was a success or a failure. * * @param urlCheckStatus The details and status of the URL to be checked. Note that this object is * modified in place with the results of the check. * @param failureMatchTexts Optional list of strings to search for on the retrieved page that * indicate failure (e.g. "Out of stock"). * @param userAgent The user-agent to set with each request. */ public void check(
UrlCheckStatus urlCheckStatus, List<String> failureMatchTexts, String userAgent) {
googleads/adwords-scripts-linkchecker
src/main/java/com/google/adwords/scripts/solutions/linkchecker/CronModule.java
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/JobsCleanupService.java // public class JobsCleanupService { // public static final int OLD_JOB_CUTOFF_DAYS = 30; // // private final BatchOperationService batchOperationService; // private final Datastore datastore; // // public static final String INDEX_BUILD_PATH = "/cron/jobscleanup"; // // @Inject // public JobsCleanupService( // BatchOperationService batchOperationService, Datastore datastore) { // this.batchOperationService = batchOperationService; // this.datastore = datastore; // } // // /** // * Deletes {@code BatchOperation}s that were created before then cutoff number of days ago. // */ // public void cleanup() { // Calendar cal = Calendar.getInstance(); // cal.setTime(new Date()); // cal.add(Calendar.DATE, -OLD_JOB_CUTOFF_DAYS); // Date cutoffDate = cal.getTime(); // // List<BatchOperation> oldOps = batchOperationService.listHistoricBatchOperations(cutoffDate); // for (BatchOperation oldOp : oldOps) { // datastore.deleteBatchOperation(oldOp.getAccountId(), oldOp.getBatchId()); // } // } // }
import com.google.adwords.scripts.solutions.linkchecker.service.JobsCleanupService; import com.google.api.server.spi.guice.EndpointsModule; import com.google.inject.Scopes;
// Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker; /** * Module to configure the CronServlet, which provides a single URL for requesting the deletion of * old jobs. */ public class CronModule extends EndpointsModule { @Override protected void configureServlets() { bind(CronServlet.class).in(Scopes.SINGLETON);
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/JobsCleanupService.java // public class JobsCleanupService { // public static final int OLD_JOB_CUTOFF_DAYS = 30; // // private final BatchOperationService batchOperationService; // private final Datastore datastore; // // public static final String INDEX_BUILD_PATH = "/cron/jobscleanup"; // // @Inject // public JobsCleanupService( // BatchOperationService batchOperationService, Datastore datastore) { // this.batchOperationService = batchOperationService; // this.datastore = datastore; // } // // /** // * Deletes {@code BatchOperation}s that were created before then cutoff number of days ago. // */ // public void cleanup() { // Calendar cal = Calendar.getInstance(); // cal.setTime(new Date()); // cal.add(Calendar.DATE, -OLD_JOB_CUTOFF_DAYS); // Date cutoffDate = cal.getTime(); // // List<BatchOperation> oldOps = batchOperationService.listHistoricBatchOperations(cutoffDate); // for (BatchOperation oldOp : oldOps) { // datastore.deleteBatchOperation(oldOp.getAccountId(), oldOp.getBatchId()); // } // } // } // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/CronModule.java import com.google.adwords.scripts.solutions.linkchecker.service.JobsCleanupService; import com.google.api.server.spi.guice.EndpointsModule; import com.google.inject.Scopes; // Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker; /** * Module to configure the CronServlet, which provides a single URL for requesting the deletion of * old jobs. */ public class CronModule extends EndpointsModule { @Override protected void configureServlets() { bind(CronServlet.class).in(Scopes.SINGLETON);
serve(JobsCleanupService.INDEX_BUILD_PATH).with(CronServlet.class);
googleads/adwords-scripts-linkchecker
src/main/java/com/google/adwords/scripts/solutions/linkchecker/CronServlet.java
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/JobsCleanupService.java // public class JobsCleanupService { // public static final int OLD_JOB_CUTOFF_DAYS = 30; // // private final BatchOperationService batchOperationService; // private final Datastore datastore; // // public static final String INDEX_BUILD_PATH = "/cron/jobscleanup"; // // @Inject // public JobsCleanupService( // BatchOperationService batchOperationService, Datastore datastore) { // this.batchOperationService = batchOperationService; // this.datastore = datastore; // } // // /** // * Deletes {@code BatchOperation}s that were created before then cutoff number of days ago. // */ // public void cleanup() { // Calendar cal = Calendar.getInstance(); // cal.setTime(new Date()); // cal.add(Calendar.DATE, -OLD_JOB_CUTOFF_DAYS); // Date cutoffDate = cal.getTime(); // // List<BatchOperation> oldOps = batchOperationService.listHistoricBatchOperations(cutoffDate); // for (BatchOperation oldOp : oldOps) { // datastore.deleteBatchOperation(oldOp.getAccountId(), oldOp.getBatchId()); // } // } // } // // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/SharedKeyService.java // public class SharedKeyService { // Datastore datastore; // // @Inject // public SharedKeyService(Datastore datastore) { // this.datastore = datastore; // } // // public SharedKey getKey() { // SharedKey key; // try { // key = datastore.getKey(); // if (key == null) { // key = datastore.createKey(); // } // } catch (NotFoundException e) { // key = datastore.createKey(); // } // return key; // } // }
import com.google.adwords.scripts.solutions.linkchecker.service.JobsCleanupService; import com.google.adwords.scripts.solutions.linkchecker.service.SharedKeyService; import com.google.inject.Inject; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
// Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker; /** * Servlet to respond to the requests from the AppEngine cron and clean up old BatchOperation * entries. */ public class CronServlet extends HttpServlet { private final JobsCleanupService jobsCleanupService; @Inject
// Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/JobsCleanupService.java // public class JobsCleanupService { // public static final int OLD_JOB_CUTOFF_DAYS = 30; // // private final BatchOperationService batchOperationService; // private final Datastore datastore; // // public static final String INDEX_BUILD_PATH = "/cron/jobscleanup"; // // @Inject // public JobsCleanupService( // BatchOperationService batchOperationService, Datastore datastore) { // this.batchOperationService = batchOperationService; // this.datastore = datastore; // } // // /** // * Deletes {@code BatchOperation}s that were created before then cutoff number of days ago. // */ // public void cleanup() { // Calendar cal = Calendar.getInstance(); // cal.setTime(new Date()); // cal.add(Calendar.DATE, -OLD_JOB_CUTOFF_DAYS); // Date cutoffDate = cal.getTime(); // // List<BatchOperation> oldOps = batchOperationService.listHistoricBatchOperations(cutoffDate); // for (BatchOperation oldOp : oldOps) { // datastore.deleteBatchOperation(oldOp.getAccountId(), oldOp.getBatchId()); // } // } // } // // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/service/SharedKeyService.java // public class SharedKeyService { // Datastore datastore; // // @Inject // public SharedKeyService(Datastore datastore) { // this.datastore = datastore; // } // // public SharedKey getKey() { // SharedKey key; // try { // key = datastore.getKey(); // if (key == null) { // key = datastore.createKey(); // } // } catch (NotFoundException e) { // key = datastore.createKey(); // } // return key; // } // } // Path: src/main/java/com/google/adwords/scripts/solutions/linkchecker/CronServlet.java import com.google.adwords.scripts.solutions.linkchecker.service.JobsCleanupService; import com.google.adwords.scripts.solutions.linkchecker.service.SharedKeyService; import com.google.inject.Inject; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // Copyright 2017, Google Inc. All Rights Reserved. // // 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 com.google.adwords.scripts.solutions.linkchecker; /** * Servlet to respond to the requests from the AppEngine cron and clean up old BatchOperation * entries. */ public class CronServlet extends HttpServlet { private final JobsCleanupService jobsCleanupService; @Inject
public CronServlet(JobsCleanupService jobsCleanupService, SharedKeyService sharedKeyService) {
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructMembers.java // public final class StructMembers { // // private final DeserializationContext context; // private final List<Member> rawMembers; // // public StructMembers(DeserializationContext context, List<Member> rawMembers) { // this.context = context; // this.rawMembers = rawMembers; // } // // private StructMember get(String name) { // for (Member rawMember : rawMembers) { // if (rawMember.name.equals(name)) { // return new StructMember(context, rawMember); // } // } // return null; // } // // public Boolean asBoolean(String name) { // StructMember member = get(name); // return member == null? null: member.asBoolean(); // } // // public Integer asInteger(String name) { // StructMember member = get(name); // return member == null? null: member.asInteger(); // } // // public Long asLong(String name) { // StructMember member = get(name); // return member == null? null: member.asLong(); // } // // public Double asDouble(String name) { // StructMember member = get(name); // return member == null? null: member.asDouble(); // } // // public String asString(String name) { // StructMember member = get(name); // return member == null? null: member.asString(); // } // // public Date asDate(String name) { // StructMember member = get(name); // return member == null? null: member.asDate(); // } // // public <T> T asObject(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asObject(type); // } // // public <T> List<T> asList(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asList(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // public static final String CODE = "struct";
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.MemberName; import nl.nl2312.xmlrpc.deserialization.StructMembers; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.util.HashMap; import java.util.List; import java.util.Map; import static nl.nl2312.xmlrpc.types.StructValue.CODE;
package nl.nl2312.xmlrpc.types; @Root(name = CODE) public final class StructValue implements Value { public static final String CODE = "struct"; public StructValue(List<Member> members) { this.members = members; } @ElementList(inline = true) public List<Member> members; @Override public List<Member> value() { return members; } @Override public void write(OutputNode node) throws Exception { OutputNode struct = node.getChild(CODE); for (Member member : members) { member.write(struct); } } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructMembers.java // public final class StructMembers { // // private final DeserializationContext context; // private final List<Member> rawMembers; // // public StructMembers(DeserializationContext context, List<Member> rawMembers) { // this.context = context; // this.rawMembers = rawMembers; // } // // private StructMember get(String name) { // for (Member rawMember : rawMembers) { // if (rawMember.name.equals(name)) { // return new StructMember(context, rawMember); // } // } // return null; // } // // public Boolean asBoolean(String name) { // StructMember member = get(name); // return member == null? null: member.asBoolean(); // } // // public Integer asInteger(String name) { // StructMember member = get(name); // return member == null? null: member.asInteger(); // } // // public Long asLong(String name) { // StructMember member = get(name); // return member == null? null: member.asLong(); // } // // public Double asDouble(String name) { // StructMember member = get(name); // return member == null? null: member.asDouble(); // } // // public String asString(String name) { // StructMember member = get(name); // return member == null? null: member.asString(); // } // // public Date asDate(String name) { // StructMember member = get(name); // return member == null? null: member.asDate(); // } // // public <T> T asObject(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asObject(type); // } // // public <T> List<T> asList(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asList(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // public static final String CODE = "struct"; // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.MemberName; import nl.nl2312.xmlrpc.deserialization.StructMembers; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.util.HashMap; import java.util.List; import java.util.Map; import static nl.nl2312.xmlrpc.types.StructValue.CODE; package nl.nl2312.xmlrpc.types; @Root(name = CODE) public final class StructValue implements Value { public static final String CODE = "struct"; public StructValue(List<Member> members) { this.members = members; } @ElementList(inline = true) public List<Member> members; @Override public List<Member> value() { return members; } @Override public void write(OutputNode node) throws Exception { OutputNode struct = node.getChild(CODE); for (Member member : members) { member.write(struct); } } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) throws
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructMembers.java // public final class StructMembers { // // private final DeserializationContext context; // private final List<Member> rawMembers; // // public StructMembers(DeserializationContext context, List<Member> rawMembers) { // this.context = context; // this.rawMembers = rawMembers; // } // // private StructMember get(String name) { // for (Member rawMember : rawMembers) { // if (rawMember.name.equals(name)) { // return new StructMember(context, rawMember); // } // } // return null; // } // // public Boolean asBoolean(String name) { // StructMember member = get(name); // return member == null? null: member.asBoolean(); // } // // public Integer asInteger(String name) { // StructMember member = get(name); // return member == null? null: member.asInteger(); // } // // public Long asLong(String name) { // StructMember member = get(name); // return member == null? null: member.asLong(); // } // // public Double asDouble(String name) { // StructMember member = get(name); // return member == null? null: member.asDouble(); // } // // public String asString(String name) { // StructMember member = get(name); // return member == null? null: member.asString(); // } // // public Date asDate(String name) { // StructMember member = get(name); // return member == null? null: member.asDate(); // } // // public <T> T asObject(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asObject(type); // } // // public <T> List<T> asList(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asList(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // public static final String CODE = "struct";
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.MemberName; import nl.nl2312.xmlrpc.deserialization.StructMembers; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.util.HashMap; import java.util.List; import java.util.Map; import static nl.nl2312.xmlrpc.types.StructValue.CODE;
package nl.nl2312.xmlrpc.types; @Root(name = CODE) public final class StructValue implements Value { public static final String CODE = "struct"; public StructValue(List<Member> members) { this.members = members; } @ElementList(inline = true) public List<Member> members; @Override public List<Member> value() { return members; } @Override public void write(OutputNode node) throws Exception { OutputNode struct = node.getChild(CODE); for (Member member : members) { member.write(struct); } } @Override public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) throws IllegalAccessException, InstantiationException { if (context.hasStructDeserializer(type)) { // Deserialize using custom deserializer
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructMembers.java // public final class StructMembers { // // private final DeserializationContext context; // private final List<Member> rawMembers; // // public StructMembers(DeserializationContext context, List<Member> rawMembers) { // this.context = context; // this.rawMembers = rawMembers; // } // // private StructMember get(String name) { // for (Member rawMember : rawMembers) { // if (rawMember.name.equals(name)) { // return new StructMember(context, rawMember); // } // } // return null; // } // // public Boolean asBoolean(String name) { // StructMember member = get(name); // return member == null? null: member.asBoolean(); // } // // public Integer asInteger(String name) { // StructMember member = get(name); // return member == null? null: member.asInteger(); // } // // public Long asLong(String name) { // StructMember member = get(name); // return member == null? null: member.asLong(); // } // // public Double asDouble(String name) { // StructMember member = get(name); // return member == null? null: member.asDouble(); // } // // public String asString(String name) { // StructMember member = get(name); // return member == null? null: member.asString(); // } // // public Date asDate(String name) { // StructMember member = get(name); // return member == null? null: member.asDate(); // } // // public <T> T asObject(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asObject(type); // } // // public <T> List<T> asList(String name, Class<T> type) { // StructMember member = get(name); // return member == null? null: member.asList(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // public static final String CODE = "struct"; // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.MemberName; import nl.nl2312.xmlrpc.deserialization.StructMembers; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.util.HashMap; import java.util.List; import java.util.Map; import static nl.nl2312.xmlrpc.types.StructValue.CODE; package nl.nl2312.xmlrpc.types; @Root(name = CODE) public final class StructValue implements Value { public static final String CODE = "struct"; public StructValue(List<Member> members) { this.members = members; } @ElementList(inline = true) public List<Member> members; @Override public List<Member> value() { return members; } @Override public void write(OutputNode node) throws Exception { OutputNode struct = node.getChild(CODE); for (Member member : members) { member.write(struct); } } @Override public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) throws IllegalAccessException, InstantiationException { if (context.hasStructDeserializer(type)) { // Deserialize using custom deserializer
return context.structDeserializer(type).deserialize(new StructMembers(context, members));
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/LongValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode;
package nl.nl2312.xmlrpc.types; @Root public final class LongValue implements Value { public static final String CODE = "i8"; @Element(name = CODE) long value; public LongValue(Long from) { this.value = from; } @Override public Long value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Long.toString(value)); } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/LongValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; package nl.nl2312.xmlrpc.types; @Root public final class LongValue implements Value { public static final String CODE = "i8"; @Element(name = CODE) long value; public LongValue(Long from) { this.value = from; } @Override public Long value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Long.toString(value)); } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) {
erickok/retrofit-xmlrpc
xmlrpc/src/test/java/nl/nl2312/xmlrpc/SimpleIntegrationTest.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/Nothing.java // public static final Nothing NOTHING = new Nothing();
import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.junit.Before; import org.junit.Test; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.POST; import java.io.IOException; import static com.google.common.truth.Truth.assertThat; import static nl.nl2312.xmlrpc.Nothing.NOTHING;
} @Test public void sumprodArray() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class); int[] execute = service.sumprodArray(new SumProdArgs(2, 4)).execute().body(); assertThat(execute).isNotEmpty(); assertThat(execute[0]).isEqualTo(6); assertThat(execute[1]).isEqualTo(8); } @Test public void sumprod() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class); SumProdResponse execute = service.sumprod(new SumProdArgs(2, 4)).execute().body(); assertThat(execute).isNotNull(); assertThat(execute.sum).isEqualTo(6); assertThat(execute.product).isEqualTo(8); } @Test public void capitalize() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class); String execute = service.capitalize("Hello, World!").execute().body(); assertThat(execute).isEqualTo("HELLO, WORLD!"); } @Test(expected = IOException.class) public void fault() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class);
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/Nothing.java // public static final Nothing NOTHING = new Nothing(); // Path: xmlrpc/src/test/java/nl/nl2312/xmlrpc/SimpleIntegrationTest.java import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.junit.Before; import org.junit.Test; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.POST; import java.io.IOException; import static com.google.common.truth.Truth.assertThat; import static nl.nl2312.xmlrpc.Nothing.NOTHING; } @Test public void sumprodArray() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class); int[] execute = service.sumprodArray(new SumProdArgs(2, 4)).execute().body(); assertThat(execute).isNotEmpty(); assertThat(execute[0]).isEqualTo(6); assertThat(execute[1]).isEqualTo(8); } @Test public void sumprod() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class); SumProdResponse execute = service.sumprod(new SumProdArgs(2, 4)).execute().body(); assertThat(execute).isNotNull(); assertThat(execute.sum).isEqualTo(6); assertThat(execute.product).isEqualTo(8); } @Test public void capitalize() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class); String execute = service.capitalize("Hello, World!").execute().body(); assertThat(execute).isEqualTo("HELLO, WORLD!"); } @Test(expected = IOException.class) public void fault() throws IOException { SimpleTestService service = retrofit.create(SimpleTestService.class);
service.nonExistentMethod(NOTHING).execute().body();
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // }
import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type;
package nl.nl2312.xmlrpc; public final class XmlRpcConverterFactory extends Converter.Factory { private final Serializer serializer;
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; package nl.nl2312.xmlrpc; public final class XmlRpcConverterFactory extends Converter.Factory { private final Serializer serializer;
private final DeserializationContext context;
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // }
import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type;
} return new XmlRpcRequestBodyConverter<>(serializer, annotation.value()); } @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { XmlRpc annotation = getAnnotation(annotations); if (annotation == null) { return null; } return new XmlRpcResponseBodyConverter<>(serializer, context, type); } private XmlRpc getAnnotation(Annotation[] annotations) { if (annotations != null) { for (Annotation annotation : annotations) { if (annotation instanceof XmlRpc) { return (XmlRpc) annotation; } } } return null; } public static class Builder { private DeserializationContext context = new DeserializationContext(); public Converter.Factory create() { // Use annotations, if any, or write using a tree, but never write any extra 'class' or 'length' attributes
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; } return new XmlRpcRequestBodyConverter<>(serializer, annotation.value()); } @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { XmlRpc annotation = getAnnotation(annotations); if (annotation == null) { return null; } return new XmlRpcResponseBodyConverter<>(serializer, context, type); } private XmlRpc getAnnotation(Annotation[] annotations) { if (annotations != null) { for (Annotation annotation : annotations) { if (annotation instanceof XmlRpc) { return (XmlRpc) annotation; } } } return null; } public static class Builder { private DeserializationContext context = new DeserializationContext(); public Converter.Factory create() { // Use annotations, if any, or write using a tree, but never write any extra 'class' or 'length' attributes
AnnotationStrategy strategy = new AnnotationStrategy(new SimplefiedTreeStrategy());
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // }
import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type;
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { XmlRpc annotation = getAnnotation(annotations); if (annotation == null) { return null; } return new XmlRpcResponseBodyConverter<>(serializer, context, type); } private XmlRpc getAnnotation(Annotation[] annotations) { if (annotations != null) { for (Annotation annotation : annotations) { if (annotation instanceof XmlRpc) { return (XmlRpc) annotation; } } } return null; } public static class Builder { private DeserializationContext context = new DeserializationContext(); public Converter.Factory create() { // Use annotations, if any, or write using a tree, but never write any extra 'class' or 'length' attributes AnnotationStrategy strategy = new AnnotationStrategy(new SimplefiedTreeStrategy()); return new XmlRpcConverterFactory(new Persister(strategy), context); }
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { XmlRpc annotation = getAnnotation(annotations); if (annotation == null) { return null; } return new XmlRpcResponseBodyConverter<>(serializer, context, type); } private XmlRpc getAnnotation(Annotation[] annotations) { if (annotations != null) { for (Annotation annotation : annotations) { if (annotation instanceof XmlRpc) { return (XmlRpc) annotation; } } } return null; } public static class Builder { private DeserializationContext context = new DeserializationContext(); public Converter.Factory create() { // Use annotations, if any, or write using a tree, but never write any extra 'class' or 'length' attributes AnnotationStrategy strategy = new AnnotationStrategy(new SimplefiedTreeStrategy()); return new XmlRpcConverterFactory(new Persister(strategy), context); }
public <T> Builder addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) {
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // }
import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type;
} return new XmlRpcResponseBodyConverter<>(serializer, context, type); } private XmlRpc getAnnotation(Annotation[] annotations) { if (annotations != null) { for (Annotation annotation : annotations) { if (annotation instanceof XmlRpc) { return (XmlRpc) annotation; } } } return null; } public static class Builder { private DeserializationContext context = new DeserializationContext(); public Converter.Factory create() { // Use annotations, if any, or write using a tree, but never write any extra 'class' or 'length' attributes AnnotationStrategy strategy = new AnnotationStrategy(new SimplefiedTreeStrategy()); return new XmlRpcConverterFactory(new Persister(strategy), context); } public <T> Builder addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { context.addStructDeserializer(clazz, structDeserializer); return this; }
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/ArrayDeserializer.java // public interface ArrayDeserializer<T> { // // T deserialize(ArrayValues values); // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/SimplefiedTreeStrategy.java // public class SimplefiedTreeStrategy extends TreeStrategy { // // @Override // public boolean write(Type type, Object value, NodeMap node, Map map) { // return false; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructDeserializer.java // public interface StructDeserializer<T> { // // T deserialize(StructMembers members); // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcConverterFactory.java import nl.nl2312.xmlrpc.deserialization.ArrayDeserializer; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import nl.nl2312.xmlrpc.deserialization.SimplefiedTreeStrategy; import nl.nl2312.xmlrpc.deserialization.StructDeserializer; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.convert.AnnotationStrategy; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import retrofit2.Converter; import retrofit2.Retrofit; import java.lang.annotation.Annotation; import java.lang.reflect.Type; } return new XmlRpcResponseBodyConverter<>(serializer, context, type); } private XmlRpc getAnnotation(Annotation[] annotations) { if (annotations != null) { for (Annotation annotation : annotations) { if (annotation instanceof XmlRpc) { return (XmlRpc) annotation; } } } return null; } public static class Builder { private DeserializationContext context = new DeserializationContext(); public Converter.Factory create() { // Use annotations, if any, or write using a tree, but never write any extra 'class' or 'length' attributes AnnotationStrategy strategy = new AnnotationStrategy(new SimplefiedTreeStrategy()); return new XmlRpcConverterFactory(new Persister(strategy), context); } public <T> Builder addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { context.addStructDeserializer(clazz, structDeserializer); return this; }
public <T> Builder addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) {
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/DoubleValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode;
package nl.nl2312.xmlrpc.types; @Root public final class DoubleValue implements Value { public static final String CODE = "double"; @Element(name = CODE) double value; public DoubleValue(Double from) { this.value = from; } @Override public Double value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Double.toString(value)); } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/DoubleValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; package nl.nl2312.xmlrpc.types; @Root public final class DoubleValue implements Value { public static final String CODE = "double"; @Element(name = CODE) double value; public DoubleValue(Double from) { this.value = from; } @Override public Double value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Double.toString(value)); } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) {
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/DateValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; import java.text.DateFormat; import java.text.ParseException; import java.util.Date;
package nl.nl2312.xmlrpc.types; @Root public final class DateValue implements Value { public static final String CODE = "dateTime.iso8601"; private static final DateFormat SIMPLE_ISO8601 = new Iso8601DateFormat(); @Element(name = CODE) Date value; public DateValue(Date from) { this.value = from; } @Override public Date value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(SIMPLE_ISO8601.format(value)); } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/DateValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; package nl.nl2312.xmlrpc.types; @Root public final class DateValue implements Value { public static final String CODE = "dateTime.iso8601"; private static final DateFormat SIMPLE_ISO8601 = new Iso8601DateFormat(); @Element(name = CODE) Date value; public DateValue(Date from) { this.value = from; } @Override public Date value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(SIMPLE_ISO8601.format(value)); } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) {
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/ValueConverter.java // public final class ValueConverter implements Converter<Value> { // // @Override // public Value read(InputNode node) throws Exception { // return getValue(node.getNext()); // } // // @Override // public void write(OutputNode node, Value value) throws Exception { // value.write(node); // } // // private static Value getValue(InputNode node) throws Exception { // switch (node.getName()) { // case IntegerValue.CODE: // return IntegerValue.parse(node.getValue()); // case IntegerValue.CODE_ALTERNTAIVE: // return IntegerValue.parse(node.getValue()); // case LongValue.CODE: // return LongValue.parse(node.getValue()); // case DoubleValue.CODE: // return DoubleValue.parse(node.getValue()); // case BooleanValue.CODE: // return BooleanValue.parse(node.getValue()); // case StringValue.CODE: // return StringValue.parse(node.getValue()); // case DateValue.CODE: // return DateValue.parse(node.getValue()); // case Base64Value.CODE: // return Base64Value.parse(node.getValue()); // case ArrayValue.CODE: // ArrayList<Value> data = new ArrayList<>(); // InputNode dataNode = node.getNext().getNext(); // while (dataNode != null && dataNode.getName().equals(Value.CODE)) { // data.add(getValue(dataNode.getNext())); // dataNode = node.getNext(); // } // return new ArrayValue(data); // case StructValue.CODE: // List<Member> members = new ArrayList<>(); // InputNode member = node.getNext(); // do { // String name = member.getNext().getValue(); // Value value = getValue(member.getNext().getNext()); // members.add(Member.create(name, value)); // member = node.getNext(); // } while (member != null && member.getName().equals(Member.CODE)); // return new StructValue(members); // } // throw new PersistenceException(node.getName() + " is an unsupported type in XML-RPC"); // } // // static Value getValue(Object value) { // // TODO? Handle null as <nil />? // if (value.getClass() == byte[].class) { // return new Base64Value((byte[]) value); // } else if (value.getClass().isArray()) { // int length = Array.getLength(value); // List<Value> values = new ArrayList<>(length); // for (int i = 0; i < length; i++) { // values.add(getValue(Array.get(value, i))); // } // return new ArrayValue(values); // } else if (value instanceof List) { // List list = (List) value; // List<Value> values = new ArrayList<>(list.size()); // for (Object o : list) { // values.add(getValue(o)); // } // return new ArrayValue(values); // } else if (value instanceof Integer) { // return new IntegerValue((Integer) value); // } else if (value instanceof Long) { // return new LongValue((Long) value); // } else if (value instanceof Double) { // return new DoubleValue((Double) value); // } else if (value instanceof Boolean) { // return new BooleanValue((Boolean) value); // } else if (value instanceof String) { // return new StringValue((String) value); // } else if (value instanceof Date) { // return new DateValue((Date) value); // } else { // try { // List<Member> members = new ArrayList<>(); // for (Field field : value.getClass().getFields()) { // if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { // continue; // } // MemberName annotation = field.getAnnotation(MemberName.class); // String memberName = annotation != null ? annotation.value() : field.getName(); // Object fieldValue = field.get(value); // if (fieldValue != null) { // members.add(Member.create(memberName, getValue(fieldValue))); // } // } // return new StructValue(members); // } catch (IllegalAccessException e) { // throw new RuntimeException(value.getClass().getSimpleName() + " is an unsupported type in XML-RPC"); // } // } // } // // }
import nl.nl2312.xmlrpc.ValueConverter; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.convert.Convert; import org.simpleframework.xml.stream.OutputNode;
package nl.nl2312.xmlrpc.types; @Root public final class Member { public static final String CODE = "member"; public static final String NAME = "name"; @Element(name = NAME) public String name; @Element(name = Value.CODE)
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/ValueConverter.java // public final class ValueConverter implements Converter<Value> { // // @Override // public Value read(InputNode node) throws Exception { // return getValue(node.getNext()); // } // // @Override // public void write(OutputNode node, Value value) throws Exception { // value.write(node); // } // // private static Value getValue(InputNode node) throws Exception { // switch (node.getName()) { // case IntegerValue.CODE: // return IntegerValue.parse(node.getValue()); // case IntegerValue.CODE_ALTERNTAIVE: // return IntegerValue.parse(node.getValue()); // case LongValue.CODE: // return LongValue.parse(node.getValue()); // case DoubleValue.CODE: // return DoubleValue.parse(node.getValue()); // case BooleanValue.CODE: // return BooleanValue.parse(node.getValue()); // case StringValue.CODE: // return StringValue.parse(node.getValue()); // case DateValue.CODE: // return DateValue.parse(node.getValue()); // case Base64Value.CODE: // return Base64Value.parse(node.getValue()); // case ArrayValue.CODE: // ArrayList<Value> data = new ArrayList<>(); // InputNode dataNode = node.getNext().getNext(); // while (dataNode != null && dataNode.getName().equals(Value.CODE)) { // data.add(getValue(dataNode.getNext())); // dataNode = node.getNext(); // } // return new ArrayValue(data); // case StructValue.CODE: // List<Member> members = new ArrayList<>(); // InputNode member = node.getNext(); // do { // String name = member.getNext().getValue(); // Value value = getValue(member.getNext().getNext()); // members.add(Member.create(name, value)); // member = node.getNext(); // } while (member != null && member.getName().equals(Member.CODE)); // return new StructValue(members); // } // throw new PersistenceException(node.getName() + " is an unsupported type in XML-RPC"); // } // // static Value getValue(Object value) { // // TODO? Handle null as <nil />? // if (value.getClass() == byte[].class) { // return new Base64Value((byte[]) value); // } else if (value.getClass().isArray()) { // int length = Array.getLength(value); // List<Value> values = new ArrayList<>(length); // for (int i = 0; i < length; i++) { // values.add(getValue(Array.get(value, i))); // } // return new ArrayValue(values); // } else if (value instanceof List) { // List list = (List) value; // List<Value> values = new ArrayList<>(list.size()); // for (Object o : list) { // values.add(getValue(o)); // } // return new ArrayValue(values); // } else if (value instanceof Integer) { // return new IntegerValue((Integer) value); // } else if (value instanceof Long) { // return new LongValue((Long) value); // } else if (value instanceof Double) { // return new DoubleValue((Double) value); // } else if (value instanceof Boolean) { // return new BooleanValue((Boolean) value); // } else if (value instanceof String) { // return new StringValue((String) value); // } else if (value instanceof Date) { // return new DateValue((Date) value); // } else { // try { // List<Member> members = new ArrayList<>(); // for (Field field : value.getClass().getFields()) { // if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { // continue; // } // MemberName annotation = field.getAnnotation(MemberName.class); // String memberName = annotation != null ? annotation.value() : field.getName(); // Object fieldValue = field.get(value); // if (fieldValue != null) { // members.add(Member.create(memberName, getValue(fieldValue))); // } // } // return new StructValue(members); // } catch (IllegalAccessException e) { // throw new RuntimeException(value.getClass().getSimpleName() + " is an unsupported type in XML-RPC"); // } // } // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java import nl.nl2312.xmlrpc.ValueConverter; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.convert.Convert; import org.simpleframework.xml.stream.OutputNode; package nl.nl2312.xmlrpc.types; @Root public final class Member { public static final String CODE = "member"; public static final String NAME = "name"; @Element(name = NAME) public String name; @Element(name = Value.CODE)
@Convert(ValueConverter.class)
erickok/retrofit-xmlrpc
xmlrpc/src/test/java/nl/nl2312/xmlrpc/RtorrentTest.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/Nothing.java // public static final Nothing NOTHING = new Nothing();
import okhttp3.*; import okhttp3.logging.HttpLoggingInterceptor; import org.junit.Before; import org.junit.Test; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.POST; import java.io.IOException; import static com.google.common.truth.Truth.assertThat; import static nl.nl2312.xmlrpc.Nothing.NOTHING;
@Before public void setUp() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient() .newBuilder() .addInterceptor(logging) .authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { return response .request() .newBuilder() .addHeader("Authorization", Credentials.basic(USERNAME, PASSWORD)) .build(); } }) .build(); retrofit = new Retrofit.Builder() .client(client) .baseUrl(URL) .addConverterFactory(XmlRpcConverterFactory.create()) .build(); } @Test public void listMethods() throws IOException { TestService service = retrofit.create(TestService.class);
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/Nothing.java // public static final Nothing NOTHING = new Nothing(); // Path: xmlrpc/src/test/java/nl/nl2312/xmlrpc/RtorrentTest.java import okhttp3.*; import okhttp3.logging.HttpLoggingInterceptor; import org.junit.Before; import org.junit.Test; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.POST; import java.io.IOException; import static com.google.common.truth.Truth.assertThat; import static nl.nl2312.xmlrpc.Nothing.NOTHING; @Before public void setUp() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient() .newBuilder() .addInterceptor(logging) .authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { return response .request() .newBuilder() .addHeader("Authorization", Credentials.basic(USERNAME, PASSWORD)) .build(); } }) .build(); retrofit = new Retrofit.Builder() .client(client) .baseUrl(URL) .addConverterFactory(XmlRpcConverterFactory.create()) .build(); } @Test public void listMethods() throws IOException { TestService service = retrofit.create(TestService.class);
String[] execute = service.listMethods(NOTHING).execute().body();
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructMembers.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java // @Root // public final class Member { // // public static final String CODE = "member"; // public static final String NAME = "name"; // // @Element(name = NAME) // public String name; // // @Element(name = Value.CODE) // @Convert(ValueConverter.class) // public Value value; // // public void write(OutputNode node) throws Exception { // OutputNode member = node.getChild(CODE); // OutputNode nameNode = member.getChild(Member.NAME); // nameNode.setValue(name); // OutputNode valueNode = member.getChild(Value.CODE); // value.write(valueNode); // } // // public static Member create(String name, Value from) { // Member param = new Member(); // param.name = name; // param.value = from; // return param; // } // // }
import nl.nl2312.xmlrpc.types.Member; import java.util.Date; import java.util.List;
package nl.nl2312.xmlrpc.deserialization; public final class StructMembers { private final DeserializationContext context;
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java // @Root // public final class Member { // // public static final String CODE = "member"; // public static final String NAME = "name"; // // @Element(name = NAME) // public String name; // // @Element(name = Value.CODE) // @Convert(ValueConverter.class) // public Value value; // // public void write(OutputNode node) throws Exception { // OutputNode member = node.getChild(CODE); // OutputNode nameNode = member.getChild(Member.NAME); // nameNode.setValue(name); // OutputNode valueNode = member.getChild(Value.CODE); // value.write(valueNode); // } // // public static Member create(String name, Value from) { // Member param = new Member(); // param.name = name; // param.value = from; // return param; // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/StructMembers.java import nl.nl2312.xmlrpc.types.Member; import java.util.Date; import java.util.List; package nl.nl2312.xmlrpc.deserialization; public final class StructMembers { private final DeserializationContext context;
private final List<Member> rawMembers;
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcResponseBodyConverter.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import retrofit2.Converter; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List;
package nl.nl2312.xmlrpc; final class XmlRpcResponseBodyConverter<T> implements Converter<ResponseBody, T> { private final Serializer serializer;
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/XmlRpcResponseBodyConverter.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import okhttp3.ResponseBody; import org.simpleframework.xml.Serializer; import retrofit2.Converter; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; package nl.nl2312.xmlrpc; final class XmlRpcResponseBodyConverter<T> implements Converter<ResponseBody, T> { private final Serializer serializer;
private final DeserializationContext context;
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Value.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.stream.OutputNode;
package nl.nl2312.xmlrpc.types; public interface Value { String CODE = "value"; Object value(); void write(OutputNode node) throws Exception;
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Value.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.stream.OutputNode; package nl.nl2312.xmlrpc.types; public interface Value { String CODE = "value"; Object value(); void write(OutputNode node) throws Exception;
Object asObject(DeserializationContext context, Class<?> type, Class<?> param)
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/MethodCall.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java // @Root // public final class Member { // // public static final String CODE = "member"; // public static final String NAME = "name"; // // @Element(name = NAME) // public String name; // // @Element(name = Value.CODE) // @Convert(ValueConverter.class) // public Value value; // // public void write(OutputNode node) throws Exception { // OutputNode member = node.getChild(CODE); // OutputNode nameNode = member.getChild(Member.NAME); // nameNode.setValue(name); // OutputNode valueNode = member.getChild(Value.CODE); // value.write(valueNode); // } // // public static Member create(String name, Value from) { // Member param = new Member(); // param.name = name; // param.value = from; // return param; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // @Root(name = CODE) // public final class StructValue implements Value { // // public static final String CODE = "struct"; // // public StructValue(List<Member> members) { // this.members = members; // } // // @ElementList(inline = true) // public List<Member> members; // // @Override // public List<Member> value() { // return members; // } // // @Override // public void write(OutputNode node) throws Exception { // OutputNode struct = node.getChild(CODE); // for (Member member : members) { // member.write(struct); // } // } // // @Override // public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) throws // IllegalAccessException, InstantiationException { // // if (context.hasStructDeserializer(type)) { // // Deserialize using custom deserializer // return context.structDeserializer(type).deserialize(new StructMembers(context, members)); // } // // if (Map.class.isAssignableFrom(type)) { // Map t = new HashMap(); // for (Member member : members) { // t.put(member.name, member.value.asObject(context, param, null)); // } // return t; // } // // // Deserialize using member to field mapping // Object t = type.newInstance(); // for (Field field : type.getDeclaredFields()) { // Member fieldMember = findMember(field); // if (fieldMember != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field // .getModifiers()) && !Modifier.isTransient(field.getModifiers())) { // Class<?> targetFieldParam = null; // if (field.getGenericType() instanceof ParameterizedType) { // targetFieldParam = (Class<?>) ((ParameterizedType) field.getGenericType()) // .getActualTypeArguments()[0]; // } // field.set(t, fieldMember.value.asObject(context, field.getType(), targetFieldParam)); // } // } // return t; // } // // private Member findMember(Field field) { // for (Member member : members) { // MemberName memberName = field.getAnnotation(MemberName.class); // if (memberName != null && memberName.value().equals(member.name)) { // return member; // } else if (memberName == null && field.getName().equals(member.name)) { // return member; // } // } // return null; // } // // }
import nl.nl2312.xmlrpc.types.Member; import nl.nl2312.xmlrpc.types.StructValue; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*;
package nl.nl2312.xmlrpc; @Root(name = "methodCall") final class MethodCall { @Element String methodName; @ElementList List<Param> params; public static MethodCall create(String method, Object param) { MethodCall methodCall = new MethodCall(); methodCall.methodName = method; if (param.getClass() == byte[].class) { methodCall.params = Collections.singletonList(Param.from(param)); } else if (param.getClass().isArray()) { // Treat param as array of individual parameters int length = Array.getLength(param); methodCall.params = new ArrayList<>(length); for (int i = 0; i < length; i++) { methodCall.params.add(Param.from(Array.get(param, i))); } } else if (param instanceof Iterable) { // Treat param as collection of individual parameters Iterator iter = ((Iterable) param).iterator(); methodCall.params = new ArrayList<>(); while (iter.hasNext()) { methodCall.params.add(Param.from(iter.next())); } } else if (param instanceof Map) { // Treat param as struct with map entries as members
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java // @Root // public final class Member { // // public static final String CODE = "member"; // public static final String NAME = "name"; // // @Element(name = NAME) // public String name; // // @Element(name = Value.CODE) // @Convert(ValueConverter.class) // public Value value; // // public void write(OutputNode node) throws Exception { // OutputNode member = node.getChild(CODE); // OutputNode nameNode = member.getChild(Member.NAME); // nameNode.setValue(name); // OutputNode valueNode = member.getChild(Value.CODE); // value.write(valueNode); // } // // public static Member create(String name, Value from) { // Member param = new Member(); // param.name = name; // param.value = from; // return param; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // @Root(name = CODE) // public final class StructValue implements Value { // // public static final String CODE = "struct"; // // public StructValue(List<Member> members) { // this.members = members; // } // // @ElementList(inline = true) // public List<Member> members; // // @Override // public List<Member> value() { // return members; // } // // @Override // public void write(OutputNode node) throws Exception { // OutputNode struct = node.getChild(CODE); // for (Member member : members) { // member.write(struct); // } // } // // @Override // public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) throws // IllegalAccessException, InstantiationException { // // if (context.hasStructDeserializer(type)) { // // Deserialize using custom deserializer // return context.structDeserializer(type).deserialize(new StructMembers(context, members)); // } // // if (Map.class.isAssignableFrom(type)) { // Map t = new HashMap(); // for (Member member : members) { // t.put(member.name, member.value.asObject(context, param, null)); // } // return t; // } // // // Deserialize using member to field mapping // Object t = type.newInstance(); // for (Field field : type.getDeclaredFields()) { // Member fieldMember = findMember(field); // if (fieldMember != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field // .getModifiers()) && !Modifier.isTransient(field.getModifiers())) { // Class<?> targetFieldParam = null; // if (field.getGenericType() instanceof ParameterizedType) { // targetFieldParam = (Class<?>) ((ParameterizedType) field.getGenericType()) // .getActualTypeArguments()[0]; // } // field.set(t, fieldMember.value.asObject(context, field.getType(), targetFieldParam)); // } // } // return t; // } // // private Member findMember(Field field) { // for (Member member : members) { // MemberName memberName = field.getAnnotation(MemberName.class); // if (memberName != null && memberName.value().equals(member.name)) { // return member; // } else if (memberName == null && field.getName().equals(member.name)) { // return member; // } // } // return null; // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/MethodCall.java import nl.nl2312.xmlrpc.types.Member; import nl.nl2312.xmlrpc.types.StructValue; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; package nl.nl2312.xmlrpc; @Root(name = "methodCall") final class MethodCall { @Element String methodName; @ElementList List<Param> params; public static MethodCall create(String method, Object param) { MethodCall methodCall = new MethodCall(); methodCall.methodName = method; if (param.getClass() == byte[].class) { methodCall.params = Collections.singletonList(Param.from(param)); } else if (param.getClass().isArray()) { // Treat param as array of individual parameters int length = Array.getLength(param); methodCall.params = new ArrayList<>(length); for (int i = 0; i < length; i++) { methodCall.params.add(Param.from(Array.get(param, i))); } } else if (param instanceof Iterable) { // Treat param as collection of individual parameters Iterator iter = ((Iterable) param).iterator(); methodCall.params = new ArrayList<>(); while (iter.hasNext()) { methodCall.params.add(Param.from(iter.next())); } } else if (param instanceof Map) { // Treat param as struct with map entries as members
ArrayList<Member> members = new ArrayList<>();
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/MethodCall.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java // @Root // public final class Member { // // public static final String CODE = "member"; // public static final String NAME = "name"; // // @Element(name = NAME) // public String name; // // @Element(name = Value.CODE) // @Convert(ValueConverter.class) // public Value value; // // public void write(OutputNode node) throws Exception { // OutputNode member = node.getChild(CODE); // OutputNode nameNode = member.getChild(Member.NAME); // nameNode.setValue(name); // OutputNode valueNode = member.getChild(Value.CODE); // value.write(valueNode); // } // // public static Member create(String name, Value from) { // Member param = new Member(); // param.name = name; // param.value = from; // return param; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // @Root(name = CODE) // public final class StructValue implements Value { // // public static final String CODE = "struct"; // // public StructValue(List<Member> members) { // this.members = members; // } // // @ElementList(inline = true) // public List<Member> members; // // @Override // public List<Member> value() { // return members; // } // // @Override // public void write(OutputNode node) throws Exception { // OutputNode struct = node.getChild(CODE); // for (Member member : members) { // member.write(struct); // } // } // // @Override // public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) throws // IllegalAccessException, InstantiationException { // // if (context.hasStructDeserializer(type)) { // // Deserialize using custom deserializer // return context.structDeserializer(type).deserialize(new StructMembers(context, members)); // } // // if (Map.class.isAssignableFrom(type)) { // Map t = new HashMap(); // for (Member member : members) { // t.put(member.name, member.value.asObject(context, param, null)); // } // return t; // } // // // Deserialize using member to field mapping // Object t = type.newInstance(); // for (Field field : type.getDeclaredFields()) { // Member fieldMember = findMember(field); // if (fieldMember != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field // .getModifiers()) && !Modifier.isTransient(field.getModifiers())) { // Class<?> targetFieldParam = null; // if (field.getGenericType() instanceof ParameterizedType) { // targetFieldParam = (Class<?>) ((ParameterizedType) field.getGenericType()) // .getActualTypeArguments()[0]; // } // field.set(t, fieldMember.value.asObject(context, field.getType(), targetFieldParam)); // } // } // return t; // } // // private Member findMember(Field field) { // for (Member member : members) { // MemberName memberName = field.getAnnotation(MemberName.class); // if (memberName != null && memberName.value().equals(member.name)) { // return member; // } else if (memberName == null && field.getName().equals(member.name)) { // return member; // } // } // return null; // } // // }
import nl.nl2312.xmlrpc.types.Member; import nl.nl2312.xmlrpc.types.StructValue; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*;
package nl.nl2312.xmlrpc; @Root(name = "methodCall") final class MethodCall { @Element String methodName; @ElementList List<Param> params; public static MethodCall create(String method, Object param) { MethodCall methodCall = new MethodCall(); methodCall.methodName = method; if (param.getClass() == byte[].class) { methodCall.params = Collections.singletonList(Param.from(param)); } else if (param.getClass().isArray()) { // Treat param as array of individual parameters int length = Array.getLength(param); methodCall.params = new ArrayList<>(length); for (int i = 0; i < length; i++) { methodCall.params.add(Param.from(Array.get(param, i))); } } else if (param instanceof Iterable) { // Treat param as collection of individual parameters Iterator iter = ((Iterable) param).iterator(); methodCall.params = new ArrayList<>(); while (iter.hasNext()) { methodCall.params.add(Param.from(iter.next())); } } else if (param instanceof Map) { // Treat param as struct with map entries as members ArrayList<Member> members = new ArrayList<>(); //noinspection unchecked Map entrySet is always a Set<Map.Entry>, we just don't know the Map.Entry type for (Map.Entry entry : ((Set<Map.Entry>) ((Map) param).entrySet())) { members.add(Member.create(entry.getKey().toString(), ValueConverter.getValue(entry.getValue()))); } Param mapAsStruct = new Param();
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Member.java // @Root // public final class Member { // // public static final String CODE = "member"; // public static final String NAME = "name"; // // @Element(name = NAME) // public String name; // // @Element(name = Value.CODE) // @Convert(ValueConverter.class) // public Value value; // // public void write(OutputNode node) throws Exception { // OutputNode member = node.getChild(CODE); // OutputNode nameNode = member.getChild(Member.NAME); // nameNode.setValue(name); // OutputNode valueNode = member.getChild(Value.CODE); // value.write(valueNode); // } // // public static Member create(String name, Value from) { // Member param = new Member(); // param.name = name; // param.value = from; // return param; // } // // } // // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StructValue.java // @Root(name = CODE) // public final class StructValue implements Value { // // public static final String CODE = "struct"; // // public StructValue(List<Member> members) { // this.members = members; // } // // @ElementList(inline = true) // public List<Member> members; // // @Override // public List<Member> value() { // return members; // } // // @Override // public void write(OutputNode node) throws Exception { // OutputNode struct = node.getChild(CODE); // for (Member member : members) { // member.write(struct); // } // } // // @Override // public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) throws // IllegalAccessException, InstantiationException { // // if (context.hasStructDeserializer(type)) { // // Deserialize using custom deserializer // return context.structDeserializer(type).deserialize(new StructMembers(context, members)); // } // // if (Map.class.isAssignableFrom(type)) { // Map t = new HashMap(); // for (Member member : members) { // t.put(member.name, member.value.asObject(context, param, null)); // } // return t; // } // // // Deserialize using member to field mapping // Object t = type.newInstance(); // for (Field field : type.getDeclaredFields()) { // Member fieldMember = findMember(field); // if (fieldMember != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field // .getModifiers()) && !Modifier.isTransient(field.getModifiers())) { // Class<?> targetFieldParam = null; // if (field.getGenericType() instanceof ParameterizedType) { // targetFieldParam = (Class<?>) ((ParameterizedType) field.getGenericType()) // .getActualTypeArguments()[0]; // } // field.set(t, fieldMember.value.asObject(context, field.getType(), targetFieldParam)); // } // } // return t; // } // // private Member findMember(Field field) { // for (Member member : members) { // MemberName memberName = field.getAnnotation(MemberName.class); // if (memberName != null && memberName.value().equals(member.name)) { // return member; // } else if (memberName == null && field.getName().equals(member.name)) { // return member; // } // } // return null; // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/MethodCall.java import nl.nl2312.xmlrpc.types.Member; import nl.nl2312.xmlrpc.types.StructValue; import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; package nl.nl2312.xmlrpc; @Root(name = "methodCall") final class MethodCall { @Element String methodName; @ElementList List<Param> params; public static MethodCall create(String method, Object param) { MethodCall methodCall = new MethodCall(); methodCall.methodName = method; if (param.getClass() == byte[].class) { methodCall.params = Collections.singletonList(Param.from(param)); } else if (param.getClass().isArray()) { // Treat param as array of individual parameters int length = Array.getLength(param); methodCall.params = new ArrayList<>(length); for (int i = 0; i < length; i++) { methodCall.params.add(Param.from(Array.get(param, i))); } } else if (param instanceof Iterable) { // Treat param as collection of individual parameters Iterator iter = ((Iterable) param).iterator(); methodCall.params = new ArrayList<>(); while (iter.hasNext()) { methodCall.params.add(Param.from(iter.next())); } } else if (param instanceof Map) { // Treat param as struct with map entries as members ArrayList<Member> members = new ArrayList<>(); //noinspection unchecked Map entrySet is always a Set<Map.Entry>, we just don't know the Map.Entry type for (Map.Entry entry : ((Set<Map.Entry>) ((Map) param).entrySet())) { members.add(Member.create(entry.getKey().toString(), ValueConverter.getValue(entry.getValue()))); } Param mapAsStruct = new Param();
mapAsStruct.value = new StructValue(members);
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/IntegerValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode;
package nl.nl2312.xmlrpc.types; @Root public final class IntegerValue implements Value { public static final String CODE = "i4"; public static final String CODE_ALTERNTAIVE = "int"; @Element(name = CODE) int value; public IntegerValue(Integer from) { this.value = from; } @Override public Integer value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Integer.toString(value)); } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/IntegerValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; package nl.nl2312.xmlrpc.types; @Root public final class IntegerValue implements Value { public static final String CODE = "i4"; public static final String CODE_ALTERNTAIVE = "int"; @Element(name = CODE) int value; public IntegerValue(Integer from) { this.value = from; } @Override public Integer value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Integer.toString(value)); } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) {
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/Param.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Value.java // public interface Value { // // String CODE = "value"; // // Object value(); // // void write(OutputNode node) throws Exception; // // Object asObject(DeserializationContext context, Class<?> type, Class<?> param) // throws IllegalAccessException, InstantiationException; // // }
import nl.nl2312.xmlrpc.types.Value; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.convert.Convert;
package nl.nl2312.xmlrpc; @Root public final class Param {
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Value.java // public interface Value { // // String CODE = "value"; // // Object value(); // // void write(OutputNode node) throws Exception; // // Object asObject(DeserializationContext context, Class<?> type, Class<?> param) // throws IllegalAccessException, InstantiationException; // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/Param.java import nl.nl2312.xmlrpc.types.Value; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.convert.Convert; package nl.nl2312.xmlrpc; @Root public final class Param {
@Element(name = Value.CODE)
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Base64Value.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import net.iharder.Base64; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.core.PersistenceException; import org.simpleframework.xml.stream.OutputNode; import java.io.IOException;
package nl.nl2312.xmlrpc.types; @Root public final class Base64Value implements Value { public static final String CODE = "base64"; @Element(name = CODE) byte[] value; public Base64Value(byte[] from) { this.value = from; } @Override public byte[] value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Base64.encodeBytes(value)); } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/Base64Value.java import net.iharder.Base64; import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.core.PersistenceException; import org.simpleframework.xml.stream.OutputNode; import java.io.IOException; package nl.nl2312.xmlrpc.types; @Root public final class Base64Value implements Value { public static final String CODE = "base64"; @Element(name = CODE) byte[] value; public Base64Value(byte[] from) { this.value = from; } @Override public byte[] value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(Base64.encodeBytes(value)); } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) {
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StringValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode;
package nl.nl2312.xmlrpc.types; @Root public final class StringValue implements Value { public static final String CODE = "string"; @Element(name = CODE) String value; public StringValue(String from) { this.value = from; } @Override public String value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(value); } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/StringValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; package nl.nl2312.xmlrpc.types; @Root public final class StringValue implements Value { public static final String CODE = "string"; @Element(name = CODE) String value; public StringValue(String from) { this.value = from; } @Override public String value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(value); } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) {
erickok/retrofit-xmlrpc
xmlrpc/src/test/java/nl/nl2312/xmlrpc/BugzillaIntegrationTest.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/Nothing.java // public static final Nothing NOTHING = new Nothing();
import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.junit.Before; import org.junit.Test; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST; import java.io.IOException; import static com.google.common.truth.Truth.assertThat; import static nl.nl2312.xmlrpc.Nothing.NOTHING;
package nl.nl2312.xmlrpc; public final class BugzillaIntegrationTest { private Retrofit retrofit; @Before public void setUp() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient() .newBuilder() .addInterceptor(logging) .build(); retrofit = new Retrofit.Builder() .client(client) .baseUrl("https://bugzilla.mozilla.org/") .addConverterFactory(XmlRpcConverterFactory.create()) .build(); } @Test public void bugzillaVersion() throws IOException { BugillaTestService service = retrofit.create(BugillaTestService.class);
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/Nothing.java // public static final Nothing NOTHING = new Nothing(); // Path: xmlrpc/src/test/java/nl/nl2312/xmlrpc/BugzillaIntegrationTest.java import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import org.junit.Before; import org.junit.Test; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST; import java.io.IOException; import static com.google.common.truth.Truth.assertThat; import static nl.nl2312.xmlrpc.Nothing.NOTHING; package nl.nl2312.xmlrpc; public final class BugzillaIntegrationTest { private Retrofit retrofit; @Before public void setUp() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient() .newBuilder() .addInterceptor(logging) .build(); retrofit = new Retrofit.Builder() .client(client) .baseUrl("https://bugzilla.mozilla.org/") .addConverterFactory(XmlRpcConverterFactory.create()) .build(); } @Test public void bugzillaVersion() throws IOException { BugillaTestService service = retrofit.create(BugillaTestService.class);
BugzillaVersion version = service.bugzillaVersion(NOTHING).execute().body();
erickok/retrofit-xmlrpc
xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/BooleanValue.java
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // }
import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode;
package nl.nl2312.xmlrpc.types; @Root public final class BooleanValue implements Value { public static final String CODE = "boolean"; public static final String FALSE = "0"; public static final String TRUE = "1"; @Element(name = CODE) boolean value; public BooleanValue(Boolean from) { this.value = from; } @Override public Boolean value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(value ? TRUE : FALSE); } @Override
// Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/deserialization/DeserializationContext.java // public final class DeserializationContext { // // private final Map<Class<?>, StructDeserializer<?>> structDeserializers = new HashMap<>(); // private final Map<Class<?>, ArrayDeserializer<?>> arrayDeserializers = new HashMap<>(); // // public boolean hasStructDeserializer(Class<?> type) { // return structDeserializers.containsKey(type); // } // // public <T> void addStructDeserializer(Class<T> clazz, StructDeserializer<T> structDeserializer) { // structDeserializers.put(clazz, structDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> StructDeserializer<T> structDeserializer(Class<T> type) { // return (StructDeserializer<T>) structDeserializers.get(type); // } // // public boolean hasArrayDeserializer(Class<?> type) { // return arrayDeserializers.containsKey(type); // } // // public <T> void addArrayDeserializer(Class<T> clazz, ArrayDeserializer<T> arrayDeserializer) { // arrayDeserializers.put(clazz, arrayDeserializer); // } // // @SuppressWarnings("unchecked") // Type parity between map key and deserializer is enforced during addition // public <T> ArrayDeserializer<T> arrayDeserializer(Class<T> type) { // return (ArrayDeserializer<T>) arrayDeserializers.get(type); // } // // } // Path: xmlrpc/src/main/java/nl/nl2312/xmlrpc/types/BooleanValue.java import nl.nl2312.xmlrpc.deserialization.DeserializationContext; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import org.simpleframework.xml.stream.OutputNode; package nl.nl2312.xmlrpc.types; @Root public final class BooleanValue implements Value { public static final String CODE = "boolean"; public static final String FALSE = "0"; public static final String TRUE = "1"; @Element(name = CODE) boolean value; public BooleanValue(Boolean from) { this.value = from; } @Override public Boolean value() { return value; } @Override public void write(OutputNode node) throws Exception { OutputNode child = node.getChild(CODE); child.setValue(value ? TRUE : FALSE); } @Override
public Object asObject(DeserializationContext context, Class<?> type, Class<?> param) {
rjohnsondev/java-libpst
src/main/java/com/pff/PSTTable7C.java
// Path: src/main/java/com/pff/PSTFile.java // public static final int PST_TYPE_ANSI = 14;
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.pff.PSTFile.PST_TYPE_ANSI;
this.columnDescriptors[col] = new ColumnDescriptor(tcHeaderNode, offset); // System.out.println("iBit: "+col+" " // +columnDescriptors[col].iBit); if (this.columnDescriptors[col].id == entityToExtract) { this.overrideCol = col; } offset += 8; } } // if we are asking for a specific column, only get that! if (this.overrideCol > -1) { this.cCols = this.overrideCol + 1; } // Read the key table /* System.out.printf("Key table:\n"); / **/ this.keyMap = new HashMap<>(); // byte[] keyTableInfo = getNodeInfo(hidRoot); final NodeInfo keyTableInfo = this.getNodeInfo(this.hidRoot); this.numberOfKeys = keyTableInfo.length() / (this.sizeOfItemKey + this.sizeOfItemValue); offset = 0; for (int x = 0; x < this.numberOfKeys; x++) { final int Context = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemKey); offset += this.sizeOfItemKey; final int RowIndex = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemValue); offset += this.sizeOfItemValue; this.keyMap.put(Context, RowIndex); }
// Path: src/main/java/com/pff/PSTFile.java // public static final int PST_TYPE_ANSI = 14; // Path: src/main/java/com/pff/PSTTable7C.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static com.pff.PSTFile.PST_TYPE_ANSI; this.columnDescriptors[col] = new ColumnDescriptor(tcHeaderNode, offset); // System.out.println("iBit: "+col+" " // +columnDescriptors[col].iBit); if (this.columnDescriptors[col].id == entityToExtract) { this.overrideCol = col; } offset += 8; } } // if we are asking for a specific column, only get that! if (this.overrideCol > -1) { this.cCols = this.overrideCol + 1; } // Read the key table /* System.out.printf("Key table:\n"); / **/ this.keyMap = new HashMap<>(); // byte[] keyTableInfo = getNodeInfo(hidRoot); final NodeInfo keyTableInfo = this.getNodeInfo(this.hidRoot); this.numberOfKeys = keyTableInfo.length() / (this.sizeOfItemKey + this.sizeOfItemValue); offset = 0; for (int x = 0; x < this.numberOfKeys; x++) { final int Context = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemKey); offset += this.sizeOfItemKey; final int RowIndex = (int) keyTableInfo.seekAndReadLong(offset, this.sizeOfItemValue); offset += this.sizeOfItemValue; this.keyMap.put(Context, RowIndex); }
if (in.getPSTFile().getPSTFileType()==PST_TYPE_ANSI)
mguymon/naether
src/test/java/com/tobedevoured/naether/ExceptionsTest.java
// Path: src/main/java/com/tobedevoured/naether/deploy/DeployException.java // public class DeployException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public DeployException( String msg ) { // super(msg); // } // // public DeployException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public DeployException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/deploy/InstallException.java // public class InstallException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public InstallException( String msg ) { // super(msg); // } // // public InstallException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public InstallException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/maven/ProjectException.java // public class ProjectException extends NaetherException { // // private static final long serialVersionUID = -483028771930335840L; // // public ProjectException( String msg ) { // super(msg); // } // // public ProjectException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public ProjectException( Throwable throwable ) { // super(throwable); // } // }
import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import com.tobedevoured.naether.deploy.DeployException; import com.tobedevoured.naether.deploy.InstallException; import com.tobedevoured.naether.maven.ProjectException;
package com.tobedevoured.naether; public class ExceptionsTest { private RuntimeException runtimeException = new RuntimeException("test"); @Test public void classLoaderException() throws Exception { checkThrowable( ClassLoaderException.class ); } @Test public void dependencyException() throws Exception { checkThrowable( DependencyException.class ); } @Test public void resolveException() throws Exception { checkThrowable( ResolveException.class ); } @Test public void urlException() throws Exception { checkThrowable( URLException.class ); } @Test public void deployException() throws Exception {
// Path: src/main/java/com/tobedevoured/naether/deploy/DeployException.java // public class DeployException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public DeployException( String msg ) { // super(msg); // } // // public DeployException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public DeployException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/deploy/InstallException.java // public class InstallException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public InstallException( String msg ) { // super(msg); // } // // public InstallException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public InstallException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/maven/ProjectException.java // public class ProjectException extends NaetherException { // // private static final long serialVersionUID = -483028771930335840L; // // public ProjectException( String msg ) { // super(msg); // } // // public ProjectException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public ProjectException( Throwable throwable ) { // super(throwable); // } // } // Path: src/test/java/com/tobedevoured/naether/ExceptionsTest.java import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import com.tobedevoured.naether.deploy.DeployException; import com.tobedevoured.naether.deploy.InstallException; import com.tobedevoured.naether.maven.ProjectException; package com.tobedevoured.naether; public class ExceptionsTest { private RuntimeException runtimeException = new RuntimeException("test"); @Test public void classLoaderException() throws Exception { checkThrowable( ClassLoaderException.class ); } @Test public void dependencyException() throws Exception { checkThrowable( DependencyException.class ); } @Test public void resolveException() throws Exception { checkThrowable( ResolveException.class ); } @Test public void urlException() throws Exception { checkThrowable( URLException.class ); } @Test public void deployException() throws Exception {
checkThrowable( DeployException.class );
mguymon/naether
src/test/java/com/tobedevoured/naether/ExceptionsTest.java
// Path: src/main/java/com/tobedevoured/naether/deploy/DeployException.java // public class DeployException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public DeployException( String msg ) { // super(msg); // } // // public DeployException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public DeployException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/deploy/InstallException.java // public class InstallException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public InstallException( String msg ) { // super(msg); // } // // public InstallException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public InstallException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/maven/ProjectException.java // public class ProjectException extends NaetherException { // // private static final long serialVersionUID = -483028771930335840L; // // public ProjectException( String msg ) { // super(msg); // } // // public ProjectException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public ProjectException( Throwable throwable ) { // super(throwable); // } // }
import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import com.tobedevoured.naether.deploy.DeployException; import com.tobedevoured.naether.deploy.InstallException; import com.tobedevoured.naether.maven.ProjectException;
package com.tobedevoured.naether; public class ExceptionsTest { private RuntimeException runtimeException = new RuntimeException("test"); @Test public void classLoaderException() throws Exception { checkThrowable( ClassLoaderException.class ); } @Test public void dependencyException() throws Exception { checkThrowable( DependencyException.class ); } @Test public void resolveException() throws Exception { checkThrowable( ResolveException.class ); } @Test public void urlException() throws Exception { checkThrowable( URLException.class ); } @Test public void deployException() throws Exception { checkThrowable( DeployException.class ); } @Test public void installException() throws Exception {
// Path: src/main/java/com/tobedevoured/naether/deploy/DeployException.java // public class DeployException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public DeployException( String msg ) { // super(msg); // } // // public DeployException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public DeployException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/deploy/InstallException.java // public class InstallException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public InstallException( String msg ) { // super(msg); // } // // public InstallException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public InstallException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/maven/ProjectException.java // public class ProjectException extends NaetherException { // // private static final long serialVersionUID = -483028771930335840L; // // public ProjectException( String msg ) { // super(msg); // } // // public ProjectException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public ProjectException( Throwable throwable ) { // super(throwable); // } // } // Path: src/test/java/com/tobedevoured/naether/ExceptionsTest.java import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import com.tobedevoured.naether.deploy.DeployException; import com.tobedevoured.naether.deploy.InstallException; import com.tobedevoured.naether.maven.ProjectException; package com.tobedevoured.naether; public class ExceptionsTest { private RuntimeException runtimeException = new RuntimeException("test"); @Test public void classLoaderException() throws Exception { checkThrowable( ClassLoaderException.class ); } @Test public void dependencyException() throws Exception { checkThrowable( DependencyException.class ); } @Test public void resolveException() throws Exception { checkThrowable( ResolveException.class ); } @Test public void urlException() throws Exception { checkThrowable( URLException.class ); } @Test public void deployException() throws Exception { checkThrowable( DeployException.class ); } @Test public void installException() throws Exception {
checkThrowable( InstallException.class );
mguymon/naether
src/test/java/com/tobedevoured/naether/ExceptionsTest.java
// Path: src/main/java/com/tobedevoured/naether/deploy/DeployException.java // public class DeployException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public DeployException( String msg ) { // super(msg); // } // // public DeployException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public DeployException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/deploy/InstallException.java // public class InstallException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public InstallException( String msg ) { // super(msg); // } // // public InstallException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public InstallException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/maven/ProjectException.java // public class ProjectException extends NaetherException { // // private static final long serialVersionUID = -483028771930335840L; // // public ProjectException( String msg ) { // super(msg); // } // // public ProjectException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public ProjectException( Throwable throwable ) { // super(throwable); // } // }
import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import com.tobedevoured.naether.deploy.DeployException; import com.tobedevoured.naether.deploy.InstallException; import com.tobedevoured.naether.maven.ProjectException;
package com.tobedevoured.naether; public class ExceptionsTest { private RuntimeException runtimeException = new RuntimeException("test"); @Test public void classLoaderException() throws Exception { checkThrowable( ClassLoaderException.class ); } @Test public void dependencyException() throws Exception { checkThrowable( DependencyException.class ); } @Test public void resolveException() throws Exception { checkThrowable( ResolveException.class ); } @Test public void urlException() throws Exception { checkThrowable( URLException.class ); } @Test public void deployException() throws Exception { checkThrowable( DeployException.class ); } @Test public void installException() throws Exception { checkThrowable( InstallException.class ); } @Test public void projectException() throws Exception {
// Path: src/main/java/com/tobedevoured/naether/deploy/DeployException.java // public class DeployException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public DeployException( String msg ) { // super(msg); // } // // public DeployException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public DeployException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/deploy/InstallException.java // public class InstallException extends NaetherException { // // private static final long serialVersionUID = -9173565689543634165L; // // public InstallException( String msg ) { // super(msg); // } // // public InstallException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public InstallException( Throwable throwable ) { // super(throwable); // } // } // // Path: src/main/java/com/tobedevoured/naether/maven/ProjectException.java // public class ProjectException extends NaetherException { // // private static final long serialVersionUID = -483028771930335840L; // // public ProjectException( String msg ) { // super(msg); // } // // public ProjectException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public ProjectException( Throwable throwable ) { // super(throwable); // } // } // Path: src/test/java/com/tobedevoured/naether/ExceptionsTest.java import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; import com.tobedevoured.naether.deploy.DeployException; import com.tobedevoured.naether.deploy.InstallException; import com.tobedevoured.naether.maven.ProjectException; package com.tobedevoured.naether; public class ExceptionsTest { private RuntimeException runtimeException = new RuntimeException("test"); @Test public void classLoaderException() throws Exception { checkThrowable( ClassLoaderException.class ); } @Test public void dependencyException() throws Exception { checkThrowable( DependencyException.class ); } @Test public void resolveException() throws Exception { checkThrowable( ResolveException.class ); } @Test public void urlException() throws Exception { checkThrowable( URLException.class ); } @Test public void deployException() throws Exception { checkThrowable( DeployException.class ); } @Test public void installException() throws Exception { checkThrowable( InstallException.class ); } @Test public void projectException() throws Exception {
checkThrowable( ProjectException.class );
mguymon/naether
src/main/java/com/tobedevoured/naether/deploy/DeployArtifact.java
// Path: src/main/java/com/tobedevoured/naether/util/RepoBuilder.java // public final class RepoBuilder { // // private RepoBuilder() { } // // /** // * Create a {@link RemoteRepository} from a String url // * // * @param url String // * @return {@link RemoteRepository} // * @throws MalformedURLException exceptions // */ // public static RemoteRepository remoteRepositoryFromUrl(String url) throws MalformedURLException { // URL parsedUrl = new URL(url); // // StringBuffer id = new StringBuffer(parsedUrl.getHost()); // String path = parsedUrl.getPath(); // if (path.length() > 0) { // path = path.replaceFirst("/", "").replaceAll("/", "-").replaceAll(":", "-"); // id.append("-"); // id.append(path); // } // // if (parsedUrl.getPort() > -1) { // id.append("-"); // id.append(parsedUrl.getPort()); // } // // return new RemoteRepository(id.toString(), "default", url); // } // // /** // * Create a {@link Repository} from a String url // * // * @param url String // * @return {@link Repository} // * @throws MalformedURLException exception // */ // public static Repository repositoryFromUrl(String url) throws MalformedURLException { // URL parsedUrl = new URL(url); // // StringBuffer id = new StringBuffer(parsedUrl.getHost()); // String path = parsedUrl.getPath(); // if (path.length() > 0) { // path = path.replaceFirst("/", "").replaceAll("/", "-").replaceAll(":", "-"); // id.append("-"); // id.append(path); // } // // if (parsedUrl.getPort() > -1) { // id.append("-"); // id.append(parsedUrl.getPort()); // } // // Repository repo = new Repository(); // repo.setId( id.toString() ); // repo.setName( parsedUrl.getHost() ); // repo.setUrl( url ); // // return repo; // } // }
import java.io.File; import java.net.MalformedURLException; import org.sonatype.aether.artifact.Artifact; import org.sonatype.aether.repository.Authentication; import org.sonatype.aether.repository.RemoteRepository; import org.sonatype.aether.util.artifact.DefaultArtifact; import org.sonatype.aether.util.artifact.SubArtifact; import com.tobedevoured.naether.util.RepoBuilder;
} public DeployArtifact( String notation, String filePath, RemoteRepository remoteRepo ) { this.notation = notation; jarArtifact = new DefaultArtifact( notation ); this.filePath = filePath; jarArtifact = jarArtifact.setFile( new File( filePath ) ); this.remoteRepo = remoteRepo; } public void setAuth( String username, String password ) { authentication = new Authentication( username, password ); if ( getRemoteRepo() != null ) { getRemoteRepo().setAuthentication( authentication ); } } public void setAuth( String username, String password, String publicKeyFile, String passphrase ) { authentication = new Authentication( username, password, publicKeyFile, passphrase ); if ( getRemoteRepo() != null ) { getRemoteRepo().setAuthentication( authentication ); } } public void setRemoteRepo( String url ) throws MalformedURLException {
// Path: src/main/java/com/tobedevoured/naether/util/RepoBuilder.java // public final class RepoBuilder { // // private RepoBuilder() { } // // /** // * Create a {@link RemoteRepository} from a String url // * // * @param url String // * @return {@link RemoteRepository} // * @throws MalformedURLException exceptions // */ // public static RemoteRepository remoteRepositoryFromUrl(String url) throws MalformedURLException { // URL parsedUrl = new URL(url); // // StringBuffer id = new StringBuffer(parsedUrl.getHost()); // String path = parsedUrl.getPath(); // if (path.length() > 0) { // path = path.replaceFirst("/", "").replaceAll("/", "-").replaceAll(":", "-"); // id.append("-"); // id.append(path); // } // // if (parsedUrl.getPort() > -1) { // id.append("-"); // id.append(parsedUrl.getPort()); // } // // return new RemoteRepository(id.toString(), "default", url); // } // // /** // * Create a {@link Repository} from a String url // * // * @param url String // * @return {@link Repository} // * @throws MalformedURLException exception // */ // public static Repository repositoryFromUrl(String url) throws MalformedURLException { // URL parsedUrl = new URL(url); // // StringBuffer id = new StringBuffer(parsedUrl.getHost()); // String path = parsedUrl.getPath(); // if (path.length() > 0) { // path = path.replaceFirst("/", "").replaceAll("/", "-").replaceAll(":", "-"); // id.append("-"); // id.append(path); // } // // if (parsedUrl.getPort() > -1) { // id.append("-"); // id.append(parsedUrl.getPort()); // } // // Repository repo = new Repository(); // repo.setId( id.toString() ); // repo.setName( parsedUrl.getHost() ); // repo.setUrl( url ); // // return repo; // } // } // Path: src/main/java/com/tobedevoured/naether/deploy/DeployArtifact.java import java.io.File; import java.net.MalformedURLException; import org.sonatype.aether.artifact.Artifact; import org.sonatype.aether.repository.Authentication; import org.sonatype.aether.repository.RemoteRepository; import org.sonatype.aether.util.artifact.DefaultArtifact; import org.sonatype.aether.util.artifact.SubArtifact; import com.tobedevoured.naether.util.RepoBuilder; } public DeployArtifact( String notation, String filePath, RemoteRepository remoteRepo ) { this.notation = notation; jarArtifact = new DefaultArtifact( notation ); this.filePath = filePath; jarArtifact = jarArtifact.setFile( new File( filePath ) ); this.remoteRepo = remoteRepo; } public void setAuth( String username, String password ) { authentication = new Authentication( username, password ); if ( getRemoteRepo() != null ) { getRemoteRepo().setAuthentication( authentication ); } } public void setAuth( String username, String password, String publicKeyFile, String passphrase ) { authentication = new Authentication( username, password, publicKeyFile, passphrase ); if ( getRemoteRepo() != null ) { getRemoteRepo().setAuthentication( authentication ); } } public void setRemoteRepo( String url ) throws MalformedURLException {
this.setRemoteRepo( RepoBuilder.remoteRepositoryFromUrl( url ) );
mguymon/naether
src/main/java/com/tobedevoured/naether/maven/Invoker.java
// Path: src/main/java/com/tobedevoured/naether/NaetherException.java // public class NaetherException extends Exception { // // private static final long serialVersionUID = 6600188769024224357L; // // public NaetherException( String msg ) { // super(msg); // } // // public NaetherException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public NaetherException( Throwable throwable ) { // super(throwable); // } // }
import com.tobedevoured.naether.NaetherException; import org.apache.maven.shared.invoker.*; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import java.util.List;
package com.tobedevoured.naether.maven; /** * Invoke Maven goals */ public class Invoker { private final static Logger logger = LoggerFactory.getLogger(Invoker.class); private DefaultInvoker invoker; /** * Construct Invoker * @param localRepo local Maven repo to use * @param mavenHome path to Maven home */ public Invoker(String localRepo, String mavenHome) { invoker = new DefaultInvoker(); invoker.setLocalRepositoryDirectory( new File(localRepo) ); if ( mavenHome != null ) { invoker.setMavenHome(new File(mavenHome)); } } /** * Execute goals for a pom * * @param pom String path * @param goals String * @return {@link InvocationResult} * @throws NaetherException exception */
// Path: src/main/java/com/tobedevoured/naether/NaetherException.java // public class NaetherException extends Exception { // // private static final long serialVersionUID = 6600188769024224357L; // // public NaetherException( String msg ) { // super(msg); // } // // public NaetherException( String msg, Throwable throwable ) { // super(msg, throwable ); // } // // public NaetherException( Throwable throwable ) { // super(throwable); // } // } // Path: src/main/java/com/tobedevoured/naether/maven/Invoker.java import com.tobedevoured.naether.NaetherException; import org.apache.maven.shared.invoker.*; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import java.util.List; package com.tobedevoured.naether.maven; /** * Invoke Maven goals */ public class Invoker { private final static Logger logger = LoggerFactory.getLogger(Invoker.class); private DefaultInvoker invoker; /** * Construct Invoker * @param localRepo local Maven repo to use * @param mavenHome path to Maven home */ public Invoker(String localRepo, String mavenHome) { invoker = new DefaultInvoker(); invoker.setLocalRepositoryDirectory( new File(localRepo) ); if ( mavenHome != null ) { invoker.setMavenHome(new File(mavenHome)); } } /** * Execute goals for a pom * * @param pom String path * @param goals String * @return {@link InvocationResult} * @throws NaetherException exception */
public InvocationResult execute(String pom, String... goals) throws NaetherException {
mguymon/naether
src/main/java/com/tobedevoured/naether/repo/RepositoryClient.java
// Path: src/main/java/com/tobedevoured/naether/aether/ValidSystemScopeDependencySelector.java // public class ValidSystemScopeDependencySelector implements DependencySelector { // // private static final String SYSTEM_SCOPE = "system"; // // public boolean selectDependency(Dependency dependency) { // if ( SYSTEM_SCOPE.equals( dependency.getScope() ) ) { // String localPath = dependency.getArtifact().getProperties().get( "localPath" ); // if ( localPath == null || !(new File( localPath )).exists() ) { // return false; // } // } // // return true; // } // // public DependencySelector deriveChildSelector( DependencyCollectionContext context) { // return this; // } // // }
import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.maven.repository.internal.DefaultServiceLocator; import org.apache.maven.repository.internal.MavenRepositorySystemSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.aether.RepositorySystem; import org.sonatype.aether.artifact.Artifact; import org.sonatype.aether.collection.CollectRequest; import org.sonatype.aether.collection.CollectResult; import org.sonatype.aether.collection.DependencyCollectionException; import org.sonatype.aether.connector.wagon.WagonProvider; import org.sonatype.aether.connector.wagon.WagonRepositoryConnectorFactory; import org.sonatype.aether.deployment.DeployRequest; import org.sonatype.aether.deployment.DeploymentException; import org.sonatype.aether.installation.InstallRequest; import org.sonatype.aether.installation.InstallationException; import org.sonatype.aether.repository.LocalRepository; import org.sonatype.aether.resolution.ArtifactRequest; import org.sonatype.aether.resolution.ArtifactResolutionException; import org.sonatype.aether.resolution.ArtifactResult; import org.sonatype.aether.resolution.DependencyRequest; import org.sonatype.aether.resolution.DependencyResolutionException; import org.sonatype.aether.resolution.DependencyResult; import org.sonatype.aether.spi.connector.RepositoryConnectorFactory; import org.sonatype.aether.util.graph.selector.AndDependencySelector; import com.tobedevoured.naether.aether.ValidSystemScopeDependencySelector;
} /** * Set the {@link BuildWorkspaceReader} * * @param artifacts List */ public void setBuildWorkspaceReader(List<Artifact> artifacts) { BuildWorkspaceReader reader = new BuildWorkspaceReader(); for ( Artifact artifact : artifacts ) { reader.addArtifact( artifact ); } systemSession = (MavenRepositorySystemSession)systemSession.setWorkspaceReader( reader ); } /** * Create new {@link RepositorySystem} */ public void newRepositorySystem() { DefaultServiceLocator locator = new DefaultServiceLocator(); locator.setServices(WagonProvider.class, new ManualWagonProvider()); locator.addService(RepositoryConnectorFactory.class, WagonRepositoryConnectorFactory.class); repositorySystem = locator.getService(RepositorySystem.class); MavenRepositorySystemSession session = new MavenRepositorySystemSession();
// Path: src/main/java/com/tobedevoured/naether/aether/ValidSystemScopeDependencySelector.java // public class ValidSystemScopeDependencySelector implements DependencySelector { // // private static final String SYSTEM_SCOPE = "system"; // // public boolean selectDependency(Dependency dependency) { // if ( SYSTEM_SCOPE.equals( dependency.getScope() ) ) { // String localPath = dependency.getArtifact().getProperties().get( "localPath" ); // if ( localPath == null || !(new File( localPath )).exists() ) { // return false; // } // } // // return true; // } // // public DependencySelector deriveChildSelector( DependencyCollectionContext context) { // return this; // } // // } // Path: src/main/java/com/tobedevoured/naether/repo/RepositoryClient.java import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.maven.repository.internal.DefaultServiceLocator; import org.apache.maven.repository.internal.MavenRepositorySystemSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.aether.RepositorySystem; import org.sonatype.aether.artifact.Artifact; import org.sonatype.aether.collection.CollectRequest; import org.sonatype.aether.collection.CollectResult; import org.sonatype.aether.collection.DependencyCollectionException; import org.sonatype.aether.connector.wagon.WagonProvider; import org.sonatype.aether.connector.wagon.WagonRepositoryConnectorFactory; import org.sonatype.aether.deployment.DeployRequest; import org.sonatype.aether.deployment.DeploymentException; import org.sonatype.aether.installation.InstallRequest; import org.sonatype.aether.installation.InstallationException; import org.sonatype.aether.repository.LocalRepository; import org.sonatype.aether.resolution.ArtifactRequest; import org.sonatype.aether.resolution.ArtifactResolutionException; import org.sonatype.aether.resolution.ArtifactResult; import org.sonatype.aether.resolution.DependencyRequest; import org.sonatype.aether.resolution.DependencyResolutionException; import org.sonatype.aether.resolution.DependencyResult; import org.sonatype.aether.spi.connector.RepositoryConnectorFactory; import org.sonatype.aether.util.graph.selector.AndDependencySelector; import com.tobedevoured.naether.aether.ValidSystemScopeDependencySelector; } /** * Set the {@link BuildWorkspaceReader} * * @param artifacts List */ public void setBuildWorkspaceReader(List<Artifact> artifacts) { BuildWorkspaceReader reader = new BuildWorkspaceReader(); for ( Artifact artifact : artifacts ) { reader.addArtifact( artifact ); } systemSession = (MavenRepositorySystemSession)systemSession.setWorkspaceReader( reader ); } /** * Create new {@link RepositorySystem} */ public void newRepositorySystem() { DefaultServiceLocator locator = new DefaultServiceLocator(); locator.setServices(WagonProvider.class, new ManualWagonProvider()); locator.addService(RepositoryConnectorFactory.class, WagonRepositoryConnectorFactory.class); repositorySystem = locator.getService(RepositorySystem.class); MavenRepositorySystemSession session = new MavenRepositorySystemSession();
session = (MavenRepositorySystemSession)session.setDependencySelector( new AndDependencySelector( session.getDependencySelector(), new ValidSystemScopeDependencySelector() ) );
mguymon/naether
src/main/java/com/tobedevoured/naether/repo/LogRepositoryListener.java
// Path: src/main/java/com/tobedevoured/naether/Const.java // public final class Const { // // public static final String TEST_JAR = "test-jar"; // public static final String POM = "pom"; // public static final String JAR = "jar"; // public static final String TEST = "test"; // // public static final String _TO_ = " to "; // public static final String _FROM_ = " from "; // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.aether.AbstractRepositoryListener; import org.sonatype.aether.RepositoryEvent; import com.tobedevoured.naether.Const;
package com.tobedevoured.naether.repo; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Based on Sonatype's * https://github.com/sonatype/sonatype-aether/blob/master/aether-demo/src/main/java/demo/util/ConsoleRepositoryListener.java */ public class LogRepositoryListener extends AbstractRepositoryListener { private static Logger log = LoggerFactory.getLogger("NaetherRepository"); public void artifactDeployed( RepositoryEvent event ) {
// Path: src/main/java/com/tobedevoured/naether/Const.java // public final class Const { // // public static final String TEST_JAR = "test-jar"; // public static final String POM = "pom"; // public static final String JAR = "jar"; // public static final String TEST = "test"; // // public static final String _TO_ = " to "; // public static final String _FROM_ = " from "; // } // Path: src/main/java/com/tobedevoured/naether/repo/LogRepositoryListener.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonatype.aether.AbstractRepositoryListener; import org.sonatype.aether.RepositoryEvent; import com.tobedevoured.naether.Const; package com.tobedevoured.naether.repo; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Based on Sonatype's * https://github.com/sonatype/sonatype-aether/blob/master/aether-demo/src/main/java/demo/util/ConsoleRepositoryListener.java */ public class LogRepositoryListener extends AbstractRepositoryListener { private static Logger log = LoggerFactory.getLogger("NaetherRepository"); public void artifactDeployed( RepositoryEvent event ) {
log.info( "Deployed " + event.getArtifact() + Const._TO_ + event.getRepository() );
skpdvdd/PAV
pav/src/pav/audiosource/AudioSource.java
// Path: pav/src/pav/Config.java // public final class Config // { // /** // * Use FIFO audio source. // */ // public static final String AUDIO_SOURCE_FIFO = "fifo"; // // /** // * Use socket audio source. // */ // public static final String AUDIO_SOURCE_UDP = "udp"; // // /** // * Audio data are transfered as little-endian byte stream. // */ // public static final String BYTE_ORDER_LE = "le"; // // /** // * Audio data are transfered as big-endian byte stream. // */ // public static final String BYTE_ORDER_BE = "be"; // // /** // * The audio source to use. // */ // public static String audioSource = AUDIO_SOURCE_UDP; // // /** // * The sample size. Must be 512, 1024 or 2048. // */ // public static int sampleSize = 1024; // // /** // * The sample rate. // */ // public static int sampleRate = 44100; // // /** // * The byte order. // */ // public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; // // /** // * The port the udp audio source should listen to. // */ // public static int udpPort = 2198; // // /** // * The path to the fifo the fifo audio source should use. // */ // public static String fifoPath = ""; // // /** // * The width of the display window. // */ // public static int windowWidth = 1024; // // /** // * The height of the display window. // */ // public static int windowHeight = 768; // // /** // * The renderer to use. // */ // public static String renderer = PConstants.P2D; // // private Config() { } // } // // Path: libpav/src/pav/lib/PAVException.java // public class PAVException extends Exception // { // private static final long serialVersionUID = 4985787077612555714L; // // /** // * Ctor. // */ // public PAVException() // { // super(); // } // // /** // * Ctor. // * // * @param message The error message // */ // public PAVException(String message) // { // super(message); // } // // /** // * Ctor. // * // * @param cause The cause of the error // */ // public PAVException(Throwable cause) // { // super(cause); // } // // /** // * Ctor. // * // * @param message The error message // * @param cause The cause of the error // */ // public PAVException(String message, Throwable cause) // { // super(message, cause); // } // }
import pav.Config; import pav.lib.PAVException;
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; /** * An audio source. * * @author christopher */ public abstract class AudioSource { /** * Creates an audio source based on the configuration. * * @param callback The callback to use. Must not be null * @return The audio source * @throws PAVException On errors */
// Path: pav/src/pav/Config.java // public final class Config // { // /** // * Use FIFO audio source. // */ // public static final String AUDIO_SOURCE_FIFO = "fifo"; // // /** // * Use socket audio source. // */ // public static final String AUDIO_SOURCE_UDP = "udp"; // // /** // * Audio data are transfered as little-endian byte stream. // */ // public static final String BYTE_ORDER_LE = "le"; // // /** // * Audio data are transfered as big-endian byte stream. // */ // public static final String BYTE_ORDER_BE = "be"; // // /** // * The audio source to use. // */ // public static String audioSource = AUDIO_SOURCE_UDP; // // /** // * The sample size. Must be 512, 1024 or 2048. // */ // public static int sampleSize = 1024; // // /** // * The sample rate. // */ // public static int sampleRate = 44100; // // /** // * The byte order. // */ // public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; // // /** // * The port the udp audio source should listen to. // */ // public static int udpPort = 2198; // // /** // * The path to the fifo the fifo audio source should use. // */ // public static String fifoPath = ""; // // /** // * The width of the display window. // */ // public static int windowWidth = 1024; // // /** // * The height of the display window. // */ // public static int windowHeight = 768; // // /** // * The renderer to use. // */ // public static String renderer = PConstants.P2D; // // private Config() { } // } // // Path: libpav/src/pav/lib/PAVException.java // public class PAVException extends Exception // { // private static final long serialVersionUID = 4985787077612555714L; // // /** // * Ctor. // */ // public PAVException() // { // super(); // } // // /** // * Ctor. // * // * @param message The error message // */ // public PAVException(String message) // { // super(message); // } // // /** // * Ctor. // * // * @param cause The cause of the error // */ // public PAVException(Throwable cause) // { // super(cause); // } // // /** // * Ctor. // * // * @param message The error message // * @param cause The cause of the error // */ // public PAVException(String message, Throwable cause) // { // super(message, cause); // } // } // Path: pav/src/pav/audiosource/AudioSource.java import pav.Config; import pav.lib.PAVException; /* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; /** * An audio source. * * @author christopher */ public abstract class AudioSource { /** * Creates an audio source based on the configuration. * * @param callback The callback to use. Must not be null * @return The audio source * @throws PAVException On errors */
public static AudioSource factory(AudioCallback callback) throws PAVException
skpdvdd/PAV
pav/src/pav/audiosource/AudioSource.java
// Path: pav/src/pav/Config.java // public final class Config // { // /** // * Use FIFO audio source. // */ // public static final String AUDIO_SOURCE_FIFO = "fifo"; // // /** // * Use socket audio source. // */ // public static final String AUDIO_SOURCE_UDP = "udp"; // // /** // * Audio data are transfered as little-endian byte stream. // */ // public static final String BYTE_ORDER_LE = "le"; // // /** // * Audio data are transfered as big-endian byte stream. // */ // public static final String BYTE_ORDER_BE = "be"; // // /** // * The audio source to use. // */ // public static String audioSource = AUDIO_SOURCE_UDP; // // /** // * The sample size. Must be 512, 1024 or 2048. // */ // public static int sampleSize = 1024; // // /** // * The sample rate. // */ // public static int sampleRate = 44100; // // /** // * The byte order. // */ // public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; // // /** // * The port the udp audio source should listen to. // */ // public static int udpPort = 2198; // // /** // * The path to the fifo the fifo audio source should use. // */ // public static String fifoPath = ""; // // /** // * The width of the display window. // */ // public static int windowWidth = 1024; // // /** // * The height of the display window. // */ // public static int windowHeight = 768; // // /** // * The renderer to use. // */ // public static String renderer = PConstants.P2D; // // private Config() { } // } // // Path: libpav/src/pav/lib/PAVException.java // public class PAVException extends Exception // { // private static final long serialVersionUID = 4985787077612555714L; // // /** // * Ctor. // */ // public PAVException() // { // super(); // } // // /** // * Ctor. // * // * @param message The error message // */ // public PAVException(String message) // { // super(message); // } // // /** // * Ctor. // * // * @param cause The cause of the error // */ // public PAVException(Throwable cause) // { // super(cause); // } // // /** // * Ctor. // * // * @param message The error message // * @param cause The cause of the error // */ // public PAVException(String message, Throwable cause) // { // super(message, cause); // } // }
import pav.Config; import pav.lib.PAVException;
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; /** * An audio source. * * @author christopher */ public abstract class AudioSource { /** * Creates an audio source based on the configuration. * * @param callback The callback to use. Must not be null * @return The audio source * @throws PAVException On errors */ public static AudioSource factory(AudioCallback callback) throws PAVException { try {
// Path: pav/src/pav/Config.java // public final class Config // { // /** // * Use FIFO audio source. // */ // public static final String AUDIO_SOURCE_FIFO = "fifo"; // // /** // * Use socket audio source. // */ // public static final String AUDIO_SOURCE_UDP = "udp"; // // /** // * Audio data are transfered as little-endian byte stream. // */ // public static final String BYTE_ORDER_LE = "le"; // // /** // * Audio data are transfered as big-endian byte stream. // */ // public static final String BYTE_ORDER_BE = "be"; // // /** // * The audio source to use. // */ // public static String audioSource = AUDIO_SOURCE_UDP; // // /** // * The sample size. Must be 512, 1024 or 2048. // */ // public static int sampleSize = 1024; // // /** // * The sample rate. // */ // public static int sampleRate = 44100; // // /** // * The byte order. // */ // public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; // // /** // * The port the udp audio source should listen to. // */ // public static int udpPort = 2198; // // /** // * The path to the fifo the fifo audio source should use. // */ // public static String fifoPath = ""; // // /** // * The width of the display window. // */ // public static int windowWidth = 1024; // // /** // * The height of the display window. // */ // public static int windowHeight = 768; // // /** // * The renderer to use. // */ // public static String renderer = PConstants.P2D; // // private Config() { } // } // // Path: libpav/src/pav/lib/PAVException.java // public class PAVException extends Exception // { // private static final long serialVersionUID = 4985787077612555714L; // // /** // * Ctor. // */ // public PAVException() // { // super(); // } // // /** // * Ctor. // * // * @param message The error message // */ // public PAVException(String message) // { // super(message); // } // // /** // * Ctor. // * // * @param cause The cause of the error // */ // public PAVException(Throwable cause) // { // super(cause); // } // // /** // * Ctor. // * // * @param message The error message // * @param cause The cause of the error // */ // public PAVException(String message, Throwable cause) // { // super(message, cause); // } // } // Path: pav/src/pav/audiosource/AudioSource.java import pav.Config; import pav.lib.PAVException; /* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; /** * An audio source. * * @author christopher */ public abstract class AudioSource { /** * Creates an audio source based on the configuration. * * @param callback The callback to use. Must not be null * @return The audio source * @throws PAVException On errors */ public static AudioSource factory(AudioCallback callback) throws PAVException { try {
if(Config.audioSource.equals(Config.AUDIO_SOURCE_FIFO)) {
skpdvdd/PAV
libpav/src/pav/lib/Visualization.java
// Path: libpav/src/pav/lib/visualizer/Visualizer.java // public interface Visualizer extends Serializable // { // /** // * Sets the PApplet to draw to. Must be called before process(). // * // * @param applet Where to draw to. Must not be null // * @throws PAVException If the visualizer does not work with this applet // */ // void drawTo(PApplet applet) throws PAVException; // // /** // * Sets the area that can be used by this visualizer. If relative is set to false // * the visualizer will use the given values as its boundary, independent of the // * size of the PApplet. If relative is true, the values must be in the range [0,1] // * and represent an area relative to the size of the PApplet. Processings coordinate // * system is used, so (0,0) is the top left pixel. // * // * @param x1 Must be >= 0 and <= 1 if relative is true // * @param y1 Must be >= 0 and <= 1 if relative is true // * @param x2 Must be > x1 and <= 1 if relative is true // * @param y2 Must be > y1 and <= 1 if relative is true // * @param relative Whether or not the values are relative // */ // void setArea(float x1, float y1, float x2, float y2, boolean relative); // // /** // * Draws to the PApplet specified by drawTo. // * // * @throws PAVException If an error occures while drawing // */ // void process() throws PAVException; // // /** // * Sets the color to use when drawing this visualizer. How a visualizer uses the color // * specified is not defined. It might not be used at all. // * // * @param color The color to use // */ // void setColor(int color); // // /** // * Sets two colors to interpolate between when drawing this visualizer. How a visualizer uses the colors // * specified is not defined. They might not be used at all. // * // * @param a The color to start from // * @param b The color to interpolate to // * @param mode The color mode to use. Must bei either PApplet.RGB or PApplet.HSB // */ // void setColor(int a, int b, int mode); // // /** // * Sets the colors to interpolate between when drawing this visualizer. How a visualizer uses the colors // * specified is not defined. They might not be used at all. // * // * @param thresholds The relative thresholds to use. Values must be between 0 and 1 and sorted. The first element must be 0, the last 1. Must be of same length as colors // * @param colors The The colors to use. Must be of same length as thresholds // * @param mode The color mode to use. Must be either PApplet.RGB or PApplet.HSB // */ // void setColor(float[] thresholds, int[] colors, int mode); // // /** // * Returns a short string representation of this visualizer. // * // * @return visualizer info // */ // String toString(); // // /** // * Disposes this visualizer, releasing all resources that were used exclusively // * by this visualizer. Subsequent calls to any methods of the visualizer might cause exceptions. // */ // void dispose(); // }
import java.util.Map; import pav.lib.visualizer.Visualizer;
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; /** * A visualization, comprised of a number of visualizers. * * @author christopher */ public interface Visualization { /** * Adds a new visualizer. The new visualizer will be drawn last. * * @param visualizer The visualizer to add. Must not be null * @throws PAVException If an error occured while adding the visualizer */
// Path: libpav/src/pav/lib/visualizer/Visualizer.java // public interface Visualizer extends Serializable // { // /** // * Sets the PApplet to draw to. Must be called before process(). // * // * @param applet Where to draw to. Must not be null // * @throws PAVException If the visualizer does not work with this applet // */ // void drawTo(PApplet applet) throws PAVException; // // /** // * Sets the area that can be used by this visualizer. If relative is set to false // * the visualizer will use the given values as its boundary, independent of the // * size of the PApplet. If relative is true, the values must be in the range [0,1] // * and represent an area relative to the size of the PApplet. Processings coordinate // * system is used, so (0,0) is the top left pixel. // * // * @param x1 Must be >= 0 and <= 1 if relative is true // * @param y1 Must be >= 0 and <= 1 if relative is true // * @param x2 Must be > x1 and <= 1 if relative is true // * @param y2 Must be > y1 and <= 1 if relative is true // * @param relative Whether or not the values are relative // */ // void setArea(float x1, float y1, float x2, float y2, boolean relative); // // /** // * Draws to the PApplet specified by drawTo. // * // * @throws PAVException If an error occures while drawing // */ // void process() throws PAVException; // // /** // * Sets the color to use when drawing this visualizer. How a visualizer uses the color // * specified is not defined. It might not be used at all. // * // * @param color The color to use // */ // void setColor(int color); // // /** // * Sets two colors to interpolate between when drawing this visualizer. How a visualizer uses the colors // * specified is not defined. They might not be used at all. // * // * @param a The color to start from // * @param b The color to interpolate to // * @param mode The color mode to use. Must bei either PApplet.RGB or PApplet.HSB // */ // void setColor(int a, int b, int mode); // // /** // * Sets the colors to interpolate between when drawing this visualizer. How a visualizer uses the colors // * specified is not defined. They might not be used at all. // * // * @param thresholds The relative thresholds to use. Values must be between 0 and 1 and sorted. The first element must be 0, the last 1. Must be of same length as colors // * @param colors The The colors to use. Must be of same length as thresholds // * @param mode The color mode to use. Must be either PApplet.RGB or PApplet.HSB // */ // void setColor(float[] thresholds, int[] colors, int mode); // // /** // * Returns a short string representation of this visualizer. // * // * @return visualizer info // */ // String toString(); // // /** // * Disposes this visualizer, releasing all resources that were used exclusively // * by this visualizer. Subsequent calls to any methods of the visualizer might cause exceptions. // */ // void dispose(); // } // Path: libpav/src/pav/lib/Visualization.java import java.util.Map; import pav.lib.visualizer.Visualizer; /* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.lib; /** * A visualization, comprised of a number of visualizers. * * @author christopher */ public interface Visualization { /** * Adds a new visualizer. The new visualizer will be drawn last. * * @param visualizer The visualizer to add. Must not be null * @throws PAVException If an error occured while adding the visualizer */
void addVisualizer(Visualizer visualizer) throws PAVException;
skpdvdd/PAV
pav/src/pav/audiosource/AudioStream.java
// Path: pav/src/pav/Config.java // public final class Config // { // /** // * Use FIFO audio source. // */ // public static final String AUDIO_SOURCE_FIFO = "fifo"; // // /** // * Use socket audio source. // */ // public static final String AUDIO_SOURCE_UDP = "udp"; // // /** // * Audio data are transfered as little-endian byte stream. // */ // public static final String BYTE_ORDER_LE = "le"; // // /** // * Audio data are transfered as big-endian byte stream. // */ // public static final String BYTE_ORDER_BE = "be"; // // /** // * The audio source to use. // */ // public static String audioSource = AUDIO_SOURCE_UDP; // // /** // * The sample size. Must be 512, 1024 or 2048. // */ // public static int sampleSize = 1024; // // /** // * The sample rate. // */ // public static int sampleRate = 44100; // // /** // * The byte order. // */ // public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; // // /** // * The port the udp audio source should listen to. // */ // public static int udpPort = 2198; // // /** // * The path to the fifo the fifo audio source should use. // */ // public static String fifoPath = ""; // // /** // * The width of the display window. // */ // public static int windowWidth = 1024; // // /** // * The height of the display window. // */ // public static int windowHeight = 768; // // /** // * The renderer to use. // */ // public static String renderer = PConstants.P2D; // // private Config() { } // }
import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import pav.Config;
/* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; /** * An audio stream. * * @author christopher */ public class AudioStream implements Runnable { private final Thread _thread; private final DataInputStream _is; private final AudioCallback _callback; private boolean _closed; /** * Ctor. * * @param source The input to read from. Must not be null and readable * @param callback The callback to send new frames to. Must not be null */ public AudioStream(InputStream source, AudioCallback callback) { _callback = callback; _is = new DataInputStream(source); _thread = new Thread(this, "AudioStream"); } /** * Starts reading (in a new thread). */ public void read() { _thread.start(); } @Override public void run() { try {
// Path: pav/src/pav/Config.java // public final class Config // { // /** // * Use FIFO audio source. // */ // public static final String AUDIO_SOURCE_FIFO = "fifo"; // // /** // * Use socket audio source. // */ // public static final String AUDIO_SOURCE_UDP = "udp"; // // /** // * Audio data are transfered as little-endian byte stream. // */ // public static final String BYTE_ORDER_LE = "le"; // // /** // * Audio data are transfered as big-endian byte stream. // */ // public static final String BYTE_ORDER_BE = "be"; // // /** // * The audio source to use. // */ // public static String audioSource = AUDIO_SOURCE_UDP; // // /** // * The sample size. Must be 512, 1024 or 2048. // */ // public static int sampleSize = 1024; // // /** // * The sample rate. // */ // public static int sampleRate = 44100; // // /** // * The byte order. // */ // public static ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; // // /** // * The port the udp audio source should listen to. // */ // public static int udpPort = 2198; // // /** // * The path to the fifo the fifo audio source should use. // */ // public static String fifoPath = ""; // // /** // * The width of the display window. // */ // public static int windowWidth = 1024; // // /** // * The height of the display window. // */ // public static int windowHeight = 768; // // /** // * The renderer to use. // */ // public static String renderer = PConstants.P2D; // // private Config() { } // } // Path: pav/src/pav/audiosource/AudioStream.java import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import pav.Config; /* * Processing Audio Visualization (PAV) * Copyright (C) 2011 Christopher Pramerdorfer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pav.audiosource; /** * An audio stream. * * @author christopher */ public class AudioStream implements Runnable { private final Thread _thread; private final DataInputStream _is; private final AudioCallback _callback; private boolean _closed; /** * Ctor. * * @param source The input to read from. Must not be null and readable * @param callback The callback to send new frames to. Must not be null */ public AudioStream(InputStream source, AudioCallback callback) { _callback = callback; _is = new DataInputStream(source); _thread = new Thread(this, "AudioStream"); } /** * Starts reading (in a new thread). */ public void read() { _thread.start(); } @Override public void run() { try {
int ss = Config.sampleSize;