public void addSobjects(
      String strOperation,
      String strParamName,
      MessageContext synCtx,
      SynapseLog synLog,
      String strExternalId) {
    SOAPEnvelope envelope = synCtx.getEnvelope();
    OMFactory fac = OMAbstractFactory.getOMFactory();
    SOAPBody body = envelope.getBody();
    Iterator<OMElement> bodyChildElements = body.getChildrenWithLocalName(strOperation);
    if (bodyChildElements.hasNext()) {
      try {
        OMElement bodyElement = bodyChildElements.next();
        if (strExternalId != null) {
          OMNamespace omNs = fac.createOMNamespace("urn:partner.soap.sforce.com", "urn");
          OMElement value = fac.createOMElement("externalIDFieldName", omNs);
          value.addChild(fac.createOMText(strExternalId));
          bodyElement.addChild(value);
        }
        String strSobject = (String) ConnectorUtils.lookupTemplateParamater(synCtx, strParamName);
        OMElement sObjects = AXIOMUtil.stringToOM(strSobject);
        Iterator<OMElement> sObject = sObjects.getChildElements();
        String strType =
            sObjects.getAttributeValue(new QName(SalesforceUtil.SALESFORCE_CREATE_SOBJECTTYPE));
        OMElement tmpElement = null;
        OMNamespace omNsurn = fac.createOMNamespace("urn:partner.soap.sforce.com", "urn");
        OMNamespace omNsurn1 = fac.createOMNamespace("urn:sobject.partner.soap.sforce.com", "urn1");
        // Loops sObject
        while (sObject.hasNext()) {
          OMElement currentElement = sObject.next();
          OMElement newElement = fac.createOMElement("sObjects", omNsurn);
          // Add Object type
          if (strType != null) {
            tmpElement = fac.createOMElement("type", omNsurn1);
            tmpElement.addChild(fac.createOMText(strType));
            newElement.addChild(tmpElement);
          }
          // Add the fields
          Iterator<OMElement> sObjectFields = currentElement.getChildElements();
          while (sObjectFields.hasNext()) {
            OMElement sObjectField = sObjectFields.next();
            tmpElement = fac.createOMElement(sObjectField.getLocalName(), omNsurn1);
            tmpElement.addChild(fac.createOMText(sObjectField.getText()));
            newElement.addChild(tmpElement);
          }

          bodyElement.addChild(newElement);
        }
      } catch (Exception e) {
        synLog.error("Saleforce adaptor - error injecting sObjects to payload : " + e);
      }
    }
  }
  private static boolean JARServiceTest() {
    boolean JARServiceStatus = false;
    OMElement result;
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://ws.apache.org/axis2", "ns1");
    OMElement payload = fac.createOMElement("echo", omNs);
    OMElement value = fac.createOMElement("args0", omNs);
    value.addChild(fac.createOMText(value, "Hello-World"));
    payload.addChild(value);

    ServiceClient serviceclient;
    try {
      serviceclient = new ServiceClient();
      Options opts = new Options();

      opts.setTo(new EndpointReference(HTTP_APPSERVER_STRATOSLIVE_URL + "/SimpleJarService"));
      opts.setAction("echo");
      // bypass http protocol exception
      opts.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);

      serviceclient.setOptions(opts);

      result = serviceclient.sendReceive(payload);

      if ((result.toString().indexOf("Hello-World")) > 0) {
        JARServiceStatus = true;
      }
      assertTrue("Jar service invocation failed", JARServiceStatus);

    } catch (AxisFault axisFault) {
      log.error("Jar service invocation failed:" + axisFault.getMessage());
      fail("Jar service invocation failed:" + axisFault.getMessage());
    }
    return JARServiceStatus;
  }
/** Serializer for {@link org.apache.synapse.mediators.Value} instances. */
public class ValueSerializer {
  protected static final OMFactory fac = OMAbstractFactory.getOMFactory();
  protected static final OMNamespace nullNS =
      fac.createOMNamespace(XMLConfigConstants.NULL_NAMESPACE, "");

  /**
   * Serialize the Value object to an OMElement representing the entry
   *
   * @param key Value to serialize
   * @param elem OMElement
   * @return OMElement
   */
  public OMElement serializeValue(Value key, String name, OMElement elem) {
    if (key != null) {
      if (key.getExpression() == null) {
        // static key
        elem.addAttribute(fac.createOMAttribute(name, nullNS, key.getKeyValue()));
      } else {
        String startChar = "{", endChar = "}";
        // if this is an expr type key we add an additional opening and closing brace
        if (key.hasExprTypeKey()) {
          startChar = startChar + "{";
          endChar = endChar + "}";
        }
        // dynamic key
        SynapsePathSerializer.serializePath(
            key.getExpression(), startChar + key.getExpression().toString() + endChar, elem, name);
      }
    }
    return elem;
  }

