working on it ...

Filters

Explore Public Snippets

Sort by

Found 60k snippets matching: java

    public by maindog modified Dec 18, 2013  10056608  3306  11  17

    javascript cheat for A Dark Room v1.3

    (can be used on chrome using the javascript console) After you get a hut and someone joins your village (not the builder) this code will provide you with a lot of wood, allowing you to build more huts, traps and other buildings once you have the resources. (does not purchase the buildings and for the mines you still have to find them on the map)
    /**
     * Module that registers the outdoors functionality
     */
    var Outside = {
    	name: "Outside",
    	
    	_GATHER_DELAY: 60,
    	_TRAPS_DELAY: 90,
    	_POP_DELAY: [0.5, 3],
    	
    	_INCOME: {
    		'gatherer': {
    			delay: 1,
    			stores: {
    				'wood': 10000
    			}
    		},
    		'hunter': {
    			delay: 1,
    			stores: {
    				'fur': 10000,
    				'meat': 10000,
    				'alien alloy': 10000,
    				'medicine': 10000
    			}
    		},
    		'trapper': {
    			delay: 1,
    			stores: {
    				'meat': 10000,
    				'bait': 10000,
    				'teeth': 10000,
    				'scales': 10000
    			}
    		},
    		'tanner': {
    			delay: 1,
    			stores: {
    				'fur': 100000,
    				'leather': 100000
    			}
    		},
    		'charcutier': {
    			delay: 1,
    			stores: {
    				'meat': 100000,
    				'wood': 100000,
    				'cured meat': 100000
    			}
    		},
    		'iron miner': {
    			delay: 1,
    			stores: {
    				'cured meat': 100000,
    				'iron': 100000
    			}
    		},
    		'coal miner': {
    			delay: 1,
    			stores: {
    				'cured meat': 100000,
    				'coal': 100000
    			}
    		},
    		'sulphur miner': {
    			delay: 1,
    			stores: {
    				'cured meat': 100000,
    				'sulphur': 100000
    			}
    		},
    		'steelworker': {
    			delay: 1,
    			stores: {
    				'iron': 100000,
    				'coal': 100000,
    				'steel': 100000
    			}
    		},
    		'armourer': {
    			delay: 1,
    			stores: {
    				'steel': 100000,
    				'sulphur': 10000,
    				'bullets': 100000
    			}
    		}
    	},
    	
    	TrapDrops: [
    		{
    			rollUnder: 0.5,
    			name: 'fur',
    			message: 'scraps of fur'
    		},
    		{
    			rollUnder: 0.75,
    			name: 'meat',
    			message: 'bits of meat'
    		},
    		{
    			rollUnder: 0.85,
    			name: 'scales',
    			message: 'strange scales'
    		},
    		{
    			rollUnder: 0.93,
    			name: 'teeth',
    			message: 'scattered teeth'
    		},
    		{
    			rollUnder: 0.995,
    			name: 'cloth',
    			message: 'tattered cloth'
    		},
    		{
    			rollUnder: 1.0,
    			name: 'charm',
    			message: 'a crudely made charm'
    		}
    	],
    	
    	init: function(options) {
    		this.options = $.extend(
    			this.options,
    			options
    		);
    		
    		if(Engine._debug) {
    			this._GATHER_DELAY = 0;
    			this._TRAPS_DELAY = 0;
    		}
    		
    		// Create the outside tab
    		this.tab = Header.addLocation("A Silent Forest", "outside", Outside);
    		
    		// Create the Outside panel
    		this.panel = $('<div>').attr('id', "outsidePanel")
    			.addClass('location')
    			.appendTo('div#locationSlider');
    		
    		//subscribe to stateUpdates
    		$.Dispatch('stateUpdate').subscribe(Outside.handleStateUpdates);
    		
    		if(typeof $SM.get('features.location.outside') == 'undefined') {
    			$SM.set('features.location.outside', true);
    			if(!$SM.get('game.buildings')) $SM.set('game.buildings', {});
    			if(!$SM.get('game.population')) $SM.set('game.population', 0);
    			if(!$SM.get('game.workers')) $SM.set('game.workers', {});
    		}
    		
    		this.updateVillage();
    		Outside.updateWorkersView();
    		
    		Engine.updateSlider();
    		
    		// Create the gather button
    		new Button.Button({
    			id: 'gatherButton',
    			text: "gather wood",
    			click: Outside.gatherWood,
    			cooldown: Outside._GATHER_DELAY,
    			width: '80px'
    		}).appendTo('div#outsidePanel');
    	},
    	
    	getMaxPopulation: function() {
    		return $SM.get('game.buildings["hut"]', true) * 4;
    	},
    	
    	increasePopulation: function() {
    		var space = Outside.getMaxPopulation() - $SM.get('game.population');
    		if(space > 0) {
    			var num = Math.floor(Math.random()*(space/2) + space/2);
    			if(num == 0) num = 1;
    			if(num == 1) {
    				Notifications.notify(null, 'a stranger arrives in the night');
    			} else if(num < 5) {
    				Notifications.notify(null, 'a weathered family takes up in one of the huts.');
    			} else if(num < 10) {
    				Notifications.notify(null, 'a small group arrives, all dust and bones.');
    			} else if(num < 30) {
    				Notifications.notify(null, 'a convoy lurches in, equal parts worry and hope.');
    			} else {
    				Notifications.notify(null, "the town's booming. word does get around.");
    			}
    			Engine.log('population increased by ' + num);
    			$SM.add('game.population', num);
    		}
    		Outside.schedulePopIncrease();
    	},
    	
    	killVillagers: function(num) {
    		$SM.add('game.population', num * -1);
    		if($SM.get('game.population') < 0) {
    			$SM.set('game.population', 0);
    		}
    		var remaining = Outside.getNumGatherers();
    		if(remaining < 0) {
    			var gap = -remaining;
    			for(var k in $SM.get('game.workers')) {
    				var num = $SM.get('game.workers["'+k+'"]');
    				if(num < gap) {
    					gap -= num;
    					$SM.set('game.workers["'+k+'"]', 0);
    				} else {
    					$SM.add('game.workers["'+k+'"]', gap * -1);
    					break;
    				}
    			}
    		}
    	},
    	
    	schedulePopIncrease: function() {
    		var nextIncrease = Math.floor(Math.random()*(Outside._POP_DELAY[1] - Outside._POP_DELAY[0])) + Outside._POP_DELAY[0];
        	Engine.log('next population increase scheduled in ' + nextIncrease + ' minutes');
        	Outside._popTimeout = setTimeout(Outside.increasePopulation, nextIncrease * 60 * 1000);
    	},
    	
    	updateWorkersView: function() {
    		var workers = $('div#workers');
    
    		// If our population is 0 and we don't already have a workers view,
    		// there's nothing to do here.
    		if(!workers.length && $SM.get('game.population') == 0) return;
    
    		var needsAppend = false;
    		if(workers.length == 0) {
    			needsAppend = true;
    			workers = $('<div>').attr('id', 'workers').css('opacity', 0);
    		}
    		
    		var numGatherers = $SM.get('game.population');
    		var gatherer = $('div#workers_row_gatherer', workers);
    		
    		for(var k in $SM.get('game.workers')) {
    			var workerCount = $SM.get('game.workers["'+k+'"]');
    			var row = $('div#workers_row_' + k.replace(' ', '-'), workers);
    			if(row.length == 0) {
    				row = Outside.makeWorkerRow(k, workerCount);
    				
    				var curPrev = null;
    				workers.children().each(function(i) {
    					var child = $(this);
    					var cName = child.attr('id').substring(12).replace('-', ' ');
    					if(cName != 'gatherer') {
    						if(cName < k && (curPrev == null || cName > curPrev)) {
    							curPrev = cName;
    						}
    					}
    				});
    				if(curPrev == null && gatherer.length == 0) {
    					row.prependTo(workers);
    				} 
    				else if(curPrev == null)
    				{
    					row.insertAfter(gatherer);
    				} 
    				else 
    				{
    					row.insertAfter(workers.find('#workers_row_' + curPrev.replace(' ', '-')));
    				}
    				
    			} else {
    				$('div#' + row.attr('id') + ' > div.row_val > span', workers).text(workerCount);
    			}
    			numGatherers -= workerCount;
    			if(workerCount == 0) {
    				$('.dnBtn', row).addClass('disabled');
    				$('.dnManyBtn', row).addClass('disabled');
    			} else {
    				$('.dnBtn', row).removeClass('disabled');
    				$('.dnManyBtn', row).removeClass('disabled');
    			}
    		}
    		
    		if(gatherer.length == 0) {
    			gatherer = Outside.makeWorkerRow('gatherer', numGatherers);
    			gatherer.prependTo(workers);
    		} else {
    			$('div#workers_row_gatherer > div.row_val > span', workers).text(numGatherers);
    		}
    		
    		if(numGatherers == 0) {
    			$('.upBtn', '#workers').addClass('disabled');
    			$('.upManyBtn', '#workers').addClass('disabled');
    		} else {
    			$('.upBtn', '#workers').removeClass('disabled');
    			$('.upManyBtn', '#workers').removeClass('disabled');
    		}
    		
    		
    		if(needsAppend && workers.children().length > 0) {
    			workers.appendTo('#outsidePanel').animate({opacity:1}, 300, 'linear');
    		}
    	},
    	
    	getNumGatherers: function() {
    		var num = $SM.get('game.population'); 
    		for(var k in $SM.get('game.workers')) {
    			num -= $SM.get('game.workers["'+k+'"]');
    		}
    		return num;
    	},
    	
    	makeWorkerRow: function(name, num) {
    		var row = $('<div>')
    			.attr('id', 'workers_row_' + name.replace(' ','-'))
    			.addClass('workerRow');
    		$('<div>').addClass('row_key').text(name).appendTo(row);
    		var val = $('<div>').addClass('row_val').appendTo(row);
    		
    		$('<span>').text(num).appendTo(val);
    		
    		if(name != 'gatherer') {
    		  $('<div>').addClass('upManyBtn').appendTo(val).click([10], Outside.increaseWorker);
    			$('<div>').addClass('upBtn').appendTo(val).click([1], Outside.increaseWorker);
    			$('<div>').addClass('dnBtn').appendTo(val).click([1], Outside.decreaseWorker);
    			$('<div>').addClass('dnManyBtn').appendTo(val).click([10], Outside.decreaseWorker);
    		}
    		
    		$('<div>').addClass('clear').appendTo(row);
    		
    		var tooltip = $('<div>').addClass('tooltip bottom right').appendTo(row);
    		var income = Outside._INCOME[name];
    		for(var s in income.stores) {
    			var r = $('<div>').addClass('storeRow');
    			$('<div>').addClass('row_key').text(s).appendTo(r);
    			$('<div>').addClass('row_val').text(Engine.getIncomeMsg(income.stores[s], income.delay)).appendTo(r);
    			r.appendTo(tooltip);
    		}
    		
    		return row;
    	},
    	
    	increaseWorker: function(btn) {
    		var worker = $(this).closest('.workerRow').children('.row_key').text();
    		if(Outside.getNumGatherers() > 0) {
    		  var increaseAmt = Math.min(Outside.getNumGatherers(), btn.data);
    			Engine.log('increasing ' + worker + ' by ' + increaseAmt);
    			$SM.add('game.workers["'+worker+'"]', increaseAmt);
    		}
    	},
    	
    	decreaseWorker: function(btn) {
    		var worker = $(this).closest('.workerRow').children('.row_key').text();
    		if($SM.get('game.workers["'+worker+'"]') > 0) {
    		  var decreaseAmt = Math.min($SM.get('game.workers["'+worker+'"]') || 0, btn.data);
    			Engine.log('decreasing ' + worker + ' by ' + decreaseAmt);
    			$SM.add('game.workers["'+worker+'"]', decreaseAmt * -1);
    		}
    	},
    	
    	updateVillageRow: function(name, num, village) {
    		var id = 'building_row_' + name.replace(' ', '-');
    		var row = $('div#' + id, village);
    		if(row.length == 0 && num > 0) {
    			row = $('<div>').attr('id', id).addClass('storeRow');
    			$('<div>').addClass('row_key').text(name).appendTo(row);
    			$('<div>').addClass('row_val').text(num).appendTo(row);
    			$('<div>').addClass('clear').appendTo(row);
    			var curPrev = null;
    			village.children().each(function(i) {
    				var child = $(this);
    				if(child.attr('id') != 'population') {
    					var cName = child.attr('id').substring(13).replace('-', ' ');
    					if(cName < name && (curPrev == null || cName > curPrev)) {
    						curPrev = cName;
    					}
    				}
    			});
    			if(curPrev == null) {
    				row.prependTo(village);
    			} else {
    				row.insertAfter('#building_row_' + curPrev.replace(' ', '-'));
    			}
    		} else if(num > 0) {
    			$('div#' + row.attr('id') + ' > div.row_val', village).text(num);
    		} else if(num == 0) {
    			row.remove();
    		}
    	},
    	
    	updateVillage: function(ignoreStores) {
    		var village = $('div#village');
    		var population = $('div#population');
    		var needsAppend = false;
    		if(village.length == 0) {
    			needsAppend = true;
    			village = $('<div>').attr('id', 'village').css('opacity', 0);
    			population = $('<div>').attr('id', 'population').appendTo(village);
    		}
    		
    		for(var k in $SM.get('game.buildings')) {
    			if(k == 'trap') {
    				var numTraps = $SM.get('game.buildings["'+k+'"]');
    				var numBait = $SM.get('stores.bait', true);
    				var traps = numTraps - numBait;
    				traps = traps < 0 ? 0 : traps;
    				Outside.updateVillageRow(k, traps, village);
    				Outside.updateVillageRow('baited trap', numBait > numTraps ? numTraps : numBait, village);
    			} else {
    				if(Outside.checkWorker(k)) {
    					Outside.updateWorkersView();
    				}
    				Outside.updateVillageRow(k, $SM.get('game.buildings["'+k+'"]'), village);
    			}
    		}
    		
    		population.text('pop ' + $SM.get('game.population') + '/' + this.getMaxPopulation());
    		
    		var hasPeeps;
    		if($SM.get('game.buildings["hut"]', true) == 0) {
    			hasPeeps = false;
    			village.addClass('noHuts');
    		} else {
    			hasPeeps = true;
    			village.removeClass('noHuts');
    		}
    		
    		if(needsAppend && village.children().length > 1) {
    			village.appendTo('#outsidePanel');
    			village.animate({opacity:1}, 300, 'linear');
    		}
    		
    		if(hasPeeps && typeof Outside._popTimeout == 'undefined') {
    			Outside.schedulePopIncrease();
    		}
    		
    		this.setTitle();
    
    		if(!ignoreStores && Engine.activeModule === Outside && village.children().length > 1) {
    			$('#storesContainer').css({top: village.height() + 26 + 'px'});
    		}
    	},
    	
    	checkWorker: function(name) {
    		var jobMap = {
    			'lodge': ['hunter', 'trapper'],
    			'tannery': ['tanner'],
    			'smokehouse': ['charcutier'],
    			'iron mine': ['iron miner'],
    			'coal mine': ['coal miner'],
    			'sulphur mine': ['sulphur miner'],
    			'steelworks': ['steelworker'],
    			'armoury' : ['armourer']
    		};
    		
    		var jobs = jobMap[name];
    		var added = false;
    		if(typeof jobs == 'object') {
    			for(var i = 0, len = jobs.length; i < len; i++) {
    				var job = jobs[i];
    				if(typeof $SM.get('game.buildings["'+name+'"]') == 'number' && 
    						typeof $SM.get('game.workers["'+job+'"]') != 'number') {
    					Engine.log('adding ' + job + ' to the workers list');
    					$SM.set('game.workers["'+job+'"]', 0);
    					added = true;
    				}
    			}
    		}
    		return added;
    	},
    	
    	updateVillageIncome: function() {		
    		for(var worker in Outside._INCOME) {
    			var income = Outside._INCOME[worker];
    			var num = worker == 'gatherer' ? Outside.getNumGatherers() : $SM.get('game.workers["'+worker+'"]');
    			if(typeof num == 'number') {
    				var stores = {};
    				if(num < 0) num = 0;
    				var tooltip = $('.tooltip', 'div#workers_row_' + worker.replace(' ', '-'));
    				tooltip.empty();
    				var needsUpdate = false;
    				var curIncome = $SM.getIncome(worker);
    				for(var store in income.stores) {
    					stores[store] = income.stores[store] * num;
    					if(curIncome[store] != stores[store]) needsUpdate = true;
    					var row = $('<div>').addClass('storeRow');
    					$('<div>').addClass('row_key').text(store).appendTo(row);
    					$('<div>').addClass('row_val').text(Engine.getIncomeMsg(stores[store], income.delay)).appendTo(row);
    					row.appendTo(tooltip);
    				}
    				if(needsUpdate) {
    					$SM.setIncome(worker, {
    						delay: income.delay,
    						stores: stores
    					});
    				}
    			}
    		}
    		Room.updateIncomeView();
    	},
    	
    	updateTrapButton: function() {
    		var btn = $('div#trapsButton');
    		if($SM.get('game.buildings["trap"]', true) > 0) {
    			if(btn.length == 0) {
    				new Button.Button({
    					id: 'trapsButton',
    					text: "check traps",
    					click: Outside.checkTraps,
    					cooldown: Outside._TRAPS_DELAY,
    					width: '80px'
    				}).appendTo('div#outsidePanel');
    			} else {
    				Button.setDisabled(btn, false);
    			}
    		} else {
    			if(btn.length > 0) {
    				Button.setDisabled(btn, true);
    			}
    		}
    	},
    	
    	setTitle: function() {
    		var numHuts = $SM.get('game.buildings["hut"]', true);
    		var title;
    		if(numHuts == 0) {
    			title = "A Silent Forest";
    		} else if(numHuts == 1) {
    			title = "A Lonely Hut";
    		} else if(numHuts <= 4) {
    			title = "A Tiny Village";
    		} else if(numHuts <= 8) {
    			title = "A Modest Village";
    		} else if(numHuts <= 14) {
    			title = "A Large Village";
    		} else {
    			title = "A Raucous Village";
    		}
    		
    		if(Engine.activeModule == this) {
    			document.title = title;
    		}
    		$('#location_outside').text(title);
    	},
    	
    	onArrival: function(transition_diff) {
    		Outside.setTitle();
    		if(!$SM.get('game.outside.seenForest')) {
    			Notifications.notify(Outside, "the sky is grey and the wind blows relentlessly");
    			$SM.set('game.outside.seenForest', true);
    		}
    		Outside.updateTrapButton();
    		Outside.updateVillage(true);
    
    		Engine.moveStoresView($('#village'), transition_diff);
    	},
    	
    	gatherWood: function() {
    		Notifications.notify(Outside, "dry brush and dead branches litter the forest floor");
    		var gatherAmt = $SM.get('game.buildings["cart"]', true) > 0 ? 50 : 10;
    		$SM.add('stores.wood', gatherAmt);
    	},
    	
    	checkTraps: function() {
    		var drops = {};
    		var msg = [];
    		var numTraps = $SM.get('game.buildings["trap"]', true);
    		var numBait = $SM.get('stores.bait', true);
    		var numDrops = numTraps + (numBait < numTraps ? numBait : numTraps);
    		for(var i = 0; i < numDrops; i++) {
    			var roll = Math.random();
    			for(var j in Outside.TrapDrops) {
    				var drop = Outside.TrapDrops[j];
    				if(roll < drop.rollUnder) {
    					var num = drops[drop.name];
    					if(typeof num == 'undefined') {
    						num = 0;
    						msg.push(drop.message);
    					}
    					drops[drop.name] = num + 1;
    					break;
    				}
    			}
    		}
    		var s = 'the traps contain ';
    		for(var i = 0, len = msg.length; i < len; i++) {
    			if(len > 1 && i > 0 && i < len - 1) {
    				s += ", ";
    			} else if(len > 1 && i == len - 1) {
    				s += " and ";
    			}
    			s += msg[i];
    		}
    		
    		var baitUsed = numBait < numTraps ? numBait : numTraps;
    		drops['bait'] = -baitUsed;
    		
    		Notifications.notify(Outside, s);
    		$SM.addM('stores', drops);
    	},
    	
    	handleStateUpdates: function(e){
    		if(e.category == 'stores'){
    			Outside.updateVillage();
    		} else if(e.stateName.indexOf('game.workers') == 0
    		          || e.stateName.indexOf('game.population') == 0){
    			Outside.updateVillage();
    			Outside.updateWorkersView();
    			Outside.updateVillageIncome();
    		};
    	}
    };

    public by cghersi modified Jan 29, 2016  9943797  2399  13  9

    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 lbottaro modified Jan 8, 2014  8454737  2781  10  9

    How to collapse a div in html

    This code shows how to collapse a div using a simple Javascript method. The div display option toggles between 'none' and 'block', hiding or showing its content. In the example you can collapse the div clicking both on a link or on a div, using the onclick event.
    <!doctype html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>Test</title>
    		<script language="javascript"> 
    function toggle(elementId) {
    	var ele = document.getElementById(elementId);
    	if(ele.style.display == "block") {
        		ele.style.display = "none";
      	}
    	else {
    		ele.style.display = "block";
    	}
    } 
    </script>
    	</head>
    	<body>
    <div class="tree">
    <div>
    BLA BLA
    </div>	
    <a id="displayText" href="javascript:toggle('toggleText');">show</a> <== click Here
    <div onclick="javascript:toggle('toggleText');">
    <h1>Hello!</h1>
    <div id="toggleText" style="display:none; border-width:2px; border-style:solid">Hidden data...</div>
    </div>
    <div>
    BLA
    </div>	
    <div>
    BLA BLA 
    </div>	
    <div>
    BLA BLA 123
    </div>
    <a id="displayText" href="javascript:toggle('toggleText2');">show</a> <== click Here
    <div id="toggleText2" style="display: none" href="javascript:toggle();"><h1>Hide!</h1></div>	
    </div></body>
    </html>

    public by micurs modified Mar 4, 2014  6854604  323  10  17

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by MarcoDeMagistris modified Apr 5, 2013  1878180  259  5  0

    Java: How to create a log4j Logger Manager using Singleton

    How to create a log4j Logger Manager using Singleton
    /**
    * LoggerManager class
    * This class implements log4j using Singleton
    */
    import org.apache.log4j.Logger;
    import org.apache.log4j.xml.DOMConfigurator;
    
    public class LoggerManager {
    	public enum LogLevel {DEBUG, INFO, WARNING, ERROR, FATAL};
    	private static LoggerManager obj;
    	private Logger oLog;
    	
    	private LoggerManager(){
    		/*
    		* Config.xml: file path used to configure log4j
    		*/
    		DOMConfigurator.configure("Config.xml");
    	}
    	
    	public LoggerManager(Logger logger) {
    		this();
    		setLogger(logger);
    	}
    
    	private void setLogger(Logger _oLog)
    	{
    		oLog = _oLog;
    	}
    	
    	public static LoggerManager getLogger(){
    		if (obj == null)
    			obj = new LoggerManager(Logger.getLogger(LoggerManager.class));
    		
    		return obj;
    	}
    	
    	public void Log(String _sMsg, LoggerManager.LogLevel _eLogLevel){
    		switch(_eLogLevel){
    			case DEBUG:
    				oLog.debug(_sMsg);
    				break;
    			case INFO:
    				oLog.info(_sMsg);
    				break;
    			case WARNING:
    				oLog.warn(_sMsg);
    				break;
    			case ERROR:
    				oLog.error(_sMsg);
    				break;
    			case FATAL:
    				oLog.fatal(_sMsg);
    				break;
    			default:
    				
    		}
    	}
    }
    
    /**
    * Main class
    * ex. Logger Manager example
    */
    public class Main {
    
    	public static void main(String[] args) {
    		LoggerManager.getLogger().Log("Starting Main", LoggerManager.LogLevel.INFO);
    	}
    
    }

    public by alaindresse modified Feb 22, 2013  1824864  380  5  0

    Understanding aui:input type="checkbox"

    Understanding aui:input type="checkbox": aui_checkbox.jsp auiCheckbox.java info.txt
    <portlet:actionURL name="testAction" var="testActionURL" />
    <aui:form action="<%=testActionURL%>">
    	<aui:input id="novalue1" type="checkbox" name="novalue"
    		label="no value first" />
    	<aui:input id="novalue2" type="checkbox" name="novalue"
    		label="no value second" />
    	<aui:input id="value1" type="checkbox" name="withvalue" label="value first"
    		value="first" />
    	<aui:input id="value2" type="checkbox" name="withvalue" label="value second"
    		value="second" />
    	<aui:button type="button" value="setValue1"
    		onClick='<%=renderResponse.getNamespace() +
    					"testJSCheckbox(\'value1\', true)"%>' />
    	<aui:button type="button" value="unsetValue1"
    		onClick='<%=renderResponse.getNamespace() +
    					"testJSCheckbox(\'value1\', false)"%>' />
    	<aui:button type="submit" />
    </aui:form>
    
    <aui:script>
    Liferay.provide(
    	window, 
    	"<portlet:namespace />testJSCheckbox",
    	function(id,value){
    		var A = AUI();
    		var checkbox = A.one("#<portlet:namespace />"+id+"Checkbox");
    		if (checkbox){ 
    			checkbox.set('checked', value);
    			Liferay.Util.updateCheckboxValue(checkbox);
    		}
    	},
    	['aui-base']
    );
    </aui:script>
    
    public class TestPortlet extends MVCPortlet {
    
    	public void testAction(ActionRequest actionRequest,
    			ActionResponse actionResponse) throws IOException, PortletException {
    		Map<String, String[]> parameters = actionRequest.getParameterMap();
    		for (String key : parameters.keySet()){
    			_log.info(key + ":[" + StringUtil.merge(parameters.get(key)) + "]");
    		}
    	}
    	
    	private static Log _log = LogFactoryUtil.getLog("TestPortlet"); 
    }
    
    
    Each `<aui:input type=”checkbox” name="xyz" … />` entry translates into two input items:
    
    > <input type="hidden" name="portlet:namespace/>xyz" ...
    > <input type="checkbox" name="<portlet:namespace/>xyzCheckbox"
    
    If the <aui:input field has __NO value assinged__, when checkboxes are clicked, the corresponding hidden item's value is set to true or false. 
    
    If the <aui:input field has __A value assinged__ (other than "true"), the value of the hidden item does not depend on the state of the checkbox. In this case, you need to rely on the entries under the name 'xyzCheckbox' from the request parameter map in your processAction method to capture the checkbox state.
    
    Note also that if you set the value of the checkbox programmatically (in javascript), and you use the xyz value in the request parameter map in your processAction method, then you also need to adapt the value of the hidden item by calling
    > Liferay.Util.updateCheckboxValue(checkbox)
    
    

    public by mporru modified May 28, 2013  1442874  314  7  2

    Trim, TrimStart, TrimEnd methods in java

    public static String TrimEnd(String input, String charsToTrim)
    	{
    		return input.replaceAll("[" + charsToTrim + "]+$", "");		
    	}	
    	
    	public static String TrimStart(String input, String charsToTrim)
    	{
    		return input.replaceAll("^[" + charsToTrim + "]+", "");	
    	}
    
    	public static String Trim(String input, String charsToTrim)
    	{
    		return input.replaceAll("^[" + charsToTrim + "]+|[" + charsToTrim + "]+$", "");	
    	}

    public by snip2code modified Oct 29, 2013  1446652  128  7  1

    Custom SWT List Box

    This widget presents a ListBox, with vertical scroll-bars, whose items can be custom (instead of simple strings as in List widget). The items should be of the same height and all homogeneous.
    import java.util.HashMap;
    import java.util.Map;
    
    import org.apache.log4j.Logger;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.custom.ScrolledComposite;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.graphics.Color;
    import org.eclipse.swt.graphics.Cursor;
    import org.eclipse.swt.graphics.Font;
    import org.eclipse.swt.layout.FormData;
    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.Link;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.wb.swt.SWTResourceManager;
    
    public class CustomListBox extends Composite {
    
    	protected static Logger log = Logger.getLogger(CustomListBox.class);
    	
    	private ScrolledComposite scrolledResults;
    	private Composite listResults;
    	
    	private int width;
    	private int height;
    	private int itemRowHeight;
    	private int rowWidth;
    	private int maxResultsDisplayed;
    	
    	private Map<String, Composite> rows = new HashMap<String, Composite>();
    	
    	/**
    	 * 
    	 * @param parent container of the component
    	 * @param style style of the componen
    	 * @param marginLeft pixels from left border of the dialog
    	 * @param topHeight pixels from top border fo the dialog
    	 * @param width total width in pixel of the component
    	 * @param height total height in pixel of the component
    	 * @param scrolledCompoFormData FormData for the component
    	 * @param itemRowHeight height in pixel of a single item
    	 */
    	public CustomListBox(Composite parent, int style, int marginLeft, int topHeight, int width, int height,
    			FormData scrolledCompoFormData, int itemRowHeight) {
    		super(parent, style);
    
    		this.width = width;
    		rowWidth = width - 25;
    		this.height = height;
    		this.itemRowHeight = itemRowHeight;
    		maxResultsDisplayed = height / itemRowHeight;
    		
    		scrolledResults = new ScrolledComposite(parent, SWT.BORDER | SWT.V_SCROLL);
    		scrolledResults.setLocation(marginLeft, topHeight);
    		scrolledResults.setSize(width, height);
    		scrolledResults.setExpandHorizontal(false);
    		scrolledResults.setExpandVertical(true);
    		scrolledResults.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
    		scrolledResults.setMinSize(width, height);	
    		scrolledCompoFormData.height = height;	//force height of the component
    		scrolledResults.setLayoutData(scrolledCompoFormData);
    		scrolledResults.getVerticalBar().setIncrement(scrolledResults.getVerticalBar().getIncrement()*10);
    		scrolledResults.addListener(SWT.Activate, new Listener() {
    		    public void handleEvent(Event e) {
    		    	scrolledResults.setFocus();
    		    }
    		});
    		
    		listResults = new Composite(scrolledResults, SWT.NONE);
    		listResults.setSize(width, height);
    		listResults.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
    		scrolledResults.setContent(listResults);
    		
    		parent.addListener(SWT.Resize, new Listener() { 
    			public void handleEvent(Event event) { 
    				resizeScrollableResults();
    			} 
    		}); 
    		parent.notifyListeners(SWT.Resize, new Event()); 
    	}
    	
    	
    	private void resizeScrollableResults() {
    		int actualHeight = rows.size() * itemRowHeight;
    		scrolledResults.setMinSize(width, Math.max(actualHeight, height));
    		scrolledResults.layout();
    	}
    	
    	@Override
    	public void layout() {
    		listResults.layout();
    		resizeScrollableResults();
    	}
    	
    	/**
    	 * Creates a new row in the list, identified by the given key.
    	 * @param key identifier to retrieve the newly created item
    	 * @return the just created and added composite item
    	 * @throws IllegalArgumentException if key already exists or is null/empty
    	 */
    	public Composite addRow(String key) throws IllegalArgumentException {
    		if (key == null || key.length() <= 0)
    			throw new IllegalArgumentException("Null or empty key");
    		if (rows.containsKey(key))
    			throw new IllegalArgumentException("Item with key " + key + " already exists");
    		
    		int rowCompoWidth = rowWidth;
    		if (!scrollbarIsShown()) 
    			rowCompoWidth += 20;
    		
    		final Composite rowCompo = new Composite(listResults, SWT.BORDER);
    		rowCompo.setLocation(0, (rows.size() * itemRowHeight));
    		rowCompo.setSize(rowCompoWidth, itemRowHeight - 2);
    		rowCompo.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
    
    		rows.put(key, rowCompo);
    		
    		return rowCompo;
    	}
    	
    	/**
    	 * True if the number of items is greater than the total visible items 
    	 */
    	public boolean scrollbarIsShown() {
    		return (rows.size() >= maxResultsDisplayed);
    	}
    	
    	/**
    	 * Returns the number of visible items
    	 */
    	public int getMaxResultsDisplayed() {
    		return maxResultsDisplayed;
    	}
    	
    	/**
    	 * Empties the list of items in the list and shows a single item with the given text
    	 * @param textToShow text to display
    	 * @param font font of the text to display
    	 * @param backgroundColor background color of the item that shows the text to display
    	 * @param link link to follow (if not empty, a Link instead of a Label will be created)
    	 */
    	public void displayMessage(String textToShow, Font font, Color backgroundColor, final String link) {
    		final Composite rowCompo = new Composite(listResults, SWT.NONE);
    		rowCompo.setLocation(0, 0);
    		rowCompo.setSize(width, itemRowHeight - 2);
    		rowCompo.setBackground(backgroundColor);
    
    		Control lblNoResults = null;
    		if (link != null) {
    			lblNoResults = new Link(rowCompo, SWT.NONE);
    			((Link)lblNoResults).setText(textToShow);
    			((Link)lblNoResults).setCursor(new Cursor(getShell().getDisplay(), SWT.CURSOR_HAND));
    			((Link)lblNoResults).addSelectionListener(new SelectionAdapter() {
    				@Override
    				public void widgetSelected(SelectionEvent e) {
    					//something to do with the link...
    				}
    			});
    		} else {		
    			lblNoResults = new Label(rowCompo, SWT.NONE);
    			((Label)lblNoResults).setAlignment(SWT.CENTER);
    			((Label)lblNoResults).setText(textToShow);
    		}
    		lblNoResults.setBounds(0, 0, width, itemRowHeight - 2); 
    		lblNoResults.setFont(font);
    		lblNoResults.setBackground(backgroundColor);
    	}
    	
    	/**
    	 * Removes all the items from the list and dispose all the children content
    	 */
    	public void cleanItems() {
    		//clean previous results:
    		Control[] children = listResults.getChildren();
    		if (children != null) {
    			for (Control child : children) {
    				child.dispose();
    			}
    		}
    		
    		rows = new HashMap<String, Composite>();
    	}
    }

    public by cghersi modified Jul 2, 2014  726874  41  6  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 snip2code modified Sep 18, 2013  697677  258  6  1

    Send An HTTP POST Request In Java

    This is a core method to send an HTTP POST Request in Java. It is able to store and re-use the set of cookies used in the past calls. It makes use of log4j library to log information regarding the process.
    import org.apache.http.HttpHost;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.CookieStore;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    private CookieStore m_cookies = null;    //cookie container ready to receive the forms auth cookie
        
    public String sendPostReq(String url, String data) {
    		// Create a new client:
    		DefaultHttpClient httpClient = new DefaultHttpClient();
    		HttpPost httppost = new HttpPost(url);
    		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    		httppost.setHeader("Charset", "UTF-8");
    		httppost.setHeader("Accept", "application/json");
    
    		//access the secured service with the authorization cookie
    		httpClient.setCookieStore(m_cookies);
    		try {
    			httppost.setEntity(new StringEntity(data, "UTF-8"));
    		} catch (UnsupportedEncodingException e1) {
    			log.error("Cannot encode data: " + data + " due to " + e1);
    			return "";
    		}
    
    		HttpResponse response = null;
    		String res = "";
    		try {
    			response = httpClient.execute(httppost);
    			res = readStreamData(response.getEntity().getContent());
    			log.info("Response:" + res);
    		} catch (org.apache.http.conn.HttpHostConnectException e) {
    			log.error("Cannot receive response due to " + e);
    			if (url.contains(LOGIN_URL))
    				res = TIMEOUT_RESP;
    		} catch (IOException e) {
    			log.error("Cannot parse incoming response due to " + e);
    		} finally {
    			httpClient.getConnectionManager().shutdown();
    		}
    		
    		//save cookies for the next secured run:
    		m_cookies = httpClient.getCookieStore();
    		
    		return res;
    }
    • Public Snippets
    • Channels Snippets