Reputation Top 1%
Snip2Code Team
14 Snippets  (51st place)
162 Channels
7 Channels
Dec 7, 2013
Last Visit
Dec 19, 2012
4492 points  (13rd place)
Top 10% Publisher
Junior Code Generator
Serious Code Generator
Junior Publisher
Serious Publisher
Serious Topic Creator
Senior Topic Creator
Master Topic Creator
Guru Topic Creator
Junior Topic Hub
Serious Topic Hub
Senior Topic Hub
Master Topic Hub
Guru Topic Hub
Junior Trend Maker
Serious Trend Maker
Senior Trend Maker
Master Trend Maker
Guru Trend Maker
Junior Influencer
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Famous Coder
Serious Famous Coder
Senior Famous Coder
Serious Wise Coder

Recent Snippets See all snippets by snip2code

public by snip2code created Oct 21, 2013  14599  48  8  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.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.setMinSize(width, height);	
		scrolledCompoFormData.height = height;	//force height of the component
		scrolledResults.addListener(SWT.Activate, new Listener() {
		    public void handleEvent(Event e) {
		listResults = new Composite(scrolledResults, SWT.NONE);
		listResults.setSize(width, height);
		parent.addListener(SWT.Resize, new Listener() { 
			public void handleEvent(Event event) { 
		parent.notifyListeners(SWT.Resize, new Event()); 
	private void resizeScrollableResults() {
		int actualHeight = rows.size() * itemRowHeight;
		scrolledResults.setMinSize(width, Math.max(actualHeight, height));
	public void layout() {
	 * 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);

		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);

		Control lblNoResults = null;
		if (link != null) {
			lblNoResults = new Link(rowCompo, SWT.NONE);
			((Link)lblNoResults).setCursor(new Cursor(getShell().getDisplay(), SWT.CURSOR_HAND));
			((Link)lblNoResults).addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					//something to do with the link...
		} else {		
			lblNoResults = new Label(rowCompo, SWT.NONE);
		lblNoResults.setBounds(0, 0, width, itemRowHeight - 2); 
	 * 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) {
		rows = new HashMap<String, Composite>();

public by snip2code created Oct 7, 2013  2518  0  4  0

Trim a string with ellipsis

This is the simplest way to trim a string to the given length. If trimmed, the last part of the string is replaced with ellipsis
public static String trimWithDots(String input, int maxLen) {
	if (isNullOrEmpty(input))
		return "";
	if (input.length() > (maxLen - 3))
		return input.substring(0, maxLen - 3) + "...";
		return input;

public by snip2code created Sep 27, 2013  2620  1  5  0

Filtered COUNT (*) in Linq

This is a very effective method to count in-memory a given collection (Users), with an established filter (active == true). Really fast, really simple, Linq style!!
(from user in Users where user.Active == true select user).Count();

public by snip2code created Sep 18, 2013  2867  0  6  1

Snip2Code APIs: Programmatically Add A Snippet

This is the fastest way to add a snippet to your bucket in Snip2Code in Java. Be sure to be logged in before sending such request.
public long saveSnippet(Snippet snippet) {
        //Check that the client has been already logged in, and if this is not the case, automatically login:
        if (!checkLogin()) {
            return -1;

        //send the request and parse the response:
        String content = serialize(snippet);  //you can use a third party library to pass from objecto to json-encoded request...
        String contentToSend = "";
		try {
			contentToSend = "content=" + URLEncoder.encode(content, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return -1;
        String response = sendPostReq(CREATE_SNIPPET_URL, contentToSend);
		S2CResObj<Object> resp = deserialize(response); //you can use a third party library to pass from json-encoded response to the object...
		//build the result:
        if ((resp != null) && (resp.getStatus() == ErrorCodes.OK)) {
			try {
        		return Long.parseLong(resp.getData().toString());
        	} catch (Exception e) {
            	return -1;
		return -1;

public by snip2code created Sep 18, 2013  2474  0  6  0

Search Snippets With Snip2Code APIs in Java

This method calls Snip2Code web service to search for the snippets matching the given filters. This method can be called both as anonymous user (without having previously logged-in, in this case the results will be only public snippets) or as logged user (in this case the results will be found in the basket of user's visible snippets).
public class PaginatedList<T extends BaseEntity> {
		public List<T> list;
		public int totNum;
		public HashMap<String, String> misc;
		public PaginatedList(List<T> list, int totNum, HashMap<String, String> misc) {
			this.list = list;
			this.totNum = totNum;
			this.misc = misc;

    public PaginatedList<Snippet> getSnippetsForSearch(String searchText, int maxNum, int start, boolean onlyCreated, int onlyOfGroup) {
        //send the request and parse the response:
        String querystring = "";
		try {
			querystring = String.format("query=%s&maxNum=%d&start=%d&onlyCreated=%b&onlyOfGroup=%d",
					URLEncoder.encode(searchText, "UTF-8"), maxNum, start, onlyCreated, onlyOfGroup);
		} catch (UnsupportedEncodingException e) {
			return new PaginatedList<Snippet>(new ArrayList<Snippet>(), 0, null);
		String SEARCH_SNIPPET_URL = ""; 
        String response = SendGetReq(SEARCH_SNIPPET_URL, querystring);
		S2CResListBaseEntity<Snippet> resp = Deserialize(response); //you can use a third party library to pass from json-encoded response to the object...

        //build the result:
        return getPaginatedListFromResp(resp, Snippet.class);

    protected <T extends BaseEntity> PaginatedList<T> getPaginatedListFromResp(S2CResListBaseEntity<T> resp, Class<T> clazz) {
	    if ((resp != null) && (resp.getStatus() == ErrorCodes.OK) 
  	    	return new PaginatedList<T>(Utils.asList(resp.getData(), clazz), resp.getTotNum(), resp.getMisc());
			return null;