{{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.
Parallel JUnit execution runner - just annotate your @Parametrized class with @Parallelized
1 files attached: Parallelized.java
Parallelized.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;

public class Parallelized extends Parameterized {

	private static class ThreadPoolScheduler implements RunnerScheduler {
		private ExecutorService executor;

		public ThreadPoolScheduler() {
			int numThreads = GenericTestCase.getIntProperty("threads");
			executor = Executors.newFixedThreadPool(numThreads);
		}

		@Override
		public void finished() {
			executor.shutdown();
			try {
				executor.awaitTermination(10, TimeUnit.MINUTES);
			} catch (InterruptedException exc) {
				throw new RuntimeException(exc);
			}
		}

		@Override
		public void schedule(Runnable childStatement) {
			executor.submit(childStatement);
		}
	}

	public Parallelized(Class klass) throws Throwable {
		super(klass);
		setScheduler(new ThreadPoolScheduler());
	}
}
My Java-Groovy joint builder (based on the UberCompile ant task)
(Some of the) Advantages:
  • No Maven or Gradle required;
  • No dependency (except JAVA_HOME and required JARs);
  • Can compile interdependent Java and Groovy code;
(Some of the) Disadvantages:
  • you need to indicate the path to the JARs;
  • Designed to work on Sun VMs;
The eu.sorescu.reflect.JARLoader is written based on Runtime dynamic loading of JARs.
1 files attached: GroovyProjectCompiler.java
GroovyProjectCompiler.java
How to make Java ignore the certificate errors
1 files attached: SSLUtil.java
SSLUtil.java
package dms.os;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public final class SSLUtil {
	private static HashSet<KeyManager> keyManagers = new HashSet<KeyManager>();
	static {
		trustAllHosts();
	}
	public static TrustManager[] _trustManagers = new TrustManager[] { new X509TrustManager() {
		private final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return (_AcceptedIssuers);
		}
	} };

	public static void addClientCertificate(byte[] data, String password)
			throws KeyManagementException, NoSuchAlgorithmException,
			UnrecoverableKeyException, KeyStoreException, CertificateException,
			FileNotFoundException, IOException {
		SSLContext context = SSLContext.getInstance("TLS");
		for (KeyManager km : getKeyManagers(data, password))
			keyManagers.add(km);
		context.init(keyManagers.toArray(new KeyManager[keyManagers.size()]),
				_trustManagers, new SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(context
				.getSocketFactory());
	}

	private static KeyManager[] getKeyManagers(byte[] data, String password)
			throws UnrecoverableKeyException, KeyStoreException,
			NoSuchAlgorithmException, CertificateException,
			FileNotFoundException, IOException {
		KeyManagerFactory tmf = null;
		char[] passwKey = password.toCharArray();
		KeyStore ts = KeyStore.getInstance("PKCS12");
		ts.load(new ByteArrayInputStream(data), passwKey);
		tmf = KeyManagerFactory.getInstance("SunX509");
		tmf.init(ts, passwKey);
		return tmf.getKeyManagers();
	}

	public static void trustAllHosts() {

		HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
			public boolean verify(String hostname,
					javax.net.ssl.SSLSession session) {
				return (true);
			}
		});
	}
}
Java class overloading/reloading - how two objects apparently belonging to the same class but they do not
Questions and answers for people that understand the code below:
  • why didn't I reload some java.lang.XXX? Because I needed to start the instrumentation agent to manipulate the AST - extra lines in article due to the standard Sun JVM behaviour on class loader priority imposed by the ClassLoader.getSystemClassLoader(); laziness...
  • Why didn't I reload also the AbstractButton so that my button can access it? Because the access octopus would spread far away...
  • Why could I reload a class that otherwise was accessible by the standard JVM class loader? The Oracle site says you cannot...; answer - I broke the Class Loading priority  convention - it's a convention, not an imposed rule to ask first the ClassLoader.parent.; second - I indicated explicitly the class loader I wanted to use.
  • Who would use such a thing?!? Java Web Start, Java Applets, and java Servlet containers, at least. :)
Expected outcome:
class hashCode
1952592365
1457769401
----------------------
check if new JButton().getClass() == our class
Original class: true
Artificial class: false
----------------------
toString for classes
originalClass: class javax.swing.JButton
artificialClass: class javax.swing.JButton
------------------
Check if classes are the same...
artificialButton.getClass() == button.getClass(): false
syntheticObject instanceof JButton: false
java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JButton
Cannot cast from class javax.swing.JButton to class javax.swing.JButton!?!
This is the genuine button toString(): javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@5abbfa4c,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=,defaultCapable=true]
java.lang.IllegalAccessError: tried to access field javax.swing.AbstractButton.defaultCapable from class javax.swing.JButton
Cannot run toString for the artificial button because:
AbstractButton.defaultCapable is hidden for classes that don't inherit the AbstractButton.
And our artificialButton JButton tried to access the AbstractButton protected field.
And that AbstractButton is the JVM standard class loader - remember if (name.equals("javax.swing.JButton"))?
1 files attached: Test.java
Test.java
Windows Media Encoder 9 - small, efficient, and powerful enough for screen capturing and streaming
Open the link http://www.microsoft.com/en-us/download/details.aspx?id=17792; choose downloading; next next next... accept T&C... next next next... install...
Wait few seconds, and you're done.
Once you start the program, choose Capture screen option, then choose between Specific window, Region of the screen, or Entire screen.
Then, enjoy the recording and the very small size of the encoded file - but still capturing all the details from your display.
Runtime dynamic loading of JARs (valid only on Sun JVMs)
Shortest (as of now) way for me to dynamically load classes from JARs that are not defined in the project.
public static synchronized void loadJAR(File jar) throws ClassNotFoundException {
	try {
		URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		URL url = jar.toURI().toURL();
		if (Arrays.asList(loader.getURLs()).contains(url))
			return;
		Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { java.net.URL.class });
		method.setAccessible(true);
		method.invoke(loader, new Object[] { url });
	} catch (final ReflectiveOperationException e) {
		throw new ClassFormatError(e.getMessage());
	} catch (final java.net.MalformedURLException e) {
		throw new ClassNotFoundException(e.getMessage());
	}
}
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