/*
 * Copyright PMEase (c) 2005-2006,
 * Date: 2006-1-11
 * Time: 18:30:08
 * All rights reserved.
 */

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

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

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

/*
 * This sample demonstrates how to list build artifacts of latest successful build
 * of specified configuration. 
 *
 * IMPORTANT: Make sure to check QuickBuild server log if you get exceptions reporting 
 * a 500 response status.
 */
public class ListArtifacts {

    @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 buildId = client.resource("http://localhost:8810/rest/ids")
        		.queryParam("build_name", configurationId + ":latest_successful").get(String.class);
        
        ClientResponse response = client.resource("http://localhost:8810/rest/files")
        		.queryParam("build_id", buildId)
        		.queryParam("path", "artifacts").get(ClientResponse.class);
        
        if (response.getStatus() == 204) {
        	System.out.println("Path does not exist.");
        } else if (response.getStatus() != 200) {
        	throw new RuntimeException("ERROR: " + response.getEntity(String.class));
        } else {
            Document dom = new SAXReader().read(new StringReader(response.getEntity(String.class)));

            System.out.println("Artifacts found:");
            for (Element element: (List<Element>)dom.getRootElement().elements()) {
                Date lastModified = new Date(Long.valueOf(element.elementTextTrim("lastModified")));
                System.out.println("Name: " + element.elementTextTrim("name") + 
                        ", Last Modified: " + lastModified);
            }
        }
        
    }
}
