package com.chenyang.nse.bussiness.engine.infa.basic.webservice;

import com.chenyang.nse.bussiness.engine.infa.InfoProperty;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import javax.xml.ws.Service.Mode;
import org.w3c.dom.Document;

public class LoginWebService {
   public static String returnStatus(InfoProperty engine) throws Exception {
      String ns = engine.getWebserviceurl();
      String wsdlUrl = engine.getWebserviceserverurl();
      URL url = new URL(wsdlUrl);
      QName sname = new QName(ns, "DataIntegrationService");
      Service service = Service.create(url, sname);
      Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns, "DataIntegration"), SOAPMessage.class, Mode.MESSAGE);
      SOAPMessage msg = MessageFactory.newInstance("SOAP 1.1 Protocol").createMessage();
      SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
      SOAPBody body = envelope.getBody();
      QName ename = new QName(ns, "Login", "ns0");
      SOAPBodyElement ele = body.addBodyElement(ename);
      ele.addChildElement("RepositoryDomainName").setValue(engine.getDomainname());
      ele.addChildElement("RepositoryName").setValue(engine.getRepository());
      ele.addChildElement("UserName").setValue(engine.getUsername());
      ele.addChildElement("Password").setValue(engine.getPassword());
      ele.addChildElement("UserNameSpace").setValue("");

      try {
         SOAPMessage response = (SOAPMessage)dispatch.invoke(msg);
         Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
         if (doc.getElementsByTagName("LoginReturn") == null) {
            return "FAIL";
         } else {
            String str = doc.getElementsByTagName("LoginReturn").item(0).getTextContent();
            return str;
         }
      } catch (Exception e) {
         e.printStackTrace();
         return "FAIL";
      }
   }
}
