{{error}}
{{(quickSearchResults.length>10)?'10+':(quickSearchResults.length)}} {{(quickSearchResults.length==1)?'result':'results'}}
{{result.title}} {{result.timeStamp | mysql2ymd }}
I am sorry, no such article was written yet.
How to make OAuth Facebook login on your site and how to query FB for your customer's information
It is ssupposed you already have the base_facebook.php, facebook.php, and fb_ca_chain_bundle.crt in their corresponding paths and included as required.
1 files attached: IdentityProviders.php
IdentityProviders.php
<?
abstract class IdentityProviderInterface{
	public $name;
	public function __construct($name){
		$this->name=$name;
	}
	public function getName(){
		return $this->name;
	}
	abstract public function getLabel();
	abstract public function getIconUrl();
	abstract public function getLink();
	abstract public function login();
	abstract public function logout();
	public function getUser(){
		return @$_SESSION['contact']['id'];
	}
}
class OAuthFB extends IdentityProviderInterface{
	function __construct(){
		parent::__construct('facebook');
		//$this->data=array('icon'=>'//facebook.com/favicon.ico','label'=>'Facebook','protocol'=>'OAuth-FB', 'login'=>'https://www.facebook.com/dialog/oauth','logout'=>'http://www.facebook.com/logout.php');
	}
	public function getLabel(){
		return 'Facebook';
	}
	public function getIconUrl(){
		return '//facebook.com/favicon.ico';
	}
	public function getLink(){
			return "?FederatedIdentityProvider=facebook";
	}
	public function login(){
		require_once("$_SESSION[common_system_folder]/OAuth-FB/facebook.php");
		$facebook=new Facebook(array('appId'=>'*****************','secret'=>'*****************'));
		$user=$facebook->getUser();
		if($user){
			try{
				$userProfile= $facebook->api('/me');// the "me" represents the customer's profile, as you query the FB on the customer's behalf
				$_SESSION['contact']['provider']=@$_GET['FederatedIdentityProvider'];
				$_SESSION['contact']['name']=@$userProfile['name'];
				$_SESSION['contact']['id']=@$userProfile['username'].'@facebook.com';
				return;
			}catch(Exception $e){
			}
		}?><!DOCTYPE html><html xmlns:fb="http://www.facebook.com/2008/fbml"><body><fb:login-button></fb:login-button><div id="fb-root"></div>
		<script>window.fbAsyncInit=function(){FB.init({appId:'<?php echo $facebook->getAppID()?>',cookie:true,xfbml:true,oauth:true});
		FB.Event.subscribe('auth.login',function(response){window.location.reload();});
		FB.Event.subscribe('auth.logout',function(response){window.location.reload();});};
		(function(){var e=document.createElement('script');e.async=true;e.src=document.location.protocol+'//connect.facebook.net/en_US/all.js';document.getElementById('fb-root').appendChild(e);}());
		</script></body></html>
		<?die;
	}
	public function logout(){
		require_once("$_SESSION[common_system_folder]/OAuth-FB/facebook.php");
		$facebook=new Facebook(array('appId'=>'*****************','secret'=>'*****************'));
		if(@$facebook->getUser())
			header('Location: '.$facebook->getLogoutUrl());
	}
}?>
Simple Java headless browser that keeps track of cookies - to make easier crowling the sites that require authentication
Sample minimal headless browser in java.
1 files attached: HeadlessBrowser.java
HeadlessBrowser.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.postgresql.util.Base64;

//import org.apache.commons.io.IOUtils;

public class HeadlessBrowser {
	private List<String> cookie = null;

	private HttpURLConnection getConnection(String url, String... headers)
			throws MalformedURLException, IOException {
		HttpURLConnection connection;
		connection = (HttpURLConnection) new URL(url).openConnection();
		if (cookie != null)
			for (int i = 0; i < cookie.size(); i++)
				connection.addRequestProperty("Cookie", cookie.get(i));
		if (headers != null)
			for (String header : headers) {
				int kvPos = header.indexOf(':');
				connection.setRequestProperty(header.substring(0, kvPos),
						header.substring(kvPos + 1));
			}
		connection.setRequestProperty("User-Agent",
				"HeadlessBrowser/1402211648 (+http://dragos-matei.sorescu.eu)");
		return connection;
	}

	public Response get(String url,String...headers) throws IOException {
		HttpURLConnection connection = getConnection(url,headers);
		Response response = new Response(connection.getHeaderFields(),
				connection.getInputStream());
		List<String> setCookie = response.headerFields.get("Set-Cookie");
		if (setCookie != null)
			cookie = setCookie;
		return response;
	}

