Reputation Top 1%
Snip2Code Team
15 Snippets  (56th place)
162 Channels
7 Channels
7468 points  (16th place)
Top 10% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Junior Publisher
Serious Publisher
Senior Publisher
Serious Topic Creator
Senior Topic Creator
Master Topic Creator
Guru Topic Creator
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
Serious Famous Coder
Senior Famous Coder
Serious Wise Coder

Recent Snippets See all snippets by snip2code

public by snip2code  796  3  4  0

First Snippet: How to play with Snip2Code

This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
/* place here the actual content of your snippet. 
   It should be code or pseudo-code. 
   The less dependencies from external stuff, the better! */

public by snip2code  16405  123  7  3

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  3069  1  3  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  3106  1  4  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  3412  0  5  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;