import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.StringReader;

/*
 * This sample demonstrates how to create a new configuration by copying an existing one.
 * 
 * IMPORTANT: Make sure to check QuickBuild server log if you get exceptions reporting 
 * a 500 response status.
 */
public class CopyConfiguration {

    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 configurationXML = client.resource("http://localhost:8810/rest/configurations/" + configurationId)
        		.get(String.class);
        Document dom = new SAXReader().read(new StringReader(configurationXML));
        dom.getRootElement().element("name").setText("test-copy");
        
        // Make sure to remove the id element to create a new configuration; otherwise
        // QuickBuild will update existing configuration with the same id.
        dom.getRootElement().element("id").detach();

        String id = client.resource("http://localhost:8810/rest/configurations")
                .post(String.class, dom.asXML());
        System.out.println("Id of newly created configuration is: " + id);
    }
}
