working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,643 snippets matching: callback

    public by micurs  748011  18  7  0

    JQuery typescript interface for $.ajax() callbacks

    To use JQuery $.ajax() you must define your callback functions with the following interfaces
    interface OnSuccessAjaxCallback {
      (data: any, textStatus?: string, jqXHR?: JQueryXHR): any;
    }
    interface OnErrorAjaxCallback {
      (jqXHR?: JQueryXHR, textStatus?: string, errorThrow?: string) : any;
    }
    

    public by cghersi  105512  654  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 sTiLL-iLL  2060  1  7  16

    use Cheez to slow rapid-firing callbacks and animations

    //'Cheez' slows callbacks, kinda like underscore's unbounce
     
    function Cheez(restFor, instant, fnc) {
        var tmOt,
        slam = function() {
            var args = arguments,
            slf = this,
            
            nxter = function() {
                tmOt = null;
                if (!instant){
                  fnc.apply(slf, args);
                }
            };
            
            var goNow = instant && !tmOt;
            clearTimeout(tmOt);
            tmOt = setTimeout(nxter, restFor);
            
            if (goNow){
              fnc.apply(slf, args);
            }
        };
        
       return slam;
    }
     
    // every 350 ms
    window.addEventListener('resize',
        Cheez(function(evt) {
          // somethin....
        },
    350));

    public by sTiLL-iLL @ SniPitz-KND  3102  1  7  19

    Promise-Defer..... then-bindsTo (100% working)

    highly performant async transmission agent. functional units are expressed with a declarative syntax. Just try and break this promise,
    // deferred execution!!!
    
    this.Promise = function () {
    		return {
    			status: 'pending',
    			error: null,
    			posCBKs: [],
    			negCBKs: [],
    			then: function (posCBK, negCBK) {
    				var defer = new Deferred();
    				posCBK = (!posCBK)? function(d){d = (d || true); return d;}:posCBK;
    				negCBK = (!negCBK)? function(d){d = (d || true); return d;}:negCBK;
    				this.posCBKs.push({
    					func: posCBK,
    					deferred: defer
    				});				
    				this.negCBKs.push({
    					func: negCBK,
    					deferred: defer
    				});
    				if (status === 'resolved') {
    					this.execAction({
    						func: posCBK,
    						deferred: defer
    					}, this.data);
    				}
    				else if (status === 'rejected') {
    					this.execAction({
    						func: negCBK,
    						deferred: defer
    					}, this.error);
    				}
    				return defer.promise;
    			},
    			execAction: function (callbackData, result) {
    				wdw.setTimeout(function () {
    					var res = callbackData.func(result);
    					if (res instanceof Promise) {
    						callbackData.deferred.bind(res);
    					}
    					else {
    						callbackData.deferred.resolve(res);
    					}
    				}, 0);
    			}
    		};
    	};
    	this.Deferred = function () {
    		return {
    			promise: new Promise(),
    			resolve: function (data) {
    				var pms = this.promise;
    				pms.data = data;
    				pms.status = 'resolved';
    				if (pms.posCBKs) {
    					pms.posCBKs.forEach(function (dta) {
    						pms.execAction(dta, data);
    					});
    				}
    			},
    			reject: function (err) {
    				var pms = this.promise;
    				pms.error = err;
    				pms.status = 'rejected';
    				if (pms.negCBks) {
    					pms.negCBKs.forEach(function (dta) {
    						pms.execAction(dta, err);
    					});
    				}
    			},
    			bind: function (promise) {
    				var slf = this;
    				promise.then(function (dta) {
    					slf.resolve(dta);
    				}, function (err) {
    					slf.reject(err);
    				});
    			}
    		};
    	};

    public by lbottaro  2797  1  7  5

    Observer Listener Design Pattern implementation in java

    The code shows how to realize a simple listener in java, implementing the observer design pattern. The listener defines a callback method, which arguments has the Observes annotation. The observed event is the invocation of methods annotated with annotation IPersonMethodInvoke. In this way the observer will be notified every time the observed me
    package com.test.example.person.listener;
    
    import javax.enterprise.event.Observes;
    
    import com.test.example.interfaces.*;
    
    public class PersonListener {
    
    	public void OnEvent(@Observes @IPersonMethodInvoke String s)
    	{
    		System.out.println("Event callback: " + s);
    	}
    
    }
    

    public by lbottaro  4524  5  7  5

    How to sort a Javascript array parsing elements using regex pattern

    The Javascript Array.sort() method accepts a callback function to compare two elements of the array using a specific logic. The callback function below may help you in sorting an array matching a particular regular expression pattern. The format of elements in array is x/y/z, where x, y and z are integers, eg "5/10/2". I need to sort the eleme
    var myCompare = function(a,b) {
    	var matchPattern_A = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(a);
    	var matchPattern_B = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(b);
    
    	if(matchPattern_A && matchPattern_B)
    	{
    		//Apply regex sort
    		//I need to sort based on match[1], match[2], match[3]
    		console.log('Apply regex sort');
    
    		if (parseInt(matchPattern_A[1], 10) < parseInt(matchPattern_B[1], 10))
    			return -1;
    		if (parseInt(matchPattern_A[1], 10) > parseInt(matchPattern_B[1], 10))
    			return 1;
    		else {
    			if (parseInt(matchPattern_A[2], 10) < parseInt(matchPattern_B[2], 10))
    				return -1;
    			if (parseInt(matchPattern_A[2], 10) > parseInt(matchPattern_B[2], 10))
    				return 1;
    			else {
    				if (parseInt(matchPattern_A[3], 10) < parseInt(matchPattern_B[3], 10))
    					return -1;
    				if (parseInt(matchPattern_A[3], 10) > parseInt(matchPattern_B[3], 10))
    					return 1;
    				return 0;
    			}
    		}
    	}
    	else {
    		//Apply basic lexicographic sort
    		console.log('Apply basic lexicographic sort');
    		if (a < b)
    			return -1;
    		if (a > b)
    			return 1;
    		return 0;
    	}
    };
    
    var myArr = [ '5/4/30', '5/10/2', '5/4/3', '1/3/8'];
    console.log(myArr);
    myArr.sort(this.myCompare);
    console.log(myArr);
    
    /*  Example,
        having an array as
        ['5/4/30', '5/10/2', '5/4/3', '1/3/8']
        it will be sorted as
        ['1/3/8', '5/4/3', '5/4/30', '5/10/2']
    */            

    public by lbottaro  13344  67  8  0

    Using lambda function to pass extra argument to slots using PyQt4 python

    When programming with PyQt is useful to pass extra arguments to slots callback methods, in order to execute some code when a UI control's action is invoked. In this example you can see the usage of lambda expression to pass the extra argument to the method invoked when pressing a button. Thanks to http://eli.thegreenplace.net/2011/04/25/passi
    self.greeting = QLabel('', self)
    
    # Create the build button with its caption
    self.build_button = QPushButton('&Build Greeting', self)
     
    # Connect the button's clicked signal to AddControl
    self.build_button.clicked.connect(lambda: self.AddControl('fooData'))
    
    def AddControl(self, name):
        self.greeting.setText('%s!' % (name))
    
    

    public by cghersi  8150  2  7  2

    Java SWT: Combobox with AutoSuggestion feature

    This component can be safely used when you want to have a combobox with the capability to display automatic filtered suggestions based on the text already entered. It uses a couple of callback actions so that the caller can specify what to do when ENTER key is hit and how to load suggestions. The call back actions are specified by a simple interf
    package com.snip2code.ui.swt;
    
    import java.util.List;
    import java.util.Random;
    
    import org.apache.log4j.Logger;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.custom.StackLayout;
    import org.eclipse.swt.events.FocusAdapter;
    import org.eclipse.swt.events.FocusEvent;
    import org.eclipse.swt.events.KeyAdapter;
    import org.eclipse.swt.events.KeyEvent;
    import org.eclipse.swt.events.MouseAdapter;
    import org.eclipse.swt.events.MouseEvent;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.layout.FillLayout;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Control;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Table;
    import org.eclipse.swt.widgets.TableItem;
    import org.eclipse.swt.widgets.Text;
    
    import com.snip2code.utils.Utils;
    
    
    /**
     * (c) 2011 snip2code inc.
     * This software is property of snip2code inc. Use or reproduction without permission is prohibited 
     *
     * This widget creates a textfield with an autosuggestion feature.
     * The list of suggestion is shown when the user clicks on the text field or starts typing in the text field
     */
    public class AutoSuggestionComposite extends Composite {
    
    	protected static Logger log = Logger.getLogger(AutoSuggestionComposite.class);
    	
    	private Composite textBoxStackPanel;
    	private StackLayout textboxLayout;
    	private Text textBox;
    	private Label tooltip;
    	private Shell popupShell;
    	private Table table;
    	private String tooltipMsg;
    
    	private ICallback<String, List<String>> loadSuggestionAction;
    	private ICallback<String, String> onEnterAction;
    	
    	private String text;
    	private int numOfDisplayedSuggestions;
    	
    	private static final String POPUPVISIB = "$$$POPUP_VISIB";
    	
    	private String uniqueID; //used to differentiate AutoSuggestion composites in the same dialog
    	private static Random rdn = new Random();
    	
    	/**
    	 * Create the dialog.
    	 * @param parent
    	 * @param style
    	 * @param tooltipMsg message to display when no input is entered
    	 * @param numOfDisplayedSuggestions masimum number of items suggested in the popup of suggestions
    	 * @param loadSuggestionAction callback to routine that loads the suggestions for autocomplete
    	 * @param onEnterAction callback when enter is pressed on the textbox
    	 */
    	public AutoSuggestionComposite(Composite parent, int style, String tooltipMsg, int numOfDisplayedSuggestions, 
    			ICallback<String, List<String>> loadSuggestionAction, ICallback<String, String> onEnterAction) {
    		super(parent, style);
    
    		textboxLayout = new StackLayout();
    		this.loadSuggestionAction = loadSuggestionAction;
    		this.onEnterAction = onEnterAction;
    		this.numOfDisplayedSuggestions = numOfDisplayedSuggestions;
    		this.tooltipMsg = tooltipMsg;
    		
    		uniqueID = rdn.nextInt() + tooltipMsg;
    		
    		createDialogArea();
    	}
    	
    	private void createDialogArea() {
    		this.setBackground(SWTUIUtilities.WHITE);
    		GridLayout gridLayout = new GridLayout();
    		gridLayout.marginHeight = 0;
    		gridLayout.marginWidth = 0;
    		this.setLayout(gridLayout);
    
    		//Panel with textbox and tooltip:
    		textBoxStackPanel = new Composite(this, SWT.NONE);
    		textBoxStackPanel.setLayout(textboxLayout);
    		GridData gdPanel = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
    		gdPanel.verticalIndent = 2;
    		textBoxStackPanel.setLayoutData(gdPanel);
    		
    		tooltip = new Label(textBoxStackPanel, SWT.NONE);
    		tooltip.setBackground(SWTUIUtilities.WHITE);
    		tooltip.setForeground(SWTUIUtilities.LIGHT_GREY);
    		tooltip.setFont(SWTUIUtilities.LBL_TEXT);
    		tooltip.setText(" " + tooltipMsg); //manual horizontal indent, cause StackLayout doesn't allow this feature
    		tooltip.addMouseListener(new MouseAdapter() {
    			@Override
    			public void mouseDown(MouseEvent e) {
    				setControlVisib(textBox, true);
    				textBoxStackPanel.layout();
    				textBox.setFocus();
    				loadSuggestions(null);
    			}
    		});
    		
    		textBox = new Text(textBoxStackPanel, SWT.NONE);
    		textBox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
    		textBox.setFont(SWTUIUtilities.LBL_TEXT);
    		textBox.setBackground(SWTUIUtilities.WHITE);
    		textBox.setData(POPUPVISIB, uniqueID);
    		
    		//popup for suggestions:
    		popupShell = new Shell(getShell().getDisplay(), SWT.ON_TOP);
    		popupShell.setLayout(new FillLayout());
    		popupShell.setData(POPUPVISIB, uniqueID);
    		popupShell.setBackground(SWTUIUtilities.WHITE);
    		table = new Table(popupShell, SWT.SINGLE);
        	table.getVerticalBar().setVisible(false);
    		table.setFont(SWTUIUtilities.LBL_TEXT);
    		table.setData(POPUPVISIB, uniqueID);
    		for (int i = 0; i < numOfDisplayedSuggestions; i++) {
    			new TableItem(table, SWT.NONE);
    		}
    		
    		//Key Listener for Keyboards events:
    		textBox.addKeyListener(new KeyAdapter() {
    			@Override
    			public void keyReleased(KeyEvent e) {
    				boolean loadSuggestions = true;
    				saveInput();
    				switch (e.keyCode) {
    					case SWT.ARROW_DOWN:
    						int index = (table.getSelectionIndex() + 1) % table.getItemCount();
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.ARROW_UP:
    						index = table.getSelectionIndex() - 1;
    						if (index < 0) 
    							index = table.getItemCount() - 1;
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.CR:
    					case SWT.LF:
    					case 16777296: //enter in numeric keypad
    						if (popupShell.isVisible() && table.getSelectionIndex() != -1) {
    							textBox.setText(table.getSelection()[0].getText());
    						}
    						
    						loadSuggestions = false;
    						execEnterAction();
    
    						break;
    					case SWT.ESC:
    						popupShell.setVisible(false);
    						break;
    				}
    
    				//only for printable characters, load search history:
    				if (loadSuggestions && (e.keyCode < 256))
    					loadSuggestions(textBox.getText());
    				
    				log.debug("End of key listener");
    			}
    		});
    		
    		//make sure the input entered in the text box is saved and ready to use:
    		textBox.addFocusListener(new FocusAdapter() {
    			@Override
    			public void focusLost(FocusEvent e) {
    				log.debug("Focus lost by textbox of autosugg from " + tooltipMsg);
    				saveInput();
    				checkTooltipVisib();
    				handleFocusLost();
    			}
    			
    			@Override
    			public void focusGained(FocusEvent e) {
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				log.debug("Focus gained by textbox of autosugg from " + tooltipMsg);
    				loadSuggestions(textBox.getText());
    			}
    		});
    		textBox.addSelectionListener(new SelectionAdapter() {
    			@Override
    			public void widgetSelected(SelectionEvent e) {
    				checkTooltipVisib();
    			}
    		});
    		
    		table.addListener(SWT.DefaultSelection, new Listener() {
    			public void handleEvent(Event event) {
    				textBox.setText(table.getSelection()[0].getText());
    				execEnterAction();
    			}
    		});
    		
    		//hide the popup of suggestions if the focus is out:
    		Listener focusOutListener = new Listener() {
    			public void handleEvent(Event event) {
    				handleFocusLost();
    			}
    		};
    		table.addListener(SWT.FocusOut, focusOutListener);
    		textBox.addListener(SWT.FocusOut, focusOutListener);
    		textBoxStackPanel.addListener(SWT.FocusOut, focusOutListener);
    		popupShell.addListener(SWT.FocusOut, focusOutListener);
    		this.addListener(SWT.FocusOut, focusOutListener);
    
    		getShell().addListener(SWT.Move, new Listener() {
    			public void handleEvent(Event event) {
    				popupShell.setVisible(false);
    				checkTooltipVisib();
    			}
    		});
    		
    		checkTooltipVisib();
    	}
    	
    	private void handleFocusLost() {
    		/* async is needed to wait until focus reaches its new Control */
    		if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    			return;
    		getShell().getDisplay().asyncExec(new Runnable() {
    			public void run() {
    				log.debug("Running handleFocusLost for " + tooltipMsg);
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				Control control = getShell().getDisplay().getFocusControl();
    				log.debug("handleFocusLost for " + tooltipMsg + ": control is " + control + ";uniqueID:" + uniqueID);
    				if ((control == null) || (control.getData(POPUPVISIB) == null) || 
    					!control.getData(POPUPVISIB).toString().equals(uniqueID)) {
    					popupShell.setVisible(false);
    				}					
    			}
    		});
    	}
    	
    	/**
    	 * Determines the visibility of textbox content vs tooltip when the textbox is empty
    	 */
    	public void checkTooltipVisib() {
    		if (Utils.isNullOrEmpty(textBox.getText())) 
    			setControlVisib(tooltip, true);
    		else
    			setControlVisib(textBox, true);
    		textBoxStackPanel.layout();
    	}
    	
    	private void execEnterAction() {
    		saveInput();
    		popupShell.setVisible(false);
    		onEnterAction.exec(text);
    	}
    	
        private void loadSuggestions(String prefix) {
        	log.debug("loading suggestions for " + prefix);
    
    //		if (Utils.isNullOrEmpty(prefix))
    //			return;
        	
        	Rectangle textBounds = getShell().getDisplay().map(textBoxStackPanel, null, textBox.getBounds());
        	
    		//load suggestions:
        	List<String> suggestions = loadSuggestionAction.exec(prefix);
        	log.debug("loaded " + suggestions.size() + " suggestions");
        	
        	table.setItemCount(suggestions.size());
    		TableItem[] items = table.getItems();
    		int maxWidthOfItem = 0;
    		log.debug("Changing " + items.length + " items in TablePopup");
    		for (int i = 0; i < items.length; i++) {
    			if (i < suggestions.size()) {
    				String sugg = suggestions.get(i);
    				if (!Utils.isNullOrEmpty(sugg)) {
    					items[i].setText(sugg);
    					int w = items[i].getBounds().width;
    					if (w > maxWidthOfItem)
    						maxWidthOfItem = w;
    				}
    			}
    		}
    //		//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    //		if ((maxWidthOfItem + 10) < textBounds.width)
    //			table.pack();
    		
    		//23 pixels is the height of 1 item in the drop down list; 
    		//always add a blank line at the end of the list to improve readability
    		int popupHeight = (suggestions.size() + 1) * 23; 
    		log.debug("popupHeight for [" + this.tooltipMsg + "]:" + popupHeight);
    		if (popupHeight <= 46)
    			popupHeight = 46; 
    	
    		//set a cap to the maximum height of the popup (17 lines):
    		if (popupHeight > 391) {
    			popupHeight = 391;
    			table.getVerticalBar().setVisible(true);
    		} else {
    			//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    			if ((maxWidthOfItem + 10) < textBounds.width)
    				table.pack();
    			table.getVerticalBar().setVisible(false);
    		}
    		
    		log.debug("setBounds popup:" + textBounds.x + ";" + (textBounds.y + textBounds.height + 4) + ";" + 
    					textBounds.width + ";" + popupHeight);
    		popupShell.setBounds(textBounds.x, textBounds.y + textBounds.height + 4, textBounds.width, popupHeight);
    		popupShell.setVisible(true);		
        }
        
    	private void setControlVisib(Control c, boolean visible) {
    		if (c == null)
    			return;
    		
    		if (visible) 
    			textboxLayout.topControl = c;
    	}
    	
    	private void saveInput() {
    		text = textBox.getText();
    		if (text == null)
    			text = "";
    		text = text.trim();
    	}
    	
    	/**
    	 * Returns the content of the textbox
    	 */
    	public String getText() {
    		return text;
    	}
    	
    	/**
    	 * Sets the content of the textbox
    	 */
    	public void setText(String text) {
    		this.text = text;
    		textBox.setText(text);
    		setControlVisib(textBox, true);
    	}
    	
    	/**
    	 * Hides the popup of suggestions
    	 */
    	public void hideSuggestions() {
    		popupShell.setVisible(false);
    	}
    	
    	@Override
    	public void dispose() {
    		if (popupShell != null) {
    			hideSuggestions();
    			popupShell.dispose();
    		}
    
    		super.dispose();
    	}
    }

    public by cghersi  5820  1  8  3

    How to retrieve GMail contacts via API, using OAuth2 token and not username/password credentials

    This class takes charge of the interaction with Google Contacts API, authenticating with an AccessToken authorization flow. In this way the final user should type the credentials in the Google form and not in your form. The "token" parameter of GetContacts() method is the one sent by Google to the callback url specified in the static constant "s_
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Google.Contacts;
    using Google.GData.Contacts;
    using Google.GData.Client;
    using Google.GData.Extensions;
    
    namespace Contact.Utils
    {
      /// <summary>
      /// Summary description for GmailHelper
      /// </summary>
      public class GmailHelper
      {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
        private static fastJSON.JSON jsonUtils = EntityUtils.InitJSONUtils();
    
        private static readonly string APP_NAME = "my app name";
        private static readonly string s_ClientId = "client id given by Google";
        private static readonly string s_ClientSecret = "secret given by Google;
        private static readonly string s_accessTokenUrl = "https://accounts.google.com/o/oauth2/token";
        private static readonly string s_redirUri = WebConfig.Current.PublicPath + "User/GmailCallback";
    
        #region PUBLIC API
        //////////////////////////////////////////////////////////////////////////////////////////////////////
    
        public static string GetRedirUriForContacts()
        {
          return string.Format("https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&redirect_uri={0}&response_type=code&client_id={1}",
            s_redirUri, s_ClientId);
        }
    
        public static List<SimpleContact> GetContacts(string token)
        {
          List<SimpleContact> results = new List<SimpleContact>();
    
          //exchange the code for a token:
          string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
            token, s_ClientId, s_ClientSecret, s_redirUri);
          string accessTokenResp = Utilities.SendHttpRequest(s_accessTokenUrl, postData, true);
          if (string.IsNullOrEmpty(accessTokenResp))
            return results;
    
          AccessTokenStruct parsedJson = null;
          try
          {
            parsedJson = jsonUtils.ToObject<AccessTokenStruct>(accessTokenResp); 
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot deserialize access token response: '{0}' due to {1}", accessTokenResp, e.Message);
            return results;
          }
          if (parsedJson == null)
            return results;
    
          //ask for contacts:
          RequestSettings settings = new RequestSettings(APP_NAME, parsedJson.access_token); 
          settings.AutoPaging = true;
          ContactsRequest cr = new ContactsRequest(settings);
          Feed<Contact> contactsFeed = cr.GetContacts();
          IEnumerable<Contact> contacts = null;
          if (contactsFeed != null)
            contacts = contactsFeed.Entries;
          if (contacts == null)
            return results;
    
          try
          {
            foreach (SimpleContact c in contacts)
            {
              if (c.PrimaryEmail == null)
                continue;
              string preferredEmail = c.PrimaryEmail.Address;
              if (string.IsNullOrEmpty(preferredEmail))
                continue;
              string[] otherEmails = null;
              if (c.Emails != null)
                otherEmails = c.Emails.Select(e => e.Address).ToArray();
              S2CContact contact = new S2CContact((c.Name == null ? "" : c.Name.FullName), 
                                                  preferredEmail, otherEmails);
              results.Add(contact);
            }
          }
          catch (Exception e)
          {
            log.ErrorFormat("Cannot retrieve contacts due to {0}", e.Message);
            return results;
          }
    
          return results;
        }
    
        #endregion
        //////////////////////////////////////////////////////////////////////////////////////////////////////
      }
    
      public class AccessTokenStruct
      {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
    
        public AccessTokenStruct() { }
      }
    
      public class SimpleContact
      {
        public string PreferredEmail { get; set; }
        public string Name { get; set; }
        public string[] Emails { get; set; }
    
        public SimpleContact(string name, string preferredEmail, string[] emails = null)
        {
          Name = name;
          PreferredEmail = preferredEmail;
          if (emails == null)
            Emails = new string[] { preferredEmail };
          else
          {
            List<string> allEmails = new List<string>(emails);
            allEmails.Add(preferredEmail);
            Emails = allEmails.Distinct().ToArray();
          }
        }
    
        public override string ToString()
        {
          if (string.IsNullOrEmpty(Name))
            return PreferredEmail;
          else
            return string.Format("{0} [{1}]", Name, PreferredEmail);
        }
      }
    
    }            

    public by PLAT.ONE @ PLAT.ONE  3397  2  6  0

    How to send and receive an application event in PLAT.ONE

    The sendFrame() method shows how to create and send an application frame representing an event thru the PLAT.ONE JMS messaging system. Note the list of Pair objects that can be attached to the event in order to decorate it with some metadata. The consume() method is the callback of IDirectAMQConsumer interface and is used to parse the incoming ev
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Timer;
    import java.util.TimerTask;
    
    import com.abodata.plat1.data.WSNdataType;
    import com.abodata.plat1.frames.dataTypeCode;
    import com.abodata.plat1.frames.eventCode;
    import com.abodata.plat1.frames.serviceTypeCode;
    import com.abodata.plat1.jms.IDirectAMQConsumer;
    import com.abodata.plat1.jms.Interest;
    import com.abodata.plat1.jms.MsgFormat;
    import com.abodata.plat1.jms.SIPCInterface;
    import com.abodata.plat1.logger.Plat1Logger;
    import com.abodata.plat1.networkInfo.IprotocolType;
    import com.abodata.plat1.networkInfo.IprotocolType.ProtocolTypeRepository;
    import com.abodata.plat1.queues.frames.Frame;
    import com.abodata.plat1.queues.frames.Plat1Event;
    import com.abodata.plat1.utils.DSUtils;
    import com.abodata.plat1.utils.Pair;
    import com.abodata.plat1.utils.Plat1CommonUtils;
    import com.abodata.plat1.ws.velocity.IProxyNetwork;
    import com.abodata.plat1.xmlparse.IJMSFrameParser;
    
    public class ReadWriteEventExample implements IDirectAMQConsumer {
    
    	private static final Plat1Logger log = new Plat1Logger(ReadWriteEventExample.class);
    	
    	private int networkID = 0;
    	private IprotocolType protType = null;
    	
    	public void start() throws Exception {		
    		//retrieve an available network:
    		List<IProxyNetwork> networks = ServiceTest.getApi().DB_GetVisibleNetworks();
    		if (!Plat1CommonUtils.isNullOrEmpty(networks)) {
    			networkID = networks.get(0).getId();
    			protType = ProtocolTypeRepository.get(networks.get(0).getType());
    		}
    		
    		//connect to the interesting topics for the events: 
    		ServiceTest.getSIPC().startConnection(getClass(), 
    				new Interest[] { 
    					new Interest(networkID, serviceTypeCode.appGarden, dataTypeCode.event, 
    						"", MsgFormat.XML, this, false) });
    		
    		//issue a time task to send event frames every 1 second:
    		Timer t = new Timer();
    		t.schedule(new TimerTask() {
    			@Override
    			public void run() {
    				sendFrame();
    			}
    		}, 10, 100000);
    	}
    	
    	private void sendFrame() {
    		//set the arguments of the event:
    		ArrayList<Pair<?>> arguments = new ArrayList<Pair<?>>();
    		arguments.add(new Pair<String>("keyName", "keyValue", WSNdataType.ASCIIStr));
    		
    		//create the frame to send:
    		Frame f = ServiceTest.getFrameParser().getNetworkEventFrame(networkID, // the ID of the network, as source of the event 
    				protType, // the protocol type of the network, as source of the event 
    				serviceTypeCode.appGarden, //the component that originated the event
    				eventCode.custom_app, 	//the type of event
    				arguments);
    
    		// send the frame:
    		getSIPC().ipcSendFrame(f);
    	}
    	
    	public void closeConnection(){
    		log.info("Closing IPC connection");
    		ServiceTest.getSIPC().remove(getClass());
    	}
    
    	@Override
    	public void consume(Frame f) {
    		IJMSFrameParser frmParser = ServiceTest.getFrameParser();
    		Plat1Event event = frmParser.getEventFromFrame(f, eventCode.custom_app);
    		if (event != null)
    			System.out.print("JSON of event:" + event.getArgsAsJson());
    	}
    
    	@Override
    	public boolean isAbleToConsumeFrames() {
    		return true;
    	}
    
    	@Override
    	public void consume(String text) {
    	}
    
    	@Override
    	public boolean isAbleToConsumeTextMessages() {
    		return false;
    	}
    
    	@Override
    	public void consume(byte[] bin) {
    	}
    
    	@Override
    	public boolean isAbleToConsumeBinaryMsg() {
    		return false;
    	}
    	
    	public SIPCInterface getSIPC() {
    		return DSUtils.get(log, ServiceTest.sipc, getClass().getCanonicalName(), true);
    	}
    }
    • Public Snippets
    • Channels Snippets