  /**
   * Serialize the Value object to an OMElement representing the entry
   *
   * @param key Value to serialize
   * @param elem OMElement
   * @return OMElement
   */
  public OMElement serializeTextValue(Value key, String name, OMElement elem) {
    if (key != null) {
      if (key.getExpression() == null) {
        // static key
        elem.setText(key.getKeyValue());
      } else {
        String startChar = "{", endChar = "}";
        // if this is an expr type key we add an additional opening and
        // closing brace
        if (key.hasExprTypeKey()) {
          startChar = startChar + "{";
          endChar = endChar + "}";
        }
        // dynamic key
        SynapsePathSerializer.serializeTextPath(
            key.getExpression(), startChar + key.getExpression().toString() + endChar, elem, name);
      }
    }
    return elem;
  }
}
  public void sendUsingMTOM(String fileName, String targetEPR) throws IOException {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
    OMElement payload = factory.createOMElement("uploadFileUsingMTOM", ns);
    OMElement request = factory.createOMElement("request", ns);
    OMElement image = factory.createOMElement("image", ns);

    FileDataSource fileDataSource = new FileDataSource(new File(fileName));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    OMText textData = factory.createOMText(dataHandler, true);
    image.addChild(textData);
    request.addChild(image);
    payload.addChild(request);

    ServiceClient serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference(targetEPR));
    options.setAction("urn:uploadFileUsingMTOM");
    options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
    options.setCallTransportCleanup(true);
    serviceClient.setOptions(options);
    OMElement response = serviceClient.sendReceive(payload);
    Assert.assertTrue(
        response
            .toString()
            .contains(
                "<m:testMTOM xmlns:m=\"http://services.samples/xsd\">"
                    + "<m:test1>testMTOM</m:test1></m:testMTOM>"));
  }
  /**
   * Retrieve all entries from service.
   *
   * @return All entries of type Entry from the service.
   * @exception FailureFaultException If an error communication with the service occurs.
   */
  public Entry[] retrieve() throws FailureFaultException {
    final String method = "retrieve";
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace namespace = factory.createOMNamespace(SERVICE, method);

    // Create a request
    OMElement request = factory.createOMElement("RetrieveRequest", namespace);

    // Configure connection
    Options options = new Options();
    options.setTo(new EndpointReference(url.toString()));
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
    options.setAction(method);

    // Create a client
    try {
      ServiceClient client = new ServiceClient();
      client.setOptions(options);

      // Try send request and receive response, could throw AxisFault
      OMElement response = client.sendReceive(request);

      // Debug
      printDebug("RESPONSE", response);

      // Parse and return result
      Entry[] result = XMLUtil.parseScores(response);
      return result;
    } catch (AxisFault e) {
      throw new FailureFaultException("Exception from service: ", e);
    }
  }
 public void addIds(
     String strOperation, String strParamName, MessageContext synCtx, SynapseLog synLog) {
   SOAPEnvelope envelope = synCtx.getEnvelope();
   OMFactory fac = OMAbstractFactory.getOMFactory();
   SOAPBody body = envelope.getBody();
   Iterator<OMElement> bodyChildElements = body.getChildrenWithLocalName(strOperation);
   if (bodyChildElements.hasNext()) {
     try {
       OMElement bodyElement = bodyChildElements.next();
       Iterator<OMElement> cElements = bodyElement.getChildElements();
       if (cElements != null && cElements.hasNext()) {
         cElements.next();
       }
       String strSobject = (String) ConnectorUtils.lookupTemplateParamater(synCtx, strParamName);
       OMElement sObjects = AXIOMUtil.stringToOM(strSobject);
       Iterator<OMElement> sObject = sObjects.getChildElements();
       OMNamespace omNsurn = fac.createOMNamespace("urn:partner.soap.sforce.com", "urn");
       // Loops sObject
       while (sObject.hasNext()) {
         OMElement currentElement = sObject.next();
         OMElement newElement = fac.createOMElement("ids", omNsurn);
         // Add the fields
         newElement.addChild(fac.createOMText(currentElement.getText()));
         bodyElement.addChild(newElement);
       }
     } catch (Exception e) {
       synLog.error("Saleforce adaptor - error injecting sObjects to payload : " + e);
     }
   }
 }
  private OMElement handleSLORequest(MessageContext messageContext, LogoutRequest logoutRequest) {

    // Get the session index from the SLORequest and remove the relevant session.
    String sessionIndex = logoutRequest.getSessionIndexes().get(0).getSessionIndex();

    String sessionId = CacheManager.getInstance().getSessionIndexMappingCache().get(sessionIndex);

    if (sessionId != null) {
      GatewayUtils.logWithRequestInfo(
          log,
          messageContext,
          String.format(
              "Found a session id (md5 : '%s')for the given session index in the SLO request: '%s'. Clearing the session",
              GatewayUtils.getMD5Hash(sessionId), sessionIndex));
      SessionStore.getInstance().removeSession(sessionId);
      CacheManager.getInstance().getSessionIndexMappingCache().remove(sessionIndex);
    } else {
      GatewayUtils.logWithRequestInfo(
          log,
          messageContext,
          String.format(
              "Couldn't find a session id for the given session index : '%s'", sessionIndex));
    }

    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace ns = fac.createOMNamespace("http://wso2.org/appm", "appm");
    OMElement payload = fac.createOMElement("SLOResponse", ns);

    OMElement errorMessage = fac.createOMElement("message", ns);
    errorMessage.setText("SLORequest has been successfully processed by WSO2 App Manager");

    payload.addChild(errorMessage);

    return payload;
  }
  @Override
  public void connect(MessageContext messageContext) throws ConnectException {
    String providerUrl = LDAPUtils.lookupContextParams(messageContext, LDAPConstants.PROVIDER_URL);
    String dn = (String) getParameter(messageContext, "dn");
    String password = (String) getParameter(messageContext, "password");

    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(LDAPConstants.CONNECTOR_NAMESPACE, "ns");
    OMElement result = factory.createOMElement("result", ns);
    OMElement message = factory.createOMElement("message", ns);

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);

    org.apache.axis2.context.MessageContext axis2MessageContext =
        ((Axis2MessageContext) messageContext).getAxis2MessageContext();

    boolean logged = false;
    DirContext ctx = null;
    try {
      ctx = new InitialDirContext(env);
      message.setText("Success");
      result.addChild(message);
      LDAPUtils.preparePayload(messageContext, result);
    } catch (NamingException e) {
      message.setText("Fail");
      result.addChild(message);
      LDAPUtils.preparePayload(messageContext, result);
    }
  }
 private OMElement createCustomQuoteRequest(String symbol) {
   OMFactory factory = OMAbstractFactory.getOMFactory();
   OMNamespace ns = factory.createOMNamespace("http://services.samples", "ns");
   OMElement chkPrice = factory.createOMElement("CheckPriceRequest", ns);
   OMElement code = factory.createOMElement("Code", ns);
   chkPrice.addChild(code);
   code.setText(symbol);
   return chkPrice;
 }
 private static OMElement createPayLoad() {
   OMFactory fac = OMAbstractFactory.getOMFactory();
   OMNamespace omNs = fac.createOMNamespace("http://service.carbon.wso2.org", "ns1");
   OMElement method = fac.createOMElement("echoString", omNs);
   OMElement value = fac.createOMElement("s", omNs);
   value.addChild(fac.createOMText(value, "Hello World"));
   method.addChild(value);
   return method;
 }
  private OMElement createStandardSimpleRequest(String symbol) {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
    OMElement method = fac.createOMElement("getSimpleQuote", omNs);
    OMElement value1 = fac.createOMElement("symbol", omNs);

    value1.addChild(fac.createOMText(method, symbol));
    method.addChild(value1);

    return method;
  }
  private OMElement getPlaceOrderPayload(String symbolValue) {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ser");
    OMNamespace xsdNs = fac.createOMNamespace("http://services.samples", "xsd");
    OMElement payload = fac.createOMElement("placeOrder", omNs);
    OMElement order = fac.createOMElement("order", omNs);

    OMElement price = fac.createOMElement("price", xsdNs);
    price.setText("invalid");
    OMElement quantity = fac.createOMElement("quantity", xsdNs);
    quantity.setText("invalid");
    OMElement symbol = fac.createOMElement("symbol", xsdNs);
    symbol.setText(symbolValue);

    order.addChild(price);
    order.addChild(quantity);
    order.addChild(symbol);
    payload.addChild(order);
    return payload;
  }
Beispiel #13
0
  private static OMElement getPayload(String value) {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns =
        factory.createOMNamespace("http://sample05.policy.samples.rampart.apache.org", "ns1");
    OMElement elem = factory.createOMElement("echo", ns);
    OMElement childElem = factory.createOMElement("param0", null);
    childElem.setText(value);
    elem.addChild(childElem);

    return elem;
  }
Beispiel #14
0
  private static OMElement getPingOMBlock(String text) {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace namespace = fac.createOMNamespace(applicationNamespaceName, "ns1");
    OMElement pingElem = fac.createOMElement(ping, namespace);
    OMElement textElem = fac.createOMElement(Text, namespace);

    textElem.setText(text);
    pingElem.addChild(textElem);

    return pingElem;
  }
  private OMElement createPayload() {

    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://localhost/my", "my");
    OMElement rpcWrapEle = fac.createOMElement("echoMTOMtoBase64", omNs);
    OMElement data = fac.createOMElement("data", omNs);
    byte[] byteArray = new byte[] {13, 56, 65, 32, 12, 12, 7, 98};
    DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(byteArray));
    expectedTextData = new OMTextImpl(dataHandler, true, fac);
    data.addChild(expectedTextData);
    rpcWrapEle.addChild(data);
    return rpcWrapEle;
  }
