Are you looking for customized advices? Click here to contact the expert!
cghersi
cghersi
Reputation Top 1%
Cristiano Ghersi
Great passion for Software Engineering, mostly coding in Java and C#, I enjoy creating modular and reusable code for everybody!
204 Snippets  (2nd place)
Published
14 Channels
Created
62 Channels
Following
2 hours ago
Last Visit
May 5, 2012
Registered
7724 points  (2nd place)
Reputation
Top 1% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Master Code Generator
Guru Code Generator
Junior Publisher
Serious Publisher
Senior Publisher
Master Publisher
Guru Publisher
Guru Topic Creator
Junior Topic Hub
Serious Topic Hub
Senior Topic Hub
Master Topic Hub
Junior Trend Maker
Serious Trend Maker
Senior Trend Maker
Master Trend Maker
Junior Influencer
Serious Influencer
Senior Influencer
Junior Commenter
Serious Commenter
Senior Commenter
Master Commenter
Junior Judge
Serious Judge
Senior Judge
Master Judge
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Master Popular Coder
Guru Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Snip2Coder
Junior Geek Aggregator
Serious Geek Aggregator
Senior Geek Aggregator
Junior Famous Coder
Serious Famous Coder
Senior Famous Coder
Junior Wise Coder

Recent Snippets See all snippets by cghersi

public by cghersi modified Tuesday at 6:02:14 PM  48  0  3  1

Remove Duplicate rows in SQL Server

This script removes the duplicate rows in table Customers detecting the rows with the same contactname
SET NOCOUNT ON
SET ROWCOUNT 1
WHILE 1 = 1
  BEGIN
    DELETE  
    FROM Customers
    WHERE contactname IN
        (SELECT  contactname
         FROM    Customers
         GROUP BY contactname
         HAVING  COUNT(*) > 1)
      
    IF @@Rowcount = 0
      BREAK ;
 END
 SET ROWCOUNT 0          
;

public by cghersi modified Jan 29, 2016  15714  1431  13  7

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 cghersi @ PLAT.ONE modified Jan 7, 2016  39  0  3  1

Add / remove visibility of some devices to a user in PLAT.ONE

These two methods add and remove the visibility of a particular device for the given user. The data of the device are preserved in any case.
public boolean associateDevice(int deviceID, int userID) throws Exception {
	// 1. check that the user is already assigned a visibility at node level:
	IPlatoneAPI api = getAPI();
	IProxyPlatUser user = api.DB_GetPlatUser(userID);
	if (user == null)
		return false;
	if (!user.isNodeLevelSecPolicy(APP_GARDEN_ID))
		api.DB_ModifyPlatUserSecPolicy(APP_GARDEN_ID, userID, false, true);
	
	// 2. associate the device:
	ArrayList<Integer> nodes = new ArrayList<Integer>();
	nodes.add(deviceID);
	return api.DB_AddAvailNodes4User(APP_GARDEN_ID, userID, nodes);
}

public boolean archiveDevice(int deviceID, int userID) throws Exception {
	// 1. check that the user is already assigned a visibility at node level:
	IPlatoneAPI api = getAPI();
	IProxyPlatUser user = api.DB_GetPlatUser(userID);
	if (user == null)
		return false;
	if (!user.isNodeLevelSecPolicy(APP_GARDEN_ID))
		api.DB_ModifyPlatUserSecPolicy(APP_GARDEN_ID, userID, false, true);
	
	// 2. archive the device:
	ArrayList<Integer> nodes = new ArrayList<Integer>();
	nodes.add(deviceID);
	api.DB_DeleteAvailNodes4User(APP_GARDEN_ID, userID, nodes);
	
	return true;
}
;

public by cghersi @ PLAT.ONE modified Jan 7, 2016  63  0  4  0

How to consume JMS frames directly incoming from devices in PLAT.ONE

This class can be used and modified to manage the JMS frames incoming in real time from the PLAT.ONE JMS Broker. The edgeware component of PLAT.ONE, that manages a set of devices, retrieves the information from the devices and publishes those information onto some JMS topics. This class represents a client that subscribes to those topics and is not
package one.plat.extensions;

import java.util.List;

import helloworldservice.HelloWorldServiceImpl;

import com.abodata.plat1.frames.dataTypeCode;
import com.abodata.plat1.frames.serviceTypeCode;
import com.abodata.plat1.jms.IDirectAMQConsumer;
import com.abodata.plat1.jms.INetworkSubscriber;
import com.abodata.plat1.jms.Interest;
import com.abodata.plat1.jms.InterestType;
import com.abodata.plat1.jms.MsgFormat;
import com.abodata.plat1.jms.SIPCInterface;
import com.abodata.plat1.logger.Plat1Logger;
import com.abodata.plat1.network.addressing.NodeIdentifier;
import com.abodata.plat1.network.node.data.Measure;
import com.abodata.plat1.network.node.data.ParsedMeasurePayload;
import com.abodata.plat1.network.node.data.PositionPayload;
import com.abodata.plat1.queues.frames.BaseHeader;
import com.abodata.plat1.queues.frames.Frame;
import com.abodata.plat1.queues.frames.NextHeader;
import com.abodata.plat1.queues.frames.Payload;
import com.abodata.plat1.queues.frames.WSNDataHeader;
import com.abodata.plat1.queues.frames.WSNnodeHeader;
import com.abodata.plat1.ws.velocity.IProxyNetwork;