	public Response post(String url, String postBody, String... headers)
			throws IOException {
		HttpURLConnection connection = getConnection(url, headers);
		connection.setDoOutput(true);
		connection.getOutputStream().write(postBody.getBytes());
		Response response;
		try {
			response = new Response(connection.getHeaderFields(),
					connection.getInputStream());
		} catch (Throwable t) {
			response = new Response(connection.getHeaderFields(),
					connection.getErrorStream());

		}
		List<String> setCookie = response.headerFields.get("Set-Cookie");
		if (setCookie != null)
			cookie = setCookie;
		return response;
	}
	public Response put(String url, String postBody, String... headers)
			throws IOException {
		HttpURLConnection connection = getConnection(url, headers);
		connection.setDoOutput(true);
		connection.setRequestMethod("PUT");
		connection.getOutputStream().write(postBody.getBytes());
		Response response;
		try {
			response = new Response(connection.getHeaderFields(),
					connection.getInputStream());
		} catch (Throwable t) {
			response = new Response(connection.getHeaderFields(),
					connection.getErrorStream());

		}
		List<String> setCookie = response.headerFields.get("Set-Cookie");
		if (setCookie != null)
			cookie = setCookie;
		return response;
	}

	public class Response {
		public Map<String, List<String>> headerFields;
		private byte[] body;

		public Response(Map<String, List<String>> headerFields, InputStream body)
				throws IOException {
			this.headerFields = headerFields;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			if (body != null) {
				byte[] dump = new byte[65536];
				for (;;) {
					int length = body.read(dump);
					if (length < 0)
						break;
					baos.write(dump, 0, length);
				}
			}
			this.body = baos.toByteArray();

		}

		public byte[] getBodyBytes() {
			return this.body;
		}

		public String toString() {
			return new String(this.body);
		}

		public String toBase64String() {
			return Base64.encodeBytes(this.body);
			// return new String(dms.os.Codec.base64.encode(this.body));
		}

		public String getHeader(String header) {
			List<String> strings = headerFields.get(header);
			return (strings == null) ? null : strings.get(0);
		}
	}
}
Simple PHP POST API call (using file_get_contents)
1 files attached: apiCall.php
apiCall.php
<?php
function apiCall($path,$params){
	$result=array();
	$url='http://crm.sorescu.eu/'.$path;
	$opts=array('http'=>array('method'=>'POST','header'=>'Content-type: application/x-www-form-urlencoded','content'=>http_build_query($params)));
	$out=file_get_contents($url,false,stream_context_create($opts));
	$result['url']=$url;
	$result['in']=$params;
	$result['out']=json_decode($out,true);
	return $result;
}?>
Simple HTA widget to see online data on desktop
How to:
  1. paste the main code below in a file named my_file.hta;
  2. just run the file by double-clicking it;
  3. close it by ALT-F4'ing it after getting it in focus.
Features:
  1. Supports resizing with mouse drag from the bottom-right corner;
  2. Supports moving the HTA on display using the CTRL-drag from the same bottom-right corner
  3. .
