JSON API » Sample clients » Java

// This is a sample client for the Enswitch JSON API.
// It is released into the public domain.
// It comes with absolutely no warranty, and is not supported.

import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

public class client {
	private static String base = "http://enswitch.example.com/api/json/";
	private static String function = "access/list";
	private static String username = "testuser";
	private static String password = "testpass";

	public static void main( String[] args ) {
		try {
			URLConnection uc = new URL( base + function + "/?auth_username=" + username + ";auth_password=" + password ).openConnection();
			ObjectMapper m = new ObjectMapper();
			JsonNode output = m.readTree( uc.getInputStream() );
			Iterator i = output.path( "responses" ).getElements();
			int fatal = 0;
			while ( i.hasNext() ) {
				JsonNode r = i.next();
				if ( r.path( "code" ).getIntValue() >= 400 ) {
					System.err.println( r.path( "message" ).getTextValue() );
					fatal = 1;
				}
			}
			if ( fatal == 1 ) {
				System.exit( 1 );
			}

			Iterator j = output.path( "data" ).getElements();
			while ( j.hasNext() ) {
				JsonNode d = j.next();
				System.out.println( "Remote access account id=" + d.path( "id" ).getTextValue() + ", name=" + d.path( "name" ).getTextValue() + "." );
			}

		} catch ( Exception e ) {
			e.printStackTrace();
		}
	}
}