Beispiel #16
0
  private static OMElement getEchoOMBlock(String text, String sequenceKey) {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace applicationNamespace = fac.createOMNamespace(applicationNamespaceName, "ns1");
    OMElement echoStringElement = fac.createOMElement(echoString, applicationNamespace);
    OMElement textElem = fac.createOMElement(Text, applicationNamespace);
    OMElement sequenceElem = fac.createOMElement(Sequence, applicationNamespace);

    textElem.setText(text);
    sequenceElem.setText(sequenceKey);
    echoStringElement.addChild(textElem);
    echoStringElement.addChild(sequenceElem);

    OMNamespace namespace =
        fac.createOMNamespace(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI, "env");
    OMAttribute attr =
        fac.createOMAttribute(
            "encodingStyle", namespace, "http://schemas.xmlsoap.org/soap/encoding/");

    echoStringElement.addAttribute(attr);

    return echoStringElement;
  }
 public static OMElement CreatePayload() // this function create a message to send to server
     {
   OMFactory fac =
       OMAbstractFactory
           .getOMFactory(); // Create object(fac)from OM Factory this is used to create all the
                            // elements.
   OMNamespace omns =
       fac.createOMNamespace(
           "http://ws.wso2.org/dataservice",
           "b"); // creating namespace to assign to message, b =  namespace
   OMElement OP1 = fac.createOMElement("OP_Count", omns); // Operation name
   return OP1;
 }
  private OMElement getPayload() {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
    OMElement method = fac.createOMElement("getQuote", omNs);
    OMElement value1 = fac.createOMElement("request", omNs);
    OMElement value2 = fac.createOMElement("symbol", omNs);

    value2.addChild(fac.createOMText(value1, "Secured"));
    value1.addChild(value2);
    method.addChild(value1);

    return method;
  }
  private static OMElement getPayload() {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://service.esb.wso2.org", "ns");
    OMElement method = fac.createOMElement("add", omNs);
    OMElement value1 = fac.createOMElement("x", omNs);
    OMElement value2 = fac.createOMElement("y", omNs);

    value1.addChild(fac.createOMText(value1, "10"));
    value2.addChild(fac.createOMText(value2, "10"));
    method.addChild(value1);
    method.addChild(value2);

    return method;
  }
  private OMElement createMultipleQuoteRequest(String symbol, int iterations) {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://services.samples", "ns");
    OMElement method = fac.createOMElement("getQuote", omNs);

    for (int i = 0; i < iterations; i++) {
      OMElement value1 = fac.createOMElement("request", omNs);
      OMElement value2 = fac.createOMElement("symbol", omNs);
      value2.addChild(fac.createOMText(value1, symbol));
      value1.addChild(value2);
      method.addChild(value1);
    }
    return method;
  }
Beispiel #21
0
  private OMElement getPayload(String value) {
    OMFactory factory = null;
    OMNamespace ns = null;
    OMElement elem = null;
    OMElement childElem = null;

    factory = OMAbstractFactory.getOMFactory();
    ns = factory.createOMNamespace("http://echo.services.core.carbon.wso2.org", "ns");
    elem = factory.createOMElement("echoString", ns);
    childElem = factory.createOMElement("in", null);
    childElem.setText(value);
    elem.addChild(childElem);

    return elem;
  }
  @Test(
      groups = {"wso2.dss"},
      invocationCount = 5,
      dependsOnMethods = "testServiceDeployment")
  public void selectOperation() throws AxisFault, XPathExpressionException {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://www.w3.org/2005/08/addressing", "ns1");
    OMElement payload = fac.createOMElement("getAllUsers", omNs);

    OMElement result = new AxisServiceClient().sendReceive(payload, serviceUrl, "getAllUsers");
    Assert.assertTrue(result.toString().contains("Will Smith"));
    Assert.assertTrue(result.toString().contains("Denzel Washington"));

    log.info("Service invocation success");
  }
  /** @testStrategy: Create an OMElement, without using a builder. Verification of AXIS2-970 */
  public void test3() throws Exception {

    //    	 Step 1: Get the SAAJConverter object from the Factory
    SAAJConverterFactory f =
        (SAAJConverterFactory) FactoryRegistry.getFactory(SAAJConverterFactory.class);
    SAAJConverter converter = f.getSAAJConverter();

    // Stept 2: Create OM and parent SOAPElement
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace wrapNs = fac.createOMNamespace("namespace", "prefix");
    OMElement ome = fac.createOMElement("localname", wrapNs);
    SOAPFactory sf = SOAPFactory.newInstance();
    SOAPElement se = sf.createElement("name");

    // Step 3: Do the conversion
    converter.toSAAJ(ome, se, sf);
  }
Beispiel #24
0
  public OMElement toOMElement(OMElement element) throws OMException, AxisFault {

    OMFactory factory = element.getOMFactory();

    if (acksTo == null)
      throw new OMException(SandeshaMessageHelper.getMessage(SandeshaMessageKeys.acceptNullAcksTo));

    OMNamespace rmNamespace =
        factory.createOMNamespace(rmNamespaceValue, Sandesha2Constants.WSRM_COMMON.NS_PREFIX_RM);
    OMElement acceptElement =
        factory.createOMElement(Sandesha2Constants.WSRM_COMMON.ACCEPT, rmNamespace);

    acksTo.toOMElement(acceptElement);
    element.addChild(acceptElement);

    return element;
  }
Beispiel #25
0
  public OMElement toOMElement(OMElement body) throws OMException {

    if (body == null || !(body instanceof SOAPBody))
      throw new OMException(
          SandeshaMessageHelper.getMessage(
              SandeshaMessageKeys.closeSeqResponseCannotBeAddedToNonBody));

    if (identifier == null)
      throw new OMException(
          SandeshaMessageHelper.getMessage(SandeshaMessageKeys.closeSeqResponsePartNullID));

    OMFactory factory = body.getOMFactory();

    OMNamespace rmNamespace =
        factory.createOMNamespace(namespaceValue, Sandesha2Constants.WSRM_COMMON.NS_PREFIX_RM);
    OMElement closeSequenceResponseElement =
        factory.createOMElement(
            Sandesha2Constants.WSRM_COMMON.CLOSE_SEQUENCE_RESPONSE, rmNamespace);
    identifier.toOMElement(closeSequenceResponseElement, rmNamespace);
    body.addChild(closeSequenceResponseElement);

    return body;
  }
