Java example for scripting the RCSB-PDB RESTful Custom Report web services

For more information on the RESTful web services see here.

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class PostCustomReport
{
   
	public static final String SERVICELOCATION="http://www.rcsb.org/pdb/rest/customReport";
   
	public static void main(String[] args){

		StringBuffer sb = new StringBuffer("?pdbids=4HHB.A.,2CPK.E,3WHM.B,2D5Z.A");
		sb.append("&customReportColumns=chainLength,clusterNumber100,clusterNumber90,clusterNumber70,uniprotRecommendedName,geneName,taxonomyId,taxonomy");
		sb.append("&service=wsfile&format=csv");

		String qstr = sb.toString();

	  	PostCustomReport r = new PostCustomReport();

		try {
      
			List<String> dataset = r.postQuery(qstr);

			for (String string : dataset)
			{
				System.out.println(string);
			}
		} catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
   
   	/** post pdbids and fields in a query string to the RESTful RCSB web service
	*
	* @param url
	* @return report dataset.
	*/
   	public List<String> postQuery(String url)
		throws IOException
	{

		URL u = new URL(SERVICELOCATION);

		String encodedUrl = URLEncoder.encode(url,"UTF-8");

		InputStream in =  doPOST(u,encodedUrl);

		List<String> lines = new ArrayList<String>();

		BufferedReader rd = new BufferedReader(new InputStreamReader(in));

		String line;
		while ((line = rd.readLine()) != null) 
		{
			lines.add(line);
		}
		rd.close();
		return lines;
	}

	/** do a POST to a URL and return the response stream for further processing elsewhere.
	*
	*
	* @param url
	* @return
	* @throws IOException
	*/
	public static InputStream doPOST(URL url, String data)
		throws IOException
   	{

		// Send data
		URLConnection conn = url.openConnection();
		
		conn.setDoOutput(true);
		
		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

		wr.write(data);
		wr.flush();

		// Get the response
		return conn.getInputStream();
	}
}