public class DirectConsumer implements IDirectAMQConsumer, INetworkSubscriber {

	private static final Plat1Logger log = new Plat1Logger(DirectConsumer.class);
	
	private InterestType[] interests = new InterestType[] {	
			//get data from the field / devices
			new InterestType(serviceTypeCode.doryService, dataTypeCode.dataPosition, false, this),
			new InterestType(serviceTypeCode.doryService, dataTypeCode.dataAbsPosition, false, this),
			new InterestType(serviceTypeCode.doryService, dataTypeCode.parsedDataReport, false, this), 

			//check new networks
			new InterestType(serviceTypeCode.wsnLifeService, dataTypeCode.event),	
		};
	
	public void startConnection() {
		log.warn("Start connection towards broker");
		try {
			HelloWorldServiceImpl.getAMQFactory().startConnection(getClass(), 
					new Interest[] { 
						new Interest(BaseHeader.BROADCAST_NETWORKID, serviceTypeCode.wsnLifeService, dataTypeCode.event, 
									"", MsgFormat.XML, null, false) });
			
			getSIPC().setOwner(this.getClass().getName());
			getSIPC().ipcOpenPipe();
			
			List<IProxyNetwork> nets = HelloWorldServiceImpl.getAPI().DB_GetVisibleNetworks();
			if (nets != null) {
				for (IProxyNetwork net : nets) {	
					log.warn("Adding interest for network " + net.getId());
					HelloWorldServiceImpl.getSIPC().ipcAddInterests(net.getId(), serviceTypeCode.crushService, dataTypeCode.event, 
							MsgFormat.XML, "", this);	
				}
			}
			
			log.warn("Connection successfully opened!");
		} catch (InstantiationException e) {
			log.error("Cannot subscribe to nets due to " + e, e);
		} catch (Exception e) {
			log.error("Cannot subscribe to nets due to " + e, e);
		}
	}
	
	public void stopConnection() {
		getSIPC().ipcClosePipe();
		HelloWorldServiceImpl.getAMQFactory().remove(getClass());
	}

	@Override
	public void consume(Frame frame) {
		//filter unwanted frames:
		BaseHeader bh = frame.getBHeader();
		switch(bh.getDataType()) {
		case parsedDataReport:
			NextHeader header = frame.getNextHeader();
			if ((header != null) && (header instanceof WSNDataHeader)) {
				Payload p = frame.getPayload();
				if ((p != null) && (p instanceof ParsedMeasurePayload))
					manageDataFrame(bh, (WSNDataHeader)header, (ParsedMeasurePayload)p);
			}
			break;
			
		case dataPosition:
		case dataAbsPosition:
			NextHeader headerPos = frame.getNextHeader();
			if ((headerPos != null) && (headerPos instanceof WSNnodeHeader)) {
				Payload p = frame.getPayload();
				if ((p != null) && (p instanceof PositionPayload))
					managePositionFrame(bh, (WSNnodeHeader)headerPos, (PositionPayload)p);
			}
			break;
			
		default: //nothing to do here...
			break;
		}
	}
	
	private void manageDataFrame(BaseHeader bh, WSNDataHeader header, ParsedMeasurePayload p) {
		NodeIdentifier nodeID = header.getNodeId(); //device that sent the new data
		
		//which data configuration has been received (e.g. High=6 - Low=0 => OpMode)
		int objIDHigh = header.getObjectIdHigh();
		int objIDLow = header.getObjectIdLow();
			
		//actual value(s) of the data, with timestamp and unit(s) of measure.
		//There can be several data associated to a single configuration, but usually there's just one information (m.getRank() = 1)
		Measure m = p.getMeasure();	
		
		// do some stuff...
	}
	
	private void managePositionFrame(BaseHeader bh, WSNnodeHeader header, PositionPayload p) {
		NodeIdentifier nodeID = header.getNodeId(); //device that sent the new position
		float[] coords = p.getCoords(); //new coordinates
		
		//whether those coordinates are absolute (latitude, longitude, quote), or relative (with respect to a known origin)
		boolean isAbsCoords = bh.getDataType() == dataTypeCode.dataAbsPosition; 
		
		// do some stuff...
	}

	@Override
	public InterestType[] getInterests() {
		return interests;
	}

	@Override
	public SIPCInterface getSIPC() {
		return HelloWorldServiceImpl.getSIPC();
	}
	
	@Override
	public boolean isAbleToConsumeFrames() { return true; }
	
	@Override
	public void consume(String arg0) {} //not used
	@Override
	public void consume(byte[] arg0) {} //not used
	@Override
	public boolean isAbleToConsumeBinaryMsg() {	return false; }
	@Override
	public boolean isAbleToConsumeTextMessages() { return false; }
}
;

public by cghersi modified Nov 5, 2015  85  0  4  0

Get estimate of number of records in MySQL tables

This query returns the number of records present in each table. It is not totally accurate, but can give a rough estimate of the sizes of the tables.
SELECT table_name, table_rows
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'MyDb';          
;