Beispiel #26
0
  /** @param args */
  public void sendMedicamento() {
    IWebServiceStub service = null;
    ResultSendMedicamento result = new ResultSendMedicamento();
    try {

      System.out.println("Inicio: " + new Timestamp(System.currentTimeMillis()));
      service = new IWebServiceStub("https://trazabilidad.pami.org.ar:9050/trazamed.WebService");
      // service = new
      // IWebServiceServiceStub("https://trazabilidad.pami.org.ar:9050/trazamed.WebService");

      ServiceClient serviceClient = service._getServiceClient();

      OMFactory omFactory = OMAbstractFactory.getOMFactory();

      OMElement security =
          omFactory.createOMElement(
              new QName(
                  "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                  "Security",
                  "wsse"),
              null);

      OMNamespace omNs =
          omFactory.createOMNamespace(
              "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
              "wsu");
      OMElement userNameToken = omFactory.createOMElement("UsernameToken", omNs);

      OMElement userName = omFactory.createOMElement("Username", omNs);
      userName.addChild(omFactory.createOMText("testwservice"));

      OMElement password = omFactory.createOMElement("Password", omNs);
      password.addChild(omFactory.createOMText("testwservicepsw"));

      userNameToken.addChild(userName);
      userNameToken.addChild(password);

      security.addChild(userNameToken);
      serviceClient.addHeader(security);

      serviceClient.getOptions().setTimeOutInMilliSeconds(1000000);

      // serviceClient.setOptions(o);

      String error = null;
      GetTransaccionesNoConfirmadasE ge = new GetTransaccionesNoConfirmadasE();
      GetTransaccionesNoConfirmadas g = new GetTransaccionesNoConfirmadas();
      g.setArg0("DROGUERIAORIEN");
      g.setArg1("ORIEN1152");

      g.setArg6("07795312001427");
      // g.setArg18("8137306466");
      ge.setGetTransaccionesNoConfirmadas(g);

      GetTransaccionesNoConfirmadasResponseE geR = new GetTransaccionesNoConfirmadasResponseE();

      System.out.println(
          "Voy a llmar a getTransaccionesNoConfirmadas "
              + new Timestamp(System.currentTimeMillis()));
      geR = service.getTransaccionesNoConfirmadas(ge);
      System.out.println(
          geR.getGetTransaccionesNoConfirmadasResponse().get_return().getList().length);
      System.out.println(
          "Llame a getTransaccionesNoConfirmadas " + new Timestamp(System.currentTimeMillis()));
      if (geR.getGetTransaccionesNoConfirmadasResponse().get_return().getErrores() != null) {
        WebServiceError[] wseArray =
            geR.getGetTransaccionesNoConfirmadasResponse().get_return().getErrores();
        for (WebServiceError wse : wseArray) {
          System.out.println(wse.get_d_error());
          error = wse.get_d_error();
        }
      }
      String idTransac = "";
      if (error == null
          && geR.getGetTransaccionesNoConfirmadasResponse().get_return().getList() != null) {
        for (TransaccionPlainWS t :
            geR.getGetTransaccionesNoConfirmadasResponse().get_return().getList()) {
          idTransac = t.get_id_transaccion();
        }
      }

      try {
        Long id_transac = Long.parseLong(idTransac);
        ConfirmacionTransaccionDTO[] series = new ConfirmacionTransaccionDTO[1];
        ConfirmacionTransaccionDTO serie = new ConfirmacionTransaccionDTO();
        serie.setP_ids_transac(id_transac);
        serie.setF_operacion(
            DateUtil.getFormatedSTDDate(new Timestamp(System.currentTimeMillis())));
        series[0] = serie;
        SendConfirmaTransaccE ge_ = new SendConfirmaTransaccE();
        SendConfirmaTransacc g_ = new SendConfirmaTransacc();
        g_.setArg0("ENTRERIOS205");
        g_.setArg1("ORIEN2012");
        g_.setArg2(series);
        ge_.setSendConfirmaTransacc(g_);

        System.out.println(
            "Voy a llmar a sendConfirmaTransacc " + new Timestamp(System.currentTimeMillis()));
        SendConfirmaTransaccResponseE result_confirm = service.sendConfirmaTransacc(ge_);
        System.out.println(
            "llame a sendConfirmaTransacc " + new Timestamp(System.currentTimeMillis()));
        String id_transac_ = "";
        if (result_confirm.getSendConfirmaTransaccResponse().get_return().getErrores() != null
            && result_confirm.getSendConfirmaTransaccResponse().get_return().getErrores().length
                > 0) {
          WebServiceError[] wseArray =
              result_confirm.getSendConfirmaTransaccResponse().get_return().getErrores();
          for (WebServiceError wse : wseArray) {
            result.setExito(false);
            result.setErrores(wse.get_d_error());
          }

        } else {
          id_transac_ =
              result_confirm
                  .getSendConfirmaTransaccResponse()
                  .get_return()
                  .getId_transac_asociada();
          result.setExito(true);
          result.setErrores("OK");
          result.setTransacNr(id_transac_);
        }

      } catch (Exception e) {
        result.setExito(false);
        result.setErrores("No se pudo obtener el id_transac_global");
      }

    } catch (AxisFault e1) {
      result.setExito(false);
      result.setErrores("No se pudo obtener el id_transac_global");
      e1.printStackTrace();
    } catch (RemoteException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      result.setExito(false);
      result.setErrores("No se pudo obtener el id_transac_global");
    }
    System.out.println(result.getErrores());
    System.out.println(result.getTransacNr());
    System.out.println("Fin: " + new Timestamp(System.currentTimeMillis()));
  }
  public void connect(MessageContext messageContext) throws ConnectException {
    try {

      String spreadsheetName =
          GoogleSpreadsheetUtils.lookupFunctionParam(messageContext, SPREADSHEET_NAME);
      if (spreadsheetName == null || "".equals(spreadsheetName.trim())) {
        log.error("Please make sure you have given a name for the spreadsheet");
        ConnectException connectException =
            new ConnectException("Please make sure you have given a name for the spreadsheet");
        GoogleSpreadsheetUtils.storeErrorResponseStatus(messageContext, connectException);
        return;
      }

      SpreadsheetService ssService =
          new GoogleSpreadsheetClientLoader(messageContext).loadSpreadsheetService();

      GoogleSpreadsheet gss = new GoogleSpreadsheet(ssService);

      SpreadsheetEntry ssEntry = gss.getSpreadSheetsByTitle(spreadsheetName);

      GoogleSpreadsheetWorksheet gssWorksheet =
          new GoogleSpreadsheetWorksheet(ssService, ssEntry.getWorksheetFeedUrl());

      List<String> resultData = gssWorksheet.getAllWorksheets();

      int resultSize = resultData.size();

      if (messageContext.getEnvelope().getBody().getFirstElement() != null) {
        messageContext.getEnvelope().getBody().getFirstElement().detach();
      }

      OMFactory factory = OMAbstractFactory.getOMFactory();
      OMNamespace ns =
          factory.createOMNamespace("http://org.wso2.esbconnectors.googlespreadsheet", "ns");
      OMElement searchResult = factory.createOMElement("getAllWorksheetsResult", ns);

      OMElement result = factory.createOMElement("result", ns);
      searchResult.addChild(result);
      result.setText("true");

      OMElement data = factory.createOMElement("data", ns);
      searchResult.addChild(data);

      for (int iterateCount = 0; iterateCount < resultSize; iterateCount++) {
        if (resultData.get(iterateCount) != null) {
          OMElement title = factory.createOMElement("title", ns);
          data.addChild(title);
          title.setText(resultData.get(iterateCount));
        }
      }

      messageContext.getEnvelope().getBody().addChild(searchResult);

    } catch (IOException te) {
      log.error("Failed to show status: " + te.getMessage(), te);
      GoogleSpreadsheetUtils.storeErrorResponseStatus(messageContext, te);
    } catch (ServiceException te) {
      log.error("Failed to show status: " + te.getMessage(), te);
      GoogleSpreadsheetUtils.storeErrorResponseStatus(messageContext, te);
    } catch (Exception te) {
      log.error("Failed to show status: " + te.getMessage(), te);
      GoogleSpreadsheetUtils.storeErrorResponseStatus(messageContext, te);
    }
  }
  /**
   * @param verifier
   * @return
   * @throws RelyingPartyException
   */
  protected String getIssuerInfoString(SAMLTokenVerifier verifier) throws RelyingPartyException {
    String issuerInfo = null;
    OMFactory factory = null;
    OMNamespace namespace = null;
    Element keyInfo = null;
    OMElement certificates = null;
    OMElement omKeyInfo = null;
    boolean siginingSet = false;
    OMElement certElem = null;
    Iterator<X509Certificate> certIterator = null;

    try {
      factory = OMAbstractFactory.getOMFactory();
      namespace =
          factory.createOMNamespace(TokenVerifierConstants.NS, TokenVerifierConstants.PREFIX);
      keyInfo = verifier.getKeyInfoElement();
      certIterator = verifier.getCertificates().iterator();

      while (certIterator.hasNext()) {
        X509Certificate cert = certIterator.next();
        byte[] encodedCert = cert.getEncoded();
        String base64Encoded = Base64.encode(encodedCert);

        if (certificates == null) {
          certificates = factory.createOMElement(TokenVerifierConstants.LN_CERTIFICATES, namespace);
        }

        certElem = factory.createOMElement(TokenVerifierConstants.LN_CERTIFICATE, namespace);

        if (siginingSet == false) {
          certElem.addAttribute(TokenVerifierConstants.LN_SIGNING_CERT, "true", null);
          siginingSet = true;
        }
        certElem.setText(base64Encoded);
        certificates.addChild(certElem);
      }

      if (keyInfo != null) {
        String value = IdentityUtil.nodeToString(keyInfo);
        XMLStreamReader parser =
            XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(value));
        StAXOMBuilder builder = new StAXOMBuilder(parser);
        omKeyInfo = builder.getDocumentElement();
      }
    } catch (Exception e) {
      log.error("Error while building issuer info", e);
      throw new RelyingPartyException("errorBuildingIssuerInfo");
    }

    if (certificates != null) {
      issuerInfo = certificates.toString();
    }

    if (omKeyInfo != null) {
      if (issuerInfo != null) {
        issuerInfo = issuerInfo + omKeyInfo.toString();
      } else {
        issuerInfo = omKeyInfo.toString();
      }
    }
    return issuerInfo;
  }
      public static NfeCabecMsg parse(final javax.xml.stream.XMLStreamReader reader)
          throws java.lang.Exception {
        final NfeCabecMsg object = new NfeCabecMsg();

        java.lang.String nillableValue = null;
        try {

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type")
              != null) {
            final java.lang.String fullTypeName =
                reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type");
            if (fullTypeName != null) {
              java.lang.String nsPrefix = null;
              if (fullTypeName.contains(":")) {
                nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":"));
              }
              nsPrefix = nsPrefix == null ? "" : nsPrefix;

              final java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1);

              if (!"nfeCabecMsg".equals(type)) {
                // find namespace for the prefix
                final java.lang.String nsUri =
                    reader.getNamespaceContext().getNamespaceURI(nsPrefix);
                return (NfeCabecMsg) ExtensionMapper.getTypeObject(nsUri, type, reader);
              }
            }
          }

          // Note all attributes that were handled. Used to differ normal attributes
          // from anyAttributes.
          final java.util.Vector<String> handledAttributes = new java.util.Vector<>();

          // now run through all any or extra attributes
          // which were not reflected until now
          for (int i = 0; i < reader.getAttributeCount(); i++) {
            if (!handledAttributes.contains(reader.getAttributeLocalName(i))) {
              // this is an anyAttribute and we create
              // an OMAttribute for this
              final org.apache.axiom.om.OMFactory factory =
                  org.apache.axiom.om.OMAbstractFactory.getOMFactory();
              final org.apache.axiom.om.OMAttribute attr =
                  factory.createOMAttribute(
                      reader.getAttributeLocalName(i),
                      factory.createOMNamespace(
                          reader.getAttributeNamespace(i), reader.getAttributePrefix(i)),
                      reader.getAttributeValue(i));

              // and add it to the extra attributes

              object.addExtraAttributes(attr);
            }
          }

          reader.next();

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.isStartElement()
              && new javax.xml.namespace.QName(
                      "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "versaoDados")
                  .equals(reader.getName())) {

            nillableValue =
                reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
            if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
              throw new org.apache.axis2.databinding.ADBException(
                  "The element: " + "versaoDados" + "  cannot be null");
            }

            final java.lang.String content = reader.getElementText();

            object.setVersaoDados(
                org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));

            reader.next();

          } // End of if for expected property start element
          else {

          }

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.isStartElement()
              && new javax.xml.namespace.QName(
                      "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "cUF")
                  .equals(reader.getName())) {

            nillableValue =
                reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
            if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
              throw new org.apache.axis2.databinding.ADBException(
                  "The element: " + "cUF" + "  cannot be null");
            }

            final java.lang.String content = reader.getElementText();

            object.setCUF(
                org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));

            reader.next();

          } // End of if for expected property start element
          else {

          }

          while (!reader.isStartElement() && !reader.isEndElement()) {
            reader.next();
          }

          if (reader.isStartElement()) {
            // A start element we are not expecting indicates a trailing invalid property
            throw new org.apache.axis2.databinding.ADBException(
                "Unexpected subelement " + reader.getName());
          }

        } catch (final javax.xml.stream.XMLStreamException e) {
          throw new java.lang.Exception(e);
        }

        return object;
      }
