/* WSDL 2.0 validator using Woden
   Doc: http://incubator.apache.org/woden/userguide.html#Getting+Started
   hugo@w3.org
*/

import org.apache.woden.WSDLFactory;
import org.apache.woden.WSDLReader;
import org.apache.woden.wsdl20.Description;
import org.apache.woden.wsdl20.xml.DescriptionElement;
import org.apache.woden.WSDLException;
import org.apache.woden.ErrorHandler;
import org.apache.woden.ErrorInfo;

public class ValidateWSDL2 implements ErrorHandler {

    private int exitcode;
    private boolean valid;

    public ValidateWSDL2(String wsdlurl) {

	exitcode = 0;
	valid = true;

	try {
	    WSDLFactory factory = WSDLFactory.newInstance();
	    WSDLReader reader = factory.newWSDLReader();
	    reader.setFeature(WSDLReader.FEATURE_VALIDATION, true);
	    DescriptionElement descElem = reader.readWSDL(wsdlurl, this);
	    Description descComp = descElem.toComponent();
        } catch (WSDLException e) {
	    System.err.println("Something went really wrong!");
	    System.err.println(e);
	    System.exit(1);
	    return;
        }
    }

    private void errorh(String type, ErrorInfo e) {
        System.out.println("[" + type + "]\t" + e);
    }

    public void warning(ErrorInfo e) {
        errorh("Warning", e);
    }
    public void error(ErrorInfo e) {
        errorh("Error", e);
	exitcode = 2;
	valid=false;
    }
    public void fatalError(ErrorInfo e) {
        errorh("Fatal", e);
	exitcode = 1;
	valid=false;
    }

    public int exit() {
        return exitcode;
    }

    public boolean isValid() {
        return valid;
    }

    public static void main (String[] args) {
        if (args == null || args.length != 1) {
            System.err.println("Usage: ValidateWSDL2 <WSDL location>");
            return;
        }
        ValidateWSDL2 validator = new ValidateWSDL2(args[0]);
	if (validator.isValid()) {
	    System.out.println("\nThis document is valid. Congratulations.");
	} else {
	    System.out.println("\nSorry, this document is not valid.");
	}
        System.exit(validator.exit());
    }

}

