import org.dom4j.DocumentException;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.StringReader;
import java.util.List;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

/*
 * This sample demonstrates how to delete all failed builds.
 *
 * IMPORTANT: Make sure to check QuickBuild server log if you get exceptions reporting 
 * a 500 response status.
 */
public class DeleteBuilds {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws IOException, DocumentException {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("admin", "admin"));
        String configurationId = client.resource("http://localhost:8810/rest/ids")
        		.queryParam("configuration_path", "root/test").get(String.class);

        String buildsXML = client.resource("http://localhost:8810/rest/builds")
        		.queryParam("configuration_id", configurationId)
        		.queryParam("status", "FAILED").get(String.class);
        Document dom = new SAXReader().read(new StringReader(buildsXML));
        for (Element element: (List<Element>) dom.getRootElement().elements()) {
            client.resource("http://localhost:8810/rest/builds/" + element.elementTextTrim("id")).delete();
            System.out.println("Build deleted: " + element.elementText("version"));
        }
    }
}