/**
 * This class contains static methods to generate REST Service registry artifact from the swagger
 * doc added to the Registry.
 */
public class RESTServiceUtils {

  private static final Log log = LogFactory.getLog(RESTServiceUtils.class);
  private static final String OVERVIEW = "overview";
  private static final String PROVIDER = "provider";
  private static final String NAME = "name";
  private static final String CONTEXT = "context";
  private static final String VERSION = "version";
  private static final String TRANSPORTS = "transports";
  private static final String DESCRIPTION = "description";
  private static final String URI_TEMPLATE = "uritemplate";
  private static final String URL_PATTERN = "urlPattern";
  private static final String AUTH_TYPE = "authType";
  private static final String HTTP_VERB = "httpVerb";
  private static final String ENDPOINT_URL = "endpointURL";
  private static final String WADL = "wadl";
  private static final String PATH_SEPERATOR = "/";
  private static final String METHOD = "method";
  private static final String PATH = "path";
  private static final String RESOURCE = "resource";
  private static final String INTERFACE = "interface";
  private static final String SWAGGER = "swagger";

  private static OMFactory factory = OMAbstractFactory.getOMFactory();
  private static OMNamespace namespace =
      factory.createOMNamespace(CommonConstants.SERVICE_ELEMENT_NAMESPACE, "");
  private static String commonRestServiceLocation;
  private static String commonEndpointLocation;

  /**
   * Extracts the data from swagger and creates an REST Service registry artifact. In 5.1.0 please
   * remove this method.
   *
   * @param swaggerDocObject swagger Json Object.
   * @param swaggerVersion swagger version.
   * @param resourceObjects swagger resource object list.
   * @return The API metadata
   * @throws RegistryException If swagger content is invalid.
   */
  public static OMElement createRestServiceArtifact(
      JsonObject swaggerDocObject,
      String swaggerVersion,
      String endpointURL,
      List<JsonObject> resourceObjects,
      String swaggerPath)
      throws RegistryException {

    if (swaggerDocObject == null || swaggerVersion == null) {
      throw new IllegalArgumentException(
          "Arguments are invalid. cannot create the REST service artifact. ");
    }

    OMElement data = factory.createOMElement(CommonConstants.SERVICE_ELEMENT_ROOT, namespace);
    OMElement overview = factory.createOMElement(OVERVIEW, namespace);
    OMElement provider = factory.createOMElement(PROVIDER, namespace);
    OMElement name = factory.createOMElement(NAME, namespace);
    OMElement context = factory.createOMElement(CONTEXT, namespace);
    OMElement apiVersion = factory.createOMElement(VERSION, namespace);
    OMElement endpoint = factory.createOMElement(ENDPOINT_URL, namespace);
    OMElement transports = factory.createOMElement(TRANSPORTS, namespace);
    OMElement description = factory.createOMElement(DESCRIPTION, namespace);
    List<OMElement> uriTemplates = null;

    JsonObject infoObject = swaggerDocObject.get(SwaggerConstants.INFO).getAsJsonObject();
    // get api name.
    String apiName = getChildElementText(infoObject, SwaggerConstants.TITLE).replaceAll("\\s", "");
    name.setText(apiName);
    context.setText("/" + apiName);
    // get api description.
    description.setText(getChildElementText(infoObject, SwaggerConstants.DESCRIPTION));
    // get api provider. (Current logged in user) : Alternative - CurrentSession.getUser();
    provider.setText(CarbonContext.getThreadLocalCarbonContext().getUsername());
    endpoint.setText(endpointURL);

    if (SwaggerConstants.SWAGGER_VERSION_2.equals(swaggerVersion)) {
      apiVersion.setText(getChildElementText(infoObject, SwaggerConstants.VERSION));
      transports.setText(getChildElementText(swaggerDocObject, SwaggerConstants.SCHEMES));
      uriTemplates = createURITemplateFromSwagger2(swaggerDocObject);
    } else if (SwaggerConstants.SWAGGER_VERSION_12.equals(swaggerVersion)) {
      apiVersion.setText(getChildElementText(swaggerDocObject, SwaggerConstants.API_VERSION));
      uriTemplates = createURITemplateFromSwagger12(resourceObjects);
    }

    overview.addChild(provider);
    overview.addChild(name);
    overview.addChild(context);
    overview.addChild(apiVersion);
    overview.addChild(description);
    overview.addChild(endpoint);
    data.addChild(overview);

    OMElement interfaceElement = factory.createOMElement(INTERFACE, namespace);
    OMElement swagger = factory.createOMElement(SWAGGER, namespace);
    swagger.setText(swaggerPath);
    interfaceElement.addChild(swagger);
    interfaceElement.addChild(transports);
    data.addChild(interfaceElement);
    if (uriTemplates != null) {
      for (OMElement uriTemplate : uriTemplates) {
        data.addChild(uriTemplate);
      }
    }

    return data;
  }