Tips for power users:
  • Make it Always on top:
    1. install an utility to bring windows on top (like http://www.softpedia.com/get/System/OS-Enhancements/PowerMenu.shtml);
    2. set attribute head/HTA:APPLICATION CAPTION="yes" - if you are using Power Menu;
    3. press F5 to refresh the widget and show the window caption;
    4. set the window always-on-top using the utility;
    5. set attribute head/HTA:APPLICATION CAPTION="no" - if you are using Power Menu;
    6. TADA! You have now  a small always-on-top HTML page showing your custom HTML page on desktop;
  • Show/hide it from task bar by manipulating the SHOWINTASKBAR attribute.
Sample caption (details below are server-side HTML that checks the status of 3rd party systems):
1 files attached: application.hta
application.hta
How to throw an exception in Java even if the compiler does not allow you to...
How to throw an exception that you are not allowed to...
Did you ever get frustrated when a previous developer declared an interface that simply won't allow you to throw a new type of exception?
Rethrow it wrapped in a runtime exception: throw new RuntimeException(myOldJunkyException)
Did you ever need to rethrow the very same exception as reported by a remote system?
Serialize it, receive it, and rewrap it in a synthetic new exception with new RuntimeException().setStackTrace(myNewSyntheticStackTraceIncludingRemoteJunkyLines)
Or, just throw it as it is, by breaking the "convention" of throwing only declared exceptions from the method signature (which anyway the JVM does not care much at run time)... Usage:
public static int main(String[] args) throws IOException {
	THROW(new RuntimeException());
	return "dummy statement that won't ever be executed, but it's requied to compile the function. The compiler cannot figure out that the THROW will throw an exception... :D".length();
}
PS: Don't try it on JVM clones, it might not work at all. Neither on Google's Dalvik...
2 files attached: HelperClass.java Usage.java
HelperClass.java Usage.java
Windows NTNET test on "Java code to check if LDAP (including AD over LDAP) with basic authentication works (check if user/password) is valid"
Thanks to Dmitriy, I put below additional notes and an example on real-life NTNET domain test (sterilized code). The code below was tested on my current (production) NTNET DC and it worked fine.
Notes: {domain_controller_machine} can be found by running Windows echo %logonserver%, then run tracert {logon_server} to identify it's full name.
{my_ntnet_user in short form} is my NTNET user without any realm or domain information.
1 files attached: Test.java
Test.java
Shortest (generally working) full-screen toggle coode
1 files attached: sample.html
sample.html
<div class='pull-right' onclick='$(this).find("a").toggle()'>
	<a onclick='for(var k in{request:1,webkit:1,moz:1,ms:1})try{document.documentElement[k+"RequestFullScreen"]();}catch(e){console.log(e)}'><%icon:maximize%></a>
	<a style='display:none' onclick='for(var k in{exitFulls:1,mozCancelFullS:1,webkitCancelFullS:1})try{document[k+"creen"]();}catch(e){console.log(e)}'><%icon:window%></a>
</div>
Java code to check if LDAP (including AD over LDAP) with basic authentication works (check if user/password) is valid
Straight-forward pinging an LDAP server (to check if also authentication works).
1 files attached: Test.java
Test.java
package dms;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.ldap.LdapName;
public class Test {
	public static void main(String[] args) {
		try {
			test();
		} catch (NamingException e) {
			System.out.println(e.getMessage());
		}
	}

	public static void test() throws NamingException {
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY,
				"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, "ldap://ldap_server.www.company.com:389/o=Users");
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL,
				"CN=myUserName,CN=Users,DC=ldap_server,DC=www,DC=company,DC=com");
		env.put(Context.SECURITY_CREDENTIALS, "********");
		DirContext ctx = new InitialDirContext(env);
		Name name=new LdapName("invalid_name");
		Object o=null;
		ctx.bind(name, o);
		//Should throw "invalid name exception"
	}
}
jQuery.val("input[type=checkbox]"[,value]) custom setter and getter - to work similar to regular input fields
Sample script on how to overwrite the jQuery val() for checkbox fields so that jQuery.val("input[type=checkbox]"[,value]) is in line with the one for input text.
1 files attached: jQueryValOverwrite.js
jQueryValOverwrite.js
$.valHooks.checkbox.get=function(a){return $(a).attr('checked')?'checked':''}
	$.valHooks.checkbox.set=function(a,b){$(a)[$(a).attr('checked')?'removeAttr':'attr']('checked','checked');}
HTML5 Canvas - sample gauge for smart home monitoring systems
Wrapper over HTML5 canvas for polar drawing (coordinates origin are in the centre of the canvas, the angle coordinate goes anti-clockwise, and the unitary magniture is the minimum of width and height of canvas) is attached. Instantiation is:
		var canvas=document.getElementById(dialName+"_z");
		var drawing=new Drawing(canvas);
. Sample usage (partial code) is in Sample.js. Result is:

