working on it ...

Filters

Explore Public Snippets

Sort by

Found 15 snippets

    public by snip2code modified Aug 13, 2017  117  0  3  1

    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 modified Oct 29, 2013  14889  61  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.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 snip2code modified Oct 7, 2013  2577  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) + "...";
    	else
    		return input;
    }

    public by snip2code modified Sep 27, 2013  2664  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 modified Sep 18, 2013  2930  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 CREATE_SNIPPET_URL = "http://www.snip2code.com/Snippets/Add";
            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 modified Sep 18, 2013  2529  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 = "http://www.snip2code.com/Search/Get"; 
            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());
    		else
    			return null;
        }

    public by snip2code modified Sep 18, 2013  1937  2  6  0

    Login With Snip2Code APIs in Java

    This is an example in Java of the login procedure to consume Snip2Code APIs that need authorization. The simple HTTP request to the login endpoint is then deserialized and the resulting User object is returned as result.
    public User login(String username, String password) {
             String postData = "Username=" + username + "&" + 
                				"Password=" + password + "&" + 
                				"LoginBtn=Login";
    
            // now post to the login form
    		String loginUrl = "http://www.snip2code.com/Access/Login"
            String response = sendPostReq(loginUrl, postData);
            S2CResBaseEntity<User> resp = Deserialize(response); //you can use a third party library to pass from json-encoded response to the object...
    
            if ((resp == null) || ((resp != null) && (resp.getStatus() == ErrorCodes.FAIL)))
                return null;
            else
                return resp.getData();
        }

    public by snip2code modified Sep 18, 2013  7104  15  7  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 by snip2code modified Sep 18, 2013  5962  3  6  0

    Send An HTTP GET Request In Java

    This is a core method to send an HTTP GET 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 sendGetReq(String url, String querystring) {
    		// Create a new client:
    		DefaultHttpClient httpClient = new DefaultHttpClient();
    		String getUrl = url;
    		if (!Utils.isNullOrEmpty(querystring))
    			getUrl += "?" + querystring;
    		HttpGet httpget = new HttpGet(getUrl);
    		httpget.setHeader("Content-Type", "application/x-www-form-urlencoded");
    		httpget.setHeader("Charset", "UTF-8");
    		httpget.setHeader("Accept", "application/json");
    
    		//access the secured service with the authorization cookie
    		httpClient.setCookieStore(m_cookies);
    		
    		HttpResponse response = null;
    		String res = "";
    		try {
    			response = httpClient.execute(httpget);
    			res = readStreamData(response.getEntity().getContent());
    		} 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 by snip2code modified Sep 18, 2013  2376  0  7  0

    Snip2Code APIs: programmatically add a snippet

    This is the fastest way to add a snippet to your bucket in Snip2Code. Be sure to be logged in before sending such request.
    public void CreateSnippet(User currentUser, string title, string descr, string code)
    {
        if (string.IsNullOrEmpty(title) && string.IsNullOrEmpty(code))
            return;
    
        //save this snippet in the basket of the user:
        Snippet newSnip = new Snippet();
        newSnip.Name = title;
        if (!string.IsNullOrWhiteSpace(descr))
            newSnip.Description = descr;
        newSnip.Code = code;
        newSnip.TargetGroupID = currentUser.PersonalGroupID;
        newSnip.Relevance = 10;
    
    	//optional fields:
    	newSnip.Tags = new string[]{"tag1", "tag2", "tag3"};
    	newSnip.Properties = new SnippetProperty[]{new SnippetProperty("OS", "Windows"), new SnippetProperty("Language", "C#")};
    	
        SaveSnippet(newSnip);
    }
    
    public long SaveSnippet(Snippet snippet)
    {
        if ((snippet == null) || (snippet.AreFieldsValid() != SnippetWrongField.OK))
        {
            log.ErrorFormat("Input error: snippet={0}, creator={1}", snippet.PrintNull(), CurrentUser.PrintNull());
            return -1;
        }
    
        //send the request and parse the response:
        string contentToSend = "content=" + HttpUtility.UrlEncode(Serialize(snippet)); //you can use a third party library to pass from objecto to json-encoded request...
        string CREATE_SNIPPET_URL = "http://www.snip2code.com/Snippets/Add";
        string response = SendRequest(CREATE_SNIPPET_URL, contentToSend, true);
        S2CResObj<object> resp = Deserialize(response); //you can use a third party library to pass from json-encoded response to the object...
    
        //build the result:
        long result = -1;
        if (resp != null)
        {
    	    if (!long.TryParse(resp.Data.ToString(), out result))
    	    {
    	        log.ErrorFormat("Invalid response: {0}", resp.Data.ToString());
    	        return -1;
    	    }
        }
        return result;
    }
    
    • Public Snippets
    • Channels Snippets