  /**
   * Extracts the data from swagger and creates an REST Service registry artifact. In 5.1.0 Please
   * remove the above method
   *
   * @param swaggerDocObject swagger Json Object.
   * @param swaggerVersion swagger version.
   * @param endpointURL Endpoint of the swagger
   * @param resourceObjects swagger resource object list.
   * @param swaggerPath Swagger resource path
   * @param documentVersion Swaggers registry version
   * @return The API metadata
   * @throws RegistryException If swagger content is invalid.
   */
  public static OMElement createRestServiceArtifact(
      JsonObject swaggerDocObject,
      String swaggerVersion,
      String endpointURL,
      List<JsonObject> resourceObjects,
      String swaggerPath,
      String documentVersion)
      throws RegistryException {

    if (swaggerDocObject == null || swaggerVersion == null) {
      throw new IllegalArgumentException(
          "Arguments are invalid. cannot create the REST service artifact. ");
    }

    OMElement data = factory.createOMElement(CommonConstants.SERVICE_ELEMENT_ROOT, namespace);
    OMElement overview = factory.createOMElement(OVERVIEW, namespace);
    OMElement provider = factory.createOMElement(PROVIDER, namespace);
    OMElement name = factory.createOMElement(NAME, namespace);
    OMElement context = factory.createOMElement(CONTEXT, namespace);
    OMElement apiVersion = factory.createOMElement(VERSION, namespace);
    OMElement endpoint = factory.createOMElement(ENDPOINT_URL, namespace);
    OMElement transports = factory.createOMElement(TRANSPORTS, namespace);
    OMElement description = factory.createOMElement(DESCRIPTION, namespace);
    List<OMElement> uriTemplates = null;

    JsonObject infoObject = swaggerDocObject.get(SwaggerConstants.INFO).getAsJsonObject();
    // get api name.
    String apiName = getChildElementText(infoObject, SwaggerConstants.TITLE).replaceAll("\\s", "");
    name.setText(apiName);
    context.setText("/" + apiName);
    // get api description.
    description.setText(getChildElementText(infoObject, SwaggerConstants.DESCRIPTION));
    // get api provider. (Current logged in user) : Alternative - CurrentSession.getUser();
    provider.setText(CarbonContext.getThreadLocalCarbonContext().getUsername());
    endpoint.setText(endpointURL);

    if (SwaggerConstants.SWAGGER_VERSION_2.equals(swaggerVersion)) {
      apiVersion.setText(documentVersion);
      transports.setText(getChildElementText(swaggerDocObject, SwaggerConstants.SCHEMES));
      uriTemplates = createURITemplateFromSwagger2(swaggerDocObject);
    } else if (SwaggerConstants.SWAGGER_VERSION_12.equals(swaggerVersion)) {
      apiVersion.setText(documentVersion);
      uriTemplates = createURITemplateFromSwagger12(resourceObjects);
    }

    overview.addChild(provider);
    overview.addChild(name);
    overview.addChild(context);
    overview.addChild(apiVersion);
    overview.addChild(description);
    overview.addChild(endpoint);
    data.addChild(overview);

    OMElement interfaceElement = factory.createOMElement(INTERFACE, namespace);
    OMElement swagger = factory.createOMElement(SWAGGER, namespace);
    swagger.setText(swaggerPath);
    interfaceElement.addChild(swagger);
    interfaceElement.addChild(transports);
    data.addChild(interfaceElement);
    if (uriTemplates != null) {
      for (OMElement uriTemplate : uriTemplates) {
        data.addChild(uriTemplate);
      }
    }

    return data;
  }

  /**
   * Extracts the data from wadl and creates an REST Service registry artifact.
   *
   * @param wadlElement wadl content.
   * @param wadlName wadl name.
   * @param version wadl version.
   * @param wadlPath wadl path.
   * @return REST Service element.
   */
  public static OMElement createRestServiceArtifact(
      OMElement wadlElement, String wadlName, String version, String wadlPath) {
    if (wadlElement == null) {
      throw new IllegalArgumentException("WADL content cannot be null.");
    }
    OMElement data = factory.createOMElement(CommonConstants.SERVICE_ELEMENT_ROOT, namespace);
    OMElement overview = factory.createOMElement(OVERVIEW, namespace);
    OMElement provider = factory.createOMElement(PROVIDER, namespace);
    OMElement name = factory.createOMElement(NAME, namespace);
    OMElement context = factory.createOMElement(CONTEXT, namespace);
    OMElement apiVersion = factory.createOMElement(VERSION, namespace);
    OMElement endpoint = factory.createOMElement(ENDPOINT_URL, namespace);
    OMElement transports = factory.createOMElement(TRANSPORTS, namespace);

    List<OMElement> uriTemplates = null;

    provider.setText(CarbonContext.getThreadLocalCarbonContext().getUsername());
    String serviceName =
        wadlName.contains(".") ? wadlName.substring(0, wadlName.lastIndexOf(".")) : wadlName;
    name.setText(serviceName);
    context.setText("/" + serviceName);
    apiVersion.setText(version);

    OMNamespace wadlNamespace = wadlElement.getNamespace();
    String wadlNamespaceURI = wadlNamespace.getNamespaceURI();
    String wadlNamespacePrefix = wadlNamespace.getPrefix();
    OMElement resourcesElement =
        wadlElement.getFirstChildWithName(
            new QName(wadlNamespaceURI, "resources", wadlNamespacePrefix));
    if (resourcesElement != null) {
      String endpointUrl = resourcesElement.getAttributeValue(new QName("base"));
      endpoint.setText(endpointUrl);
      if (endpointUrl != null) {
        transports.setText(endpointUrl.substring(0, endpointUrl.indexOf("://")));
      }
      uriTemplates = createURITemplateFromWADL(resourcesElement);
    } else {
      log.warn("WADL does not contains any resource paths. ");
    }

    overview.addChild(provider);
    overview.addChild(name);
    overview.addChild(context);
    overview.addChild(apiVersion);

    overview.addChild(endpoint);
    data.addChild(overview);

    OMElement interfaceElement = factory.createOMElement(INTERFACE, namespace);
    OMElement wadl = factory.createOMElement(WADL, namespace);
    wadl.setText(wadlPath);
    interfaceElement.addChild(wadl);
    interfaceElement.addChild(transports);
    data.addChild(interfaceElement);
    if (uriTemplates != null) {
      for (OMElement uriTemplate : uriTemplates) {
        data.addChild(uriTemplate);
      }
    }

    return data;
  }

