working on it ...

Filters

Explore Public Snippets

Sort by

Found 2,031 snippets matching: queue

    public by sTiLL-iLL @ SniPitz-KND  550004  5  8  16

    Async Queue in C#

    using System;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    
    public class ParalyzKue
    {
    	readonly object _locker = new object();
    	Task _tail = Task.FromResult (true);
    	
    	public Task Enqueue (Action action)
    	{
    		lock (_locker)
    			return _tail = _tail.ContinueWith (ant => action());
    	}
    
    	public Task<TResult> Enqueue<TResult> (Func<TResult> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.ContinueWith (ant => func()));
    	}
    
    	public Task Enqueue (Func<Task> action)
    	{
    		lock (_locker)
    			return _tail = _tail.Catch().Then (action);
    	}	
    
    	public Task<TResult> Enqueue<TResult> (Func<Task<TResult>> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.Catch().Then (func));
    	}
    }
    
    
    public static class Extensions
    {
    	public static Task<T> Catch<T,TError> (this Task<T> task, Func<TError,T> onError) where TError : Exception
    	{
    		var tcs = new TaskCompletionSource<T> ();
    		task.ContinueWith (ant => {
    			if (task.IsFaulted && task.Exception.InnerException is TError)
    			{
    				tcs.SetResult (onError ((TError) task.Exception.InnerException));
    			}
    			else if (ant.IsCanceled)
    			{
    				tcs.SetCanceled ();
    			}
    			else if (task.IsFaulted)
    			{
    				tcs.SetException (ant.Exception.InnerException);
    			}
    			else
    			{
    				tcs.SetResult (ant.Result);
    			}
    		});
    		return tcs.Task;
    	}		
    	public static Task<T> Catch<T,TError> (this Task<T> task, T onError) where TError : Exception
    	{
    		return task.Catch<T,TError> (ex => onError);
    	}
    	
    	public static Task<T> Catch<T,TError> (this Task task, T onError) where TError : Exception
    	{
    		return task.ToTaskOfT<T>().Catch<T,TError> (onError);
    	}
    
    	public static Task Catch (this Task task)
    	{
    		return task.Catch<object,Exception> (null);
    	}
    	
    	public static Task<T> Catch<T> (this Task<T> task, T valueIfError = default(T))
    	{
    		return task.Catch<T,Exception> (valueIfError);
    	}
    
    	public async static Task<T> ToTaskOfT<T> (this Task t)
    	{
    		await t;
    		return default(T);
    	}
    	
    	public static async Task Then(this Task task, Func<Task> continuation)
    	{
    		await task;
    		await continuation();
    	}
    	
    	public static async Task<TNewResult> Then<TNewResult>(this Task task, Func<Task<TNewResult>> continuation)
    	{
    		await task;
    		return await continuation();
    	}
    	
    	public static async Task Then<TResult>(this Task<TResult> task, Func<TResult,Task> continuation)
    	{
    		await continuation(await task);
    	}
    	
    	public static async Task<TNewResult> Then<TResult, TNewResult>(this Task<TResult> task, Func<TResult, Task<TNewResult>> continuation)
    	{
    		return await continuation(await task);
    	}
    }
    
    /*
    public void doKue()
    {
    	var pcQ = new ParaKue();
    	
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 1");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 2");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://yahoo.com/search?q=the cube")).Dump ("Task 3");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 4");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 5");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://www.google.com/search?q=web scrapers")).Dump ("Task 6");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 7");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 8");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/search?q=aliens gods")).Dump ("Task 9");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 10");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 11");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=javascript")).Dump ("Task 12");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 13");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/search?q=aliens")).Dump ("Task 14");
      pcQ.Enqueue (() => AsyncMethod ("https://www.yahoo.com/")).Dump ("Task 15");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 16");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=aliens disclosure")).Dump ("Task 17");
    }
    
    string SyncMethod (string uri)
    {
        var x = new System.Net.WebClient();
        var y = x.DownloadString(uri);
        return y;
    }
    
    async Task<string> AsyncMethod (string uri)
    {
       return await Task.Run(() => new System.Net.WebClient().DownloadStringTaskAsync(uri).Dump());
    }
    
    
    async Task<string> AsyncMethod1 (string uri)
    {
       var x = await new System.Net.WebClient().DownloadStringTaskAsync(uri);
       return x;
    }
    
    */

    public by cghersi  105550  659  11  10

    Java: read from USB using RXTX library

    This is a well-tested class to read from USB device using RXTX library. First of all place rxtxSerial.so (or rxtxSerial.dll) in the classpath. The received bytes are stored in a queue called "receivedBytes". This queue is filled by the serialEvent() callback called by RXTX framework. Users of this class should retrieve the ready data from "receiv
    import gnu.io.*;
    import java.io.*;
    
    import java.util.Enumeration;
    import java.io.IOException;
    
    /**
     * This class provides the utilities to read the data exchanged via USB port.
     */
    public class USBComm implements SerialPortEventListener {
    
    	/**
    	 * Stream for the storage of incoming data
    	 */
    	private InputStream inputStream;
    	/**
    	 * Stream for the dispatching of data
    	 */
    	private OutputStream outputStream;
    	/**
    	 * Timeout of the USB port
    	 */
    	private final int PORT_TIMEOUT = 2000;
    	/**
    	 * Representation of the serial port used for the communication
    	 */
    	private SerialPort serialPort;
    	/**
    	 * Buffer that stores the received bytes from the media
    	 */
    	protected LinkedBlockingQueue<Byte> receivedBytes;
    
    	/**
    	 * Builds a new manager for the communication via USB port.
    	 * @exception IOException if an error occurred during the opening of the USB port
    	 */
    	public USBComm() throws IOException {
    	  receivedBytes = new LinkedBlockingQueue<Byte>(100000);
    		String port = "COM1"; //place the right COM port here, OS dependent
    	
    		//Check that the USB port exists and is recognized:
    		Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
    		boolean portFound = false;
    		CommPortIdentifier portId = null;
    		while (portList.hasMoreElements()) {
    			portId = (CommPortIdentifier) portList.nextElement();
    		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    		    	System.out.println.info(portId.getName());
    				if (portId.getName().equals(port)) {
    					System.out.println("Found port: " + port);
    				    portFound = true;
    				    break;
    				} 
    		    } 
    		} 
    	
    		if (!portFound) 
    		    throw new IOException("port " + port + " not found.");
    	
    		try {
    			System.out.println("USB port opening...");
    		    serialPort = (SerialPort) portId.open("USBCommunicator", PORT_TIMEOUT);
    		    System.out.println("USB port opened");
    		    inputStream = serialPort.getInputStream();
    		    outputStream = serialPort.getOutputStream();
    		    serialPort.addEventListener(this);
    			    	serialPort.notifyOnDataAvailable(true);
    			//#==================================================================#
    			// WARNING! - DO NOT SET THE FOLLOWING PROPERTY WITH RXTX LIBRARY, IT
    			// 			  CAUSES A PROGRAM LOCK:
    			// 	serialPort.notifyOnOutputEmpty(true);
    			//#==================================================================#
    			    	
    		    //wait for a while to leave the time to javax.comm to
    		    //correctly configure the port:
    		    Thread.sleep(1000);
    		    
    			int baudRate = 115200; //set propertly
    	    	serialPort.setSerialPortParams(baudRate, 
    	    		SerialPort.DATABITS_8, 
    	    		SerialPort.STOPBITS_1, 
    				SerialPort.PARITY_NONE);
    		    
    	    	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    	    		
    		    System.out.println("setted SerialPortParams");
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    			throw new IOException(e.getMessage());
    		}
    	}
    
    	
    	public void closeUSB(){
    		//close the streams for serial port:
    		try {
    			inputStream.close();
    			outputStream.close();
    		} catch (IOException e) {
    			System.err.println("Cannot close streams:" + e.getMessage(), e);
    		}
    	}
    
    	/**
    	 * Listener for USB events
    	 * 
    	 * @param event new event occurred on the USB port
    	 */
    	public void serialEvent(SerialPortEvent event){
    		switch (event.getEventType()) {
    	
    			case SerialPortEvent.BI:
    			case SerialPortEvent.OE:
    			case SerialPortEvent.FE:
    			case SerialPortEvent.PE:
    			case SerialPortEvent.CD:
    			case SerialPortEvent.CTS:
    			case SerialPortEvent.DSR:
    			case SerialPortEvent.RI:
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    				//nothing to do...
    			    break;
    	
    			case SerialPortEvent.DATA_AVAILABLE:
    				byte received = -1;
    				do {
    					try {
    						received = (byte)inputStream.read();
    					} catch (IOException e) {
    						System.err.println("Error reading USB:" + e.getMessage());
    					}
    				
    					synchronized (receivedBytes) {
    						try {
    							receivedBytes.add(received);
    						} catch (IllegalStateException ew) {
    							System.err.println(ew.getMessage());
    							receivedBytes.poll();
    							receivedBytes.add(received);
    						}
    					}
    				} while(received != -1);
    
    			    break;
    		}
    	}
    
    	protected void write(byte[] buffer){
    	    try {
    	    	outputStream.write(buffer);
    	    	outputStream.flush();
    	    } catch (IOException e) {
    	    	System.err.println("Cannot write:" + e.getMessage());
    	    }
    	}
    }            

    public by dave83  3052  1  7  4

    Reading Messages from a Queue with a MessageConsumer in JMS

    The code shows how to read messages from a queue using a Message Consumer in java Java Message Service. MessageConsumer object is created from the Session object, defined as non-transacted and auto-acknowledged, invoking createConsumer method. Such method will bind the consumer to the queue defined via JNDI lookup table.
    //Creating a non-transacted, auto-acknowledged session
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    //Creating messageConsumer bound to destination queue
    MessageConsumer messageConsumer = session.createConsumer(destination);
    connection.start();
    		
    Message message;
    boolean end = false;
    //read
    while (!end)
    {
        message = messageConsumer.receive();
        String text;
        if (message instanceof TextMessage)
        {
            text = ((TextMessage) message).getText();
        }
        else
        {
            byte[] body = new byte[(int) ((BytesMessage) message).getBodyLength()];
            ((BytesMessage) message).readBytes(body);
            text = new String(body);
        }
        if (text.equals("EXIT"))
        {
            System.out.println("Received exit message " + text);
            end = true;
        }
        else
        {
            System.out.println("Received  message:  " + text);
        }
    }
    //Tear down connection
    connection.close();

    public by sTiLL-iLL @ SniPitz-KND  2730  6  7  14

    C# Non Blocking, Multithreaded, Maker/Taker Queue

    effn sweet....
    public class KQue
    {
      readonly object synk = new object();
      Thread[] wrkrz;
      Queue<Action> itmQ = new Queue<Action>();
    
      public KQue (int workerCount)
      {
        wrkrz = new Thread [workerCount];
        for (int i = 0; i < workerCount; i++)
        {
          (wrkrz[i] = new Thread(konsume)).Start();
        }
      }
    
    
      public void Shutdown (bool waitingFor)
      {
        foreach (var thd in wrkrz)
        {
          NQItem (null);
        }
        if (waitingFor)
        {
          foreach (var thd in wrkrz)
          {
            thd.Join();
          }
        }
      }
    
      public void NQItem (Action itm)
      {
        lock (synk)
        {
          itmQ.Enqueue (itm);       
          Monitor.Pulse (synk);         
        }
      }
    
      private void konsume()
      {
        while (true)     
        {                               
          Action itm;
          lock (synk)
          {
            while (itmQ.Count == 0)
            {
                Monitor.Wait (synk);
            }
            itm = itmQ.Dequeue();
          }
    
          if (itm == null)  
          {
              return;
          }
    
          itm();   
        }
      }
    }
    
                

    public by sTiLL-iLL  2608  1  8  13

    Managed Interval! Timer Alchemy with concurrent kueue executes tasks on the b bb b bbeat

    check files, ping a server, download a receipt... if you can list it this can execute it, neat and tidy. its like a gold watch of timer structs (use my non-bloking kueue with this)
    using System;
    using System.IO;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    
    void Main()
    {
    	var dct = new DownCount(5);
    	new Thread (() =>
    	{
    		for (int i = 0; i < 5; i++)
    		{
    			Thread.Sleep(1000);
    			dct.Signal();
    			Console.WriteLine ("Signal " + i);
    		}
    	}).Start();
    	
    	Console.WriteLine ("Wait for it...");
    	dc.Wait();
    	Console.WriteLine ("ahhhhhh......");
    }
    
    public class DownCount
    {
      int val;
    	object loka = new object ();
    	public DownCount() { }
    	
    	public DownCount (int cnt1)
    	{
    	  val = cnt1;
    	}
    	
    	public void Signal()
    	{
    	  DCnt1 (-1);
    	}
    	
    	public void DCnt1 (int totl)
    	{
    		lock (loka) 
    		{ 
    			val += totl;
    			if (val <= 0)
    			{
    			  Monitor.PulseAll (loka);
    			}
    		}
    	}
    	
    	public void Wait()
    	{
    		lock (loka)
    		{
    			while (val > 0)
    			{
    				Monitor.Wait (loka);
    			}
    		}
    	}
    }
    
    //////////////////////////////////////////////////////////
    
    public class betterInterval
    {
      static void Tik(long t)
      {
        this.onTik.Invoke(t);
      }
      
      static IObservable<long> Interval(TimeSpan period)
      {
          return Observable.Create<long> (observer => {
    	    long i = 0;
    	    object sync = new object();
    	        return new Timer (_ => {
                      lock (sync) observer.OnNext (i++);
              }, Tik(i), period, period);
        });
      }
      
      static IObservable<long> kreate(TimeSpan period)
      {
        return Interval (TimeSpan.FromSeconds(period)).Subscribe(onTik);
      }
      
      static async void onTik(t)
      {
        Console.WriteLine(t);
      }
    }
    
    void Main()
    {
        IObservable<long> bi = betterInterval.kreate(TimeSpan.FromSeconds(5));
        bi.Subscribe(Console.WriteLine(t);
    }
    
    
    ///////////////////////////////////////////////////////////////////////
    
    public class KInterval
    {
        public delegate void Signal (object signal);
        public event Signal Received;
    
        static long tcnt = 0;
        long dly = 0;
        long prd = 0;
        KQue kq = new KQue(5);
        Timer tmr;
    
        public KInterval (long delay = 5000, long period = 3000, int workersCount = 3)
        {
            dly = delay;
            prd = period;
            if (workersCount > 0)
            {
                kq = new KQue(workersCount);
            }
        }
    
        public void Begin ( )
        {
            kq.NQItem(( ) => tmr = new Timer(Signaled, tcnt, dly, prd));
        }
    
        public void Kill ( )
        {
            tmr.Dispose();
            kq.ShutdownKQ(true);
        }
    
        private void Signaled (object signal)
        {
            var sig = (long) signal;
            var st = sig;
            this.Received += KInterval_Received;
            this.Received.Invoke(sig);
            this.Received -= KInterval_Received;
        }
    
        void KInterval_Received (object signal)
        {      }
    }                        

    public by cghersi  2792  2  7  1

    Manage a queue in Java

    This simple class has a queue that is filled and depleted with its two methods. The getter blocks until a new item is ready on the queue. It can be used also as a synchronization mechanism between two threads
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Observable;
    import java.util.Observer;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.ConcurrentHashMap;
    
    public class ClassWithQueue {
    
    	private ArrayBlockingQueue<String> incomingTextMessages;
    	
    	public StubIPCJ(){
    		incomingTextMessages = new ArrayBlockingQueue<String>(1000);
    	}
    	
    	public String getTextMessage(){
    		String msg = null;
    		try {			
    			msg = incomingTextMessages.take();
    		} catch (InterruptedException e) {
    			log.error("ipcGetFrame failure: " + e.getMessage());
    			return null;
    		}
    			
    		return msg; 		
    	}
    
    	public void addToQueue(String obj) {		
    		synchronized(incomingTextMessages){
    			try {
    				incomingTextMessages.add(obj);
    			}catch(IllegalStateException ew){
    				incomingTextMessages.poll();
    				incomingTextMessages.add(obj);
    			}
    		}								
    	}
    }
    

    public by sidlors  2316  2  6  1

    Consume Message from Queue

    Es el minimo codigo para consumir un mensaje, hace falta agregar mas clases para soportar topic, mensajes mas generales y no solo de texto, etc...
    // Enter here the actual content of the snippet.            
    //Import the JMS API classes.
    import javax.jms.*;
    
    public class HelloWorldMessage implements MessageListener {
    	public void onMessage(Message message) {
    		/* Unpack and handle the messages received */
    		String newStockData = null;
    		/* Unpack and handle the messages received */
    		try {
    			newStockData = ((TextMessage) message).getText();
    		} catch (JMSException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		if (newStockData != null) {
    			/* Logic related to the data */
    		}
    	}
    }

    public by panshulgupta  2175  2  5  0

    Java Queue

    Using queues to iterate over a collection which can add elements during iteration of the collection
    Queue<Integer> queue = new LinkedList<Integer>();
    queue.add(1);
    queue.add(2);
    queue.add(3);
    queue.add(4);
    
    while (!queue.isEmpty()) {
        Integer i = queue.remove();
        if (i == 2)
            queue.add(42);
    
        System.out.println(i);
    }

    public by dave83  2691  1  7  4

    How to create an asynchronous MessageListener in JMS

    This code is an example of Java Message Service message listener implementation. It shows how to create an asynchronous MessageListener, in order to receive message asynchronously as they are delivered to the message consumer. The client needs to create a message listener that implements the MessageListener interface. The MessageListener is as
    //Import the JMS API classes.
    import javax.jms.*;
    
    public class HelloWorldMessage implements MessageListener {
    	public void onMessage(Message message) {
    		/* Unpack and handle the messages received */
    		String newStockData = null;
    		/* Unpack and handle the messages received */
    		try {
    			newStockData = ((TextMessage) message).getText();
    		} catch (JMSException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		if (newStockData != null) {
    			/* Logic related to the data */
    		}
    	}
    }

    public by dave83  2762  1  6  2

    How to send messages using MessageProducer in JMS

    The code shows how to send messages using a MessageProducer in Java Message Service. Destination object is the queue where to send, read as JNDI lookup queue. The Session used is not transactional and auto acknowledged. Note the delivery mode of send method is set to Persistent, so the message will be persisted by JMS broker and its delivery wil
    // Load JNDI properties
    Properties properties = new Properties();            
    properties.load(this.getClass().getResourceAsStream("my.properties"));
    
    //Create the initial context       
    Context ctx = new InitialContext(properties);
    		            
    // look up destination and connection factory
    Destination destination = (Destination)ctx.lookup("myQueue");
    ConnectionFactory conFac = (ConnectionFactory)ctx.lookup("Connectionfactory");
    Connection connection = conFac.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(destination);
    TextMessage message;
    
    // Send a series of messages in a loop
    for (int i = 1; i < 100; i++)
    {
        message = session.createTextMessage("Message " + i);
        messageProducer.send(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);             
    }
    • Public Snippets
    • Channels Snippets