2 files attached: Canvas.js Sample.js
Canvas.js Sample.js
:for(var sensorIdx=0;sensorIdx<sensors.length;sensorIdx++){
	var dialName=sensors[sensorIdx];
	var canvas=document.getElementById(dialName+"_z");
	var drawing=new Drawing(canvas);
	drawing.clear();
	drawing.circle({w:0.5,r:1,fg:'#000',bg:'#448'});
	drawing.circle({r:0.85,fg:'#111',bg:'#eee'});
	drawing.line({w:4,fg:'#f00',from:{a:Math.PI/2,m:0},to:{a:Math.PI/2,m:0.98}});
	drawing.line({w:2,fg:'#ff0',from:{a:Math.PI/2,m:0},to:{a:Math.PI/2,m:0.97}});
	for(var hour=1;hour<=12;hour++){
		drawing.line({w:0.25,fg:'#777',from:{x:0,y:0},to:{a:offsetA-Math.PI*2*(hour)/(12),m:0.85}});
		drawing.text({a:offsetA-Math.PI*2*(hour)/(12),m:0.925,text:hour,size:0.125,fg:'#bbb'});
	}
	:
	if(MOUSE_OVER){
		if(dialName==MOUSE_OVER.sensor){
			MOUSE_OVER.at=Math.atan2(-MOUSE_OVER.y+canvas.height/2,MOUSE_OVER.x-canvas.width/2);
			while(MOUSE_OVER.at<0)
				MOUSE_OVER.at+=2*Math.PI;
			while(MOUSE_OVER.at>=2*Math.PI)
				MOUSE_OVER.at-=2*Math.PI;
			drawing.line({from:{a:0,m:0},to:{a:MOUSE_OVER.at,m:0.85},w:2,fg:'#f70'});
		}
	}
	:
	drawing.circle({w:0.5,r:0.4,fg:'#000',bg:'#dde'});
	var params={};
	drawing.text({x:0,y:1.2,text:allSensors[sensorProperties.name].label,size:0.2,align:'center',bg:'#000',fg:'#ff0'});
	var lastPoint=null;
	var tooltips=[];
	for(var dataIdx=0;dataIdx<data.length;dataIdx++){
		var x=data[dataIdx][0];
		if(lastTS-x>1000000)continue;
		if(!minTSIdx)minTSIdx=dataIdx;
		if(data[minTSIdx][0]>x)
			minTSIdx=dataIdx;
		var y=data[dataIdx][1+json.sensor2column[sensorProperties.name]];
		if(!data[dataIdx][1+json.sensor2column[sensorProperties.name]])continue;
		if((x==null)||(y==null))continue;
		x/=100;
		var min=x%100;
		var hour=((x-min)/100)%100;
		var params={};
		params.w=0.5+3*dataIdx/data.length*dataIdx/data.length;
		params.from=lastPoint;
		var chan=2.5+2.5*Math.sin(Math.PI*2*((12+6+hour-1)/24));
		chan=Math.round(chan);
		params.fg='rgba('+chan*255/5+',0,'+(5-chan)*255/5+','+(1)+')';
		params.to={};
		params.to.a=offsetA-2*Math.PI*(hour/12+min/12/60);
		while(params.to.a<0)
			params.to.a+=2*Math.PI;
		while(params.to.a>=2*Math.PI)
			params.to.a-=2*Math.PI;
		params.to.m=(y-minVal)/(maxVal-minVal)*0.4+0.4;
		params.y=y;
		if(lastPoint){
			drawing.line(params);
			if(MOUSE_OVER)
			if(dialName==MOUSE_OVER.sensor){
					//alert(params.from.a);
						//alert([params.from.a,MOUSE_OVER.at,params.to.a]);
						if(between(params.from.a,MOUSE_OVER.at,params.to.a)){
							if(tooltips.length==2)
								alert([params.from.a,MOUSE_OVER.at,params.to.a]);
							tooltips.push(dataIdx);
						}
				}
		}
		lastPoint=params.to;
	}
	var rezolutie=allSensors[sensorProperties.name].resolution;
	//alert(rezolutie);
	var actualValue=Math.round(params.y/rezolutie)*rezolutie;
	var yesterdaysValue=Math.round(data[minTSIdx][colIdx]/rezolutie)*rezolutie;
	actualValue=1*actualValue.toFixed(6);
	yesterdaysValue=1*yesterdaysValue.toFixed(6);
	var delta=actualValue-yesterdaysValue;
	delta=1*delta.toFixed(6);
	if(delta>0)
		delta='+'+delta;
	delta=delta+' ';
	//alert(data[minTSIdx][0]);
	drawing.text({x:0,y:-0.34,text:minVal,size:0.1,bg:"#bbb"});
	drawing.text({x:0,y:+0.34,text:maxVal,size:0.1,bg:"#bbb"});
	if(actualValue>yesterdaysValue){
		drawing.text({x:0,y:0.2,text:actualValue,size:0.25,align:'center',fg:params.fg,bg:params.fg});
		drawing.text({x:0,y:0,text:delta+"&#8599;",size:0.1,bg:"#f00",align:"center"});
		drawing.text({x:0,y:-0.15,text:allSensors[sensorProperties.name].um,size:0.2,align:'center',fg:params.fg,bg:params.fg});
		//drawing.text({x:0,y:-0.05,text:delta,size:0.1,align:"center"});
	}else if(actualValue<yesterdaysValue){
		drawing.text({x:0,y:0.2,text:actualValue,size:0.25,align:'center',fg:params.fg,bg:params.fg});
		drawing.text({x:0,y:0,text:delta+"&#8600;",size:0.1,bg:"#00f",align:"center"});
		drawing.text({x:0,y:-0.15,text:allSensors[sensorProperties.name].um,size:0.2,align:'center',fg:params.fg,bg:params.fg});
		//drawing.text({x:0,y:-0.05,text:,size:0.1,align:"center"});
	}else{
		drawing.text({x:0,y:0,text:actualValue+allSensors[sensorProperties.name].um,size:0.2,align:'center',fg:params.fg,bg:params.fg});
	}