  /**
   * Saves the REST Service registry artifact created from the imported swagger definition.
   *
   * @param requestContext information about current request.
   * @param data service artifact metadata.
   * @throws RegistryException If a failure occurs when adding the api to registry.
   */
  public static String addServiceToRegistry(RequestContext requestContext, OMElement data)
      throws RegistryException {

    if (requestContext == null || data == null) {
      throw new IllegalArgumentException(
          "Some or all of the arguments may be null. Cannot add the rest service to registry. ");
    }

    Registry registry = requestContext.getRegistry();
    // Creating new resource.
    Resource serviceResource = new ResourceImpl();
    // setting API media type.
    serviceResource.setMediaType(CommonConstants.REST_SERVICE_MEDIA_TYPE);
    serviceResource.setProperty(CommonConstants.SOURCE_PROPERTY, CommonConstants.SOURCE_AUTO);

    OMElement overview =
        data.getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, OVERVIEW));
    String serviceVersion =
        overview
            .getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, VERSION))
            .getText();
    String apiName =
        overview
            .getFirstChildWithName(new QName(CommonConstants.SERVICE_ELEMENT_NAMESPACE, NAME))
            .getText();
    serviceVersion =
        (serviceVersion == null) ? CommonConstants.SERVICE_VERSION_DEFAULT_VALUE : serviceVersion;

    String serviceProvider = CarbonContext.getThreadLocalCarbonContext().getUsername();

    String pathExpression = getRestServicePath(requestContext, data, apiName, serviceProvider);

    // set version property.
    serviceResource.setProperty(RegistryConstants.VERSION_PARAMETER_NAME, serviceVersion);
    // copy other property
    serviceResource.setProperties(copyProperties(requestContext));
    // set content.
    serviceResource.setContent(RegistryUtils.encodeString(data.toString()));

    String resourceId = serviceResource.getUUID();
    // set resource UUID
    resourceId = (resourceId == null) ? UUID.randomUUID().toString() : resourceId;

    serviceResource.setUUID(resourceId);
    String servicePath =
        getChrootedServiceLocation(requestContext.getRegistryContext())
            + CarbonContext.getThreadLocalCarbonContext().getUsername()
            + RegistryConstants.PATH_SEPARATOR
            + apiName
            + RegistryConstants.PATH_SEPARATOR
            + serviceVersion
            + RegistryConstants.PATH_SEPARATOR
            + apiName
            + "-rest_service";
    // saving the api resource to repository.

    registry.put(pathExpression, serviceResource);

    String defaultLifeCycle = CommonUtil.getDefaultLifecycle(registry, "restservice");
    if (defaultLifeCycle != null && !defaultLifeCycle.isEmpty()) {
      registry.associateAspect(serviceResource.getId(), defaultLifeCycle);
    }

    if (log.isDebugEnabled()) {
      log.debug("REST Service created at " + pathExpression);
    }
    return pathExpression;
  }

  /**
   * Generate REST service path
   *
   * @param requestContext Request Context
   * @param data REST Service content(OMElement)
   * @param serviceName REST Service name
   * @param serviceProvider Service Provider(current user)
   * @return Populated Path
   */
  private static String getRestServicePath(
      RequestContext requestContext, OMElement data, String serviceName, String serviceProvider) {
    String pathExpression =
        Utils.getRxtService().getStoragePath(CommonConstants.REST_SERVICE_MEDIA_TYPE);
    pathExpression = CommonUtil.replaceExpressionOfPath(pathExpression, "name", serviceName);
    pathExpression =
        RegistryUtils.getAbsolutePath(
            requestContext.getRegistryContext(),
            CommonUtil.getPathFromPathExpression(
                pathExpression, data, requestContext.getResource().getProperties()));
    pathExpression =
        CommonUtil.getPathFromPathExpression(
            pathExpression, requestContext.getResource().getProperties(), null);
    pathExpression =
        RegistryUtils.getAbsolutePath(
            requestContext.getRegistryContext(),
            CommonUtil.replaceExpressionOfPath(pathExpression, "provider", serviceProvider));
    return CommonUtil.getRegistryPath(
        requestContext.getRegistry().getRegistryContext(), pathExpression);
  }

  /**
   * Adds the service endpoint element to the registry.
   *
   * @param requestContext current request information.
   * @param endpointElement endpoint metadata element.
   * @param endpointPath endpoint location.
   * @return The resource path of the endpoint.
   * @throws RegistryException If fails to add the endpoint to the registry.
   */
  public static String addEndpointToRegistry(
      RequestContext requestContext, OMElement endpointElement, String endpointPath)
      throws RegistryException {

    if (requestContext == null || endpointElement == null || endpointPath == null) {
      throw new IllegalArgumentException(
          "Some or all of the arguments may be null. Cannot add the endpoint to registry. ");
    }

    endpointPath = getEndpointPath(requestContext, endpointElement, endpointPath);

    Registry registry = requestContext.getRegistry();
    // Creating new resource.
    Resource endpointResource = new ResourceImpl();
    // setting endpoint media type.
    endpointResource.setMediaType(CommonConstants.ENDPOINT_MEDIA_TYPE);
    // set content.
    endpointResource.setContent(RegistryUtils.encodeString(endpointElement.toString()));
    // copy other property
    endpointResource.setProperties(copyProperties(requestContext));
    // set path
    // endpointPath = getChrootedEndpointLocation(requestContext.getRegistryContext()) +
    // endpointPath;

    String resourceId = endpointResource.getUUID();
    // set resource UUID
    resourceId = (resourceId == null) ? UUID.randomUUID().toString() : resourceId;

    endpointResource.setUUID(resourceId);
    // saving the api resource to repository.
    registry.put(endpointPath, endpointResource);
    if (log.isDebugEnabled()) {
      log.debug("Endpoint created at " + endpointPath);
    }
    return endpointPath;
  }

  /**
   * This method used to generate endpoint path
   *
   * @param requestContext Request Context
   * @param endpointElement Endpoint XML element
   * @param endpointPath Current endpoint path
   * @return Updated endpoint path;
   */
  private static String getEndpointPath(
      RequestContext requestContext, OMElement endpointElement, String endpointPath) {
    String pathExpression =
        Utils.getRxtService().getStoragePath(CommonConstants.ENDPOINT_MEDIA_TYPE);
    pathExpression =
        CommonUtil.getPathFromPathExpression(
            pathExpression, endpointElement, requestContext.getResource().getProperties());
    endpointPath = CommonUtil.replaceExpressionOfPath(pathExpression, "name", endpointPath);

    return CommonUtil.getRegistryPath(
        requestContext.getRegistry().getRegistryContext(), endpointPath);
  }

  /**
   * Returns a Json element as a string
   *
   * @param object json Object
   * @param key element key
   * @return Element value
   */
  private static String getChildElementText(JsonObject object, String key) {
    JsonElement element = object.get(key);
    if (element != null && element.isJsonArray()) {
      if (((JsonArray) element).size() == 1) {
        return object.get(key).getAsString();
      } else {
        StringBuffer sb = new StringBuffer();
        JsonArray elements = (JsonArray) object.get(key);
        for (int i = 0; i < elements.size(); i++) {
          JsonPrimitive ob = (JsonPrimitive) elements.get(i);
          sb.append(ob.getAsString());
          if (i < elements.size() - 1) {
            sb.append(",");
          }
        }
        return sb.toString();
      }
    } else if (element != null && (element.isJsonObject() || element.isJsonPrimitive())) {
      return object.get(key).getAsString();
    }
    return null;
  }

  /**
   * Contains the logic to create URITemplate XML Element from the swagger 1.2 resource.
   *
   * @param resourceObjects the path resource documents.
   * @return URITemplate element.
   */
  private static List<OMElement> createURITemplateFromSwagger12(List<JsonObject> resourceObjects) {

    List<OMElement> uriTemplates = new ArrayList<>();

    for (JsonObject resourceObject : resourceObjects) {
      JsonArray pathResources = resourceObject.getAsJsonArray(SwaggerConstants.APIS);

      // Iterating through the Paths
      for (JsonElement pathResource : pathResources) {
        JsonObject path = pathResource.getAsJsonObject();
        String pathText = path.get(SwaggerConstants.PATH).getAsString();
        JsonArray methods = path.getAsJsonArray(SwaggerConstants.OPERATIONS);

        // Iterating through HTTP methods (Actions)
        for (JsonElement method : methods) {
          JsonObject methodObj = method.getAsJsonObject();

          OMElement uriTemplateElement = factory.createOMElement(URI_TEMPLATE, namespace);
          OMElement urlPatternElement = factory.createOMElement(URL_PATTERN, namespace);
          OMElement httpVerbElement = factory.createOMElement(HTTP_VERB, namespace);
          OMElement authTypeElement = factory.createOMElement(AUTH_TYPE, namespace);

          urlPatternElement.setText(pathText);
          httpVerbElement.setText(methodObj.get(SwaggerConstants.METHOD).getAsString());

          // Adding urlPattern element to URITemplate element.
          uriTemplateElement.addChild(urlPatternElement);
          uriTemplateElement.addChild(httpVerbElement);
          uriTemplateElement.addChild(authTypeElement);
          uriTemplates.add(uriTemplateElement);
        }
      }
    }

    return uriTemplates;
  }

  /**
   * Contains the logic to create URITemplate XML Element from the swagger 2.0 resource.
   *
   * @param swaggerDocObject swagger document
   * @return URITemplate element.
   */
  private static List<OMElement> createURITemplateFromSwagger2(JsonObject swaggerDocObject) {

    List<OMElement> uriTemplates = new ArrayList<>();

    JsonObject paths = swaggerDocObject.get(SwaggerConstants.PATHS).getAsJsonObject();
    Set<Map.Entry<String, JsonElement>> pathSet = paths.entrySet();

    for (Map.Entry path : pathSet) {
      JsonObject urlPattern = ((JsonElement) path.getValue()).getAsJsonObject();
      String pathText = path.getKey().toString();
      Set<Map.Entry<String, JsonElement>> operationSet = urlPattern.entrySet();

      for (Map.Entry operationEntry : operationSet) {
        OMElement uriTemplateElement = factory.createOMElement(URI_TEMPLATE, namespace);
        OMElement urlPatternElement = factory.createOMElement(URL_PATTERN, namespace);
        OMElement httpVerbElement = factory.createOMElement(HTTP_VERB, namespace);
        OMElement authTypeElement = factory.createOMElement(AUTH_TYPE, namespace);

        urlPatternElement.setText(pathText);
        httpVerbElement.setText(operationEntry.getKey().toString());

        uriTemplateElement.addChild(urlPatternElement);
        uriTemplateElement.addChild(httpVerbElement);
        uriTemplateElement.addChild(authTypeElement);
        uriTemplates.add(uriTemplateElement);
      }
    }
    return uriTemplates;
  }

  /**
   * Contains the logic to create URITemplate XML Element from wadl resource.
   *
   * @param resourcesElement wadl document
   * @return URITemplate element.
   */
  private static List<OMElement> createURITemplateFromWADL(OMElement resourcesElement) {
    List<OMElement> uriTemplates = new ArrayList<>();

    Iterator resources = resourcesElement.getChildrenWithLocalName(RESOURCE);
    while (resources.hasNext()) {
      OMElement resource = (OMElement) resources.next();
      String path = resource.getAttributeValue(new QName(PATH));
      path = path.endsWith(PATH_SEPERATOR) ? path : path + PATH_SEPERATOR;
      Iterator methods = resource.getChildrenWithLocalName(METHOD);
      uriTemplates.addAll(getUriTemplateElementFromMethods(path, methods));
      Iterator subResources = resource.getChildrenWithLocalName(RESOURCE);
      while (subResources.hasNext()) {
        OMElement subResource = (OMElement) subResources.next();
        String subPath = subResource.getAttributeValue(new QName(PATH));
        subPath = subPath.startsWith(PATH_SEPERATOR) ? subPath.substring(1) : subPath;
        Iterator subMethods = resource.getChildrenWithLocalName(METHOD);
        uriTemplates.addAll(getUriTemplateElementFromMethods(subPath, subMethods));
      }
    }
    return uriTemplates;
  }

  /**
   * Creates uri template elements for HTTP action verbs.
   *
   * @param resourcePath resource path.
   * @param methods http verbs.
   * @return Uri template element list.
   */
  private static List<OMElement> getUriTemplateElementFromMethods(
      String resourcePath, Iterator methods) {
    List<OMElement> uriTemplates = new ArrayList<>();
    while (methods.hasNext()) {
      OMElement method = (OMElement) methods.next();
      String httpVerb = method.getAttributeValue(new QName(NAME));
      OMElement uriTemplateElement = factory.createOMElement(URI_TEMPLATE, namespace);
      OMElement urlPatternElement = factory.createOMElement(URL_PATTERN, namespace);
      OMElement httpVerbElement = factory.createOMElement(HTTP_VERB, namespace);
      OMElement authTypeElement = factory.createOMElement(AUTH_TYPE, namespace);

      urlPatternElement.setText(resourcePath);
      httpVerbElement.setText(httpVerb);
      uriTemplateElement.addChild(urlPatternElement);
      uriTemplateElement.addChild(httpVerbElement);
      uriTemplateElement.addChild(authTypeElement);

      uriTemplates.add(uriTemplateElement);
    }
    return uriTemplates;
  }

  /**
   * Returns the root location of the API.
   *
   * @param registryContext registry context
   * @return The root location of the API artifact.
   */
  private static String getChrootedServiceLocation(RegistryContext registryContext) {
    return RegistryUtils.getAbsolutePath(
        registryContext,
        RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + commonRestServiceLocation);
  }

  /**
   * Returns the root location of the endpoint.
   *
   * @param registryContext registry context
   * @return The root location of the Endpoint artifact.
   */
  private static String getChrootedEndpointLocation(RegistryContext registryContext) {
    return RegistryUtils.getAbsolutePath(
        registryContext, RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + commonEndpointLocation);
  }

  /**
   * Set the restServiceLocation.
   *
   * @param restServiceLocation the restServiceLocation
   */
  public static void setCommonRestServiceLocation(String restServiceLocation) {
    RESTServiceUtils.commonRestServiceLocation = restServiceLocation;
  }

  /**
   * Set the endpointLocation.
   *
   * @param endpointLocation the endpointLocation
   */
  public static void setCommonEndpointLocation(String endpointLocation) {
    RESTServiceUtils.commonEndpointLocation = endpointLocation;
  }

  /**
   * This method used to extract properties from request context
   *
   * @param requestContext Request Context
   * @return Extracted Properties
   */
  private static Properties copyProperties(RequestContext requestContext) {
    Properties properties = requestContext.getResource().getProperties();
    Properties copiedProperties = new Properties();
    if (properties != null) {
      List<String> linkProperties =
          Arrays.asList(
              RegistryConstants.REGISTRY_LINK,
              RegistryConstants.REGISTRY_USER,
              RegistryConstants.REGISTRY_MOUNT,
              RegistryConstants.REGISTRY_AUTHOR,
              RegistryConstants.REGISTRY_MOUNT_POINT,
              RegistryConstants.REGISTRY_TARGET_POINT,
              RegistryConstants.REGISTRY_ACTUAL_PATH,
              RegistryConstants.REGISTRY_REAL_PATH);
      for (Map.Entry<Object, Object> e : properties.entrySet()) {
        String key = (String) e.getKey();
        if (!linkProperties.contains(key)
            && !(key.startsWith("resource") || key.startsWith("registry"))) {
          copiedProperties.put(key, (List<String>) e.getValue());
        }
      }
    }
    return copiedProperties;
  }
}