Are you looking for customized advices? Click here to contact the expert!
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!
253 Snippets  (3rd place)
16 Channels
73 Channels
11 hours ago
Last Visit
May 5, 2012
68599 points  (5th place)
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
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
Master Geek Aggregator
Junior Famous Coder
Serious Famous Coder
Senior Famous Coder
Master Famous Coder
Guru Famous Coder
Junior Wise Coder
Master Wise Coder

Recent Snippets See all snippets by cghersi

public by cghersi created Jan 10, 2017  2169  10  5  3

How to write bytes into file in Java

Efficient way to write strings or bytes onto a file.
  import java.nio.file.Files;
  import java.nio.file.Paths;

  public static void writeFile(String path, String content) throws Exception {
		if (isNullOrEmpty(path) || isNullOrEmpty(content)) {
		Files.write(Paths.get(path), content.getBytes());

public by cghersi created Jan 10, 2017  2424  2  5  0

Read file in Java

Efficient way to read file in Java using Files class
  import java.nio.file.Files; 
  import java.nio.file.Paths;

  public static String readFile(String path) throws Exception {
		if (isNullOrEmpty(path)) {
			return "";
		return new String(Files.readAllBytes(Paths.get(path)));

public by cghersi created Nov 4, 2012  289698  2  8  0

How to read a file into a string in Java

This simple snippet reads a file and put the content into a returned string
private static String readFileAsString(String filePath) throws{

	StringBuffer fileData = new StringBuffer(1000);
	BufferedReader reader = new BufferedReader(new FileReader(filePath));
	char[] buf = new char[1024];
	int numRead=0;
	while(( != -1){
		String readData = String.valueOf(buf, 0, numRead);
		buf = new char[1024];

	return fileData.toString();

public by cghersi created Dec 16, 2016  2160  5  6  0

How to post an HTTP Request

just consume a RESTful API via POST request
public String sendPostReq(String url, String data, boolean addAccessToken) {
		// Create a new client:
		DefaultHttpClient httpClient = createHttpClient(url.startsWith("https"));
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httppost.setHeader("Charset", "UTF-8");
		httppost.setHeader("Accept", m_requestFormat.getMimeType());
		httppost.setHeader(S2C_HEADER, S2C_HEADER_VALUE);

		//access the secured service with the authorization cookie
		if (addAccessToken && !Utils.isNullOrEmpty(m_accessToken)) {
		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());"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 {
		m_cookies = httpClient.getCookieStore(); //save cookies for the next secured run		
		return res;

public by cghersi created Oct 5, 2016  8449  1  5  0

Preprovision a device via API with PLAT.ONE

This is a way to use the PLAT.ONE API to create a device with a full structure: once the device is then active, it will be automatically integrated into the PLAT.ONE environment.
// define the addressing information of the device:
int netId = 1;			
String deviceAddress = "100100";
WSNNodeType nodeType = WSNNodeType.ENDPOINT;
// add sensor breakdown:
List<LogNodeConfig> logNodeConfigs = new ArrayList<LogNodeConfig>();
List<ObjectId> objsTemp = new ArrayList<ObjectId>();
ObjectId objectIdTemp = frameParser.getObjID(0, 10);	// ObjectIdLow==0, ObjectIdHigh==10 = Temperature
LogNodeConfig myNodeConf1 = frameParser.getLogNodeCfg(0, objsTemp, true);
Tsap tsapTemp = frameParser.getTsap("AA:11:22:33:4E");
// invoke the API
ACSIresponseTicket<NodeIdentifier> ticket = null;
try {
	ticket = apiManager.ACSI_addNode(netId, nodeAddress, logNodeConfigs, nodeType, null);
} catch (Exception e1) {
	log.error("Could not create node ID= " + nodeAddress + ". "+ e1.getMessage());
	return null;

log.trace("Ticket: " +  ticket.getRequestReturnCode());
if (ticket.getRequestReturnCode() != ACSIreturnCodes.SUCCESS)
	return null;

nodeID = ticket.getResponse();
if (nodeID!=null) {"Creating node: " + nodeID);
} else {
	log.error("CreateNode returned null NodeIdentifier");
	return null;