/**
   * Invokes the bussiness logic invocation on the service implementation class
   *
   * @param msgContext the incoming message context
   * @param newmsgContext the response message context
   * @throws AxisFault on invalid method (wrong signature) or behaviour (return null)
   */
  public void invokeBusinessLogic(MessageContext msgContext, MessageContext newmsgContext)
      throws AxisFault {
    try {

      // get the implementation class for the Web Service
      Object obj = getTheImplementationObject(msgContext);

      // find the WebService method
      Class implClass = obj.getClass();

      AxisOperation opDesc = msgContext.getAxisOperation();
      Method method = findOperation(opDesc, implClass);

      if (method == null) {
        throw new AxisFault(
            Messages.getMessage("methodDoesNotExistInOut", opDesc.getName().toString()));
      }

      OMElement result =
          (OMElement)
              method.invoke(
                  obj, new Object[] {msgContext.getEnvelope().getBody().getFirstElement()});
      SOAPFactory fac = getSOAPFactory(msgContext);
      SOAPEnvelope envelope = fac.getDefaultEnvelope();

      if (result != null) {
        envelope.getBody().addChild(result);
      }

      newmsgContext.setEnvelope(envelope);
    } catch (Exception e) {
      throw AxisFault.makeFault(e);
    }
  }
Exemplo n.º 2
0
  public static String sendSOAP(
      EndpointReference soapEPR, String requestString, String action, String operation)
      throws Exception {

    ServiceClient sender = PmServiceClient.getServiceClient();
    OperationClient operationClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    // creating message context
    MessageContext outMsgCtx = new MessageContext();
    // assigning message context's option object into instance variable
    Options opts = outMsgCtx.getOptions();
    // setting properties into option
    log.debug(soapEPR);
    opts.setTo(soapEPR);
    opts.setAction(action);
    opts.setTimeOutInMilliSeconds(180000);

    log.debug(requestString);

    SOAPEnvelope envelope = null;

    try {
      SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
      envelope = fac.getDefaultEnvelope();
      OMNamespace omNs =
          fac.createOMNamespace(
              "http://rpdr.partners.org/", //$NON-NLS-1$
              "rpdr"); //$NON-NLS-1$

      // creating the SOAP payload
      OMElement method = fac.createOMElement(operation, omNs);
      OMElement value = fac.createOMElement("RequestXmlString", omNs); // $NON-NLS-1$
      value.setText(requestString);
      method.addChild(value);
      envelope.getBody().addChild(method);
    } catch (FactoryConfigurationError e) {
      log.error(e.getMessage());
      throw new Exception(e);
    }

    outMsgCtx.setEnvelope(envelope);

    operationClient.addMessageContext(outMsgCtx);
    operationClient.execute(true);

    MessageContext inMsgtCtx = operationClient.getMessageContext("In"); // $NON-NLS-1$
    SOAPEnvelope responseEnv = inMsgtCtx.getEnvelope();

    OMElement soapResponse = responseEnv.getBody().getFirstElement();
    //		System.out.println("Sresponse: "+ soapResponse.toString());
    OMElement soapResult = soapResponse.getFirstElement();
    //		System.out.println("Sresult: "+ soapResult.toString());

    String i2b2Response = soapResult.getText();
    log.debug(i2b2Response);

    return i2b2Response;
  }
Exemplo n.º 3
0
  public static MessageContext sendUsingSwA(String fileName, String targetEPR) throws IOException {

    Options options = new Options();
    options.setTo(new EndpointReference(targetEPR));
    options.setAction("urn:uploadFileUsingSwA");
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);

    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();

    System.out.println("Sending file : " + fileName + " as SwA");
    FileDataSource fileDataSource = new FileDataSource(new File(fileName));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);

    SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = factory.getDefaultEnvelope();
    OMNamespace ns = factory.createOMNamespace("http://services.samples/xsd", "m0");
    OMElement payload = factory.createOMElement("uploadFileUsingSwA", ns);
    OMElement request = factory.createOMElement("request", ns);
    OMElement imageId = factory.createOMElement("imageId", ns);
    imageId.setText(attachmentID);
    request.addChild(imageId);
    payload.addChild(request);
    env.getBody().addChild(payload);
    mc.setEnvelope(env);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);

    SOAPBody body = response.getEnvelope().getBody();
    String imageContentId =
        body.getFirstChildWithName(
                new QName("http://services.samples/xsd", "uploadFileUsingSwAResponse"))
            .getFirstChildWithName(new QName("http://services.samples/xsd", "response"))
            .getFirstChildWithName(new QName("http://services.samples/xsd", "imageId"))
            .getText();

    Attachments attachment = response.getAttachmentMap();
    dataHandler = attachment.getDataHandler(imageContentId);
    File tempFile = File.createTempFile("swa-", ".gif");
    FileOutputStream fos = new FileOutputStream(tempFile);
    dataHandler.writeTo(fos);
    fos.flush();
    fos.close();

    System.out.println("Saved response to file : " + tempFile.getAbsolutePath());

    return response;
  }
Exemplo n.º 4
0
  public static void transferFile(File file, String destinationFile) throws Exception {

    Options options = new Options();
    options.setTo(targetEPR);
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // Increase the time out when sending large attachments
    options.setTimeOutInMilliSeconds(10000);
    options.setTo(targetEPR);
    options.setAction("urn:uploadFile");

    // assume the use runs this sample at
    // <axis2home>/samples/soapwithattachments/ dir
    ConfigurationContext configContext =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            "../../repository", null);

    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);

    MessageContext mc = new MessageContext();
    FileDataSource fileDataSource = new FileDataSource(file);

    // Create a dataHandler using the fileDataSource. Any implementation of
    // javax.activation.DataSource interface can fit here.
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);

    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa");
    OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(destinationFile);
    OMElement idEle = fac.createOMElement("attchmentID", omNs);
    idEle.setText(attachmentID);
    uploadFile.addChild(nameEle);
    uploadFile.addChild(idEle);
    env.getBody().addChild(uploadFile);
    mc.setEnvelope(env);

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element =
        body.getFirstElement()
            .getFirstChildWithName(
                new QName("http://service.soapwithattachments.sample", "return"));
    System.out.println(element.getText());
  }
  private static MessageContext cloneForSend(MessageContext ori, String preserveAddressing)
      throws AxisFault {

    MessageContext newMC = MessageHelper.clonePartially(ori);

    newMC.setEnvelope(ori.getEnvelope());
    if (preserveAddressing != null && Boolean.parseBoolean(preserveAddressing)) {
      newMC.setMessageID(ori.getMessageID());
    } else {
      MessageHelper.removeAddressingHeaders(newMC);
    }

    newMC.setProperty(
        org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS,
        ori.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS));

    return newMC;
  }
  /** Auto generated method signature */
  public void setEmp(com.pa.SetEmp setEmp3) throws java.rmi.RemoteException {

    org.apache.axis2.context.MessageContext _messageContext = null;

    org.apache.axis2.client.OperationClient _operationClient =
        _serviceClient.createClient(_operations[0].getName());
    _operationClient.getOptions().setAction("urn:setEmp");
    _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

    addPropertyToOperationClient(
        _operationClient,
        org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
        "&");

    org.apache.axiom.soap.SOAPEnvelope env = null;
    _messageContext = new org.apache.axis2.context.MessageContext();

    // Style is Doc.

    env =
        toEnvelope(
            getFactory(_operationClient.getOptions().getSoapVersionURI()),
            setEmp3,
            optimizeContent(new javax.xml.namespace.QName("http://pa.com", "setEmp")),
            new javax.xml.namespace.QName("http://pa.com", "setEmp"));

    // adding SOAP soap_headers
    _serviceClient.addHeadersToEnvelope(env);
    // create message context with that soap envelope

    _messageContext.setEnvelope(env);

    // add the message contxt to the operation client
    _operationClient.addMessageContext(_messageContext);

    _operationClient.execute(true);

    if (_messageContext.getTransportOut() != null) {
      _messageContext.getTransportOut().getSender().cleanup(_messageContext);
    }

    return;
  }
  public static org.apache.axis2.context.MessageContext attachMessage(
      SOAPEnvelope envelope, org.apache.axis2.context.MessageContext axis2Ctx) {
    if (envelope == null) {
      log.error("Cannot attach null SOAP Envelope.");
      return null;
    }

    AxisConfiguration axisConfig = axis2Ctx.getConfigurationContext().getAxisConfiguration();
    if (axisConfig == null) {
      log.warn("Cannot create AxisConfiguration. AxisConfiguration is null.");
      return null;
    }

    try {
      axis2Ctx.setEnvelope(envelope);
      return axis2Ctx;
    } catch (Exception e) {
      log.error("Cannot attach SOAPEnvelope to Message Context. Error:" + e.getMessage(), e);
      return null;
    }
  }
  public void createSoapRequest(MessageContext msgCtx, Element message, Operation op)
      throws AxisFault {
    if (op == null) {
      throw new NullPointerException("Null operation");
    }
    // The message can be null if the input message has no part
    if (op.getInput().getMessage().getParts().size() > 0 && message == null) {
      throw new NullPointerException("Null message.");
    }
    if (msgCtx == null) {
      throw new NullPointerException("Null msgCtx");
    }

    BindingOperation bop = binding.getBindingOperation(op.getName(), null, null);

    if (bop == null) {
      throw new OdeFault("BindingOperation not found.");
    }

    BindingInput bi = bop.getBindingInput();
    if (bi == null) {
      throw new OdeFault("BindingInput not found.");
    }

    SOAPEnvelope soapEnv = msgCtx.getEnvelope();
    if (soapEnv == null) {
      soapEnv = soapFactory.getDefaultEnvelope();
      msgCtx.setEnvelope(soapEnv);
    }

    //        createSoapHeaders(soapEnv, getSOAPHeaders(bi), op.getInput().getMessage(), message);

    SOAPBody soapBody = getSOAPBody(bi);
    if (soapBody != null) {
      org.apache.axiom.soap.SOAPBody sb =
          soapEnv.getBody() == null ? soapFactory.createSOAPBody(soapEnv) : soapEnv.getBody();
      createSoapBody(sb, soapBody, op.getInput().getMessage(), message, op.getName());
    }
  }
  public static org.apache.axis2.context.MessageContext attachMessage(
      String jsonMessage, org.apache.axis2.context.MessageContext axis2Ctx) {
    if (jsonMessage == null) {
      log.error("Cannot attach null JSON string.");
      return null;
    }

    AxisConfiguration axisConfig = axis2Ctx.getConfigurationContext().getAxisConfiguration();
    if (axisConfig == null) {
      log.warn("Cannot create AxisConfiguration. AxisConfiguration is null.");
      return null;
    }

    try {
      SOAPFactory soapFactory = new SOAP12Factory();
      SOAPEnvelope envelope = soapFactory.createSOAPEnvelope();
      envelope.addChild(JsonUtil.newJsonPayload(axis2Ctx, jsonMessage, true, true));
      axis2Ctx.setEnvelope(envelope);
      return axis2Ctx;
    } catch (Exception e) {
      log.error("Cannot attach message to Message Context. Error: " + e.getMessage(), e);
      return null;
    }
  }
Exemplo n.º 10
0
  public static void testConnect(
      String strOperation, String strParamName, AbstractConnector connector) throws AxisFault {

    org.apache.axis2.context.MessageContext axis2Ctx =
        new org.apache.axis2.context.MessageContext();
    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    org.apache.axiom.soap.SOAPEnvelope envelope = fac.getDefaultEnvelope();
    axis2Ctx.setEnvelope(envelope);
    Collection<String> collection = new java.util.ArrayList<String>();
    collection.add(strParamName);
    testCtx.setProperty(
        TEST_TEMPLATE + ":" + strParamName,
        new Value(
            "<sfdc:sObjects xmlns:sfdc='sfdc' type='Account'><sfdc:sObject><sfdc:Name>name01</sfdc:Name></sfdc:sObject></sfdc:sObjects>"));
    TemplateContext context = new TemplateContext(TEST_TEMPLATE, collection);
    Stack<TemplateContext> stack = new Stack<TemplateContext>();
    stack.add(context);
    context.setupParams(testCtx);

    testCtx.setProperty(SynapseConstants.SYNAPSE__FUNCTION__STACK, stack);
    try {
      connector.connect(testCtx);
    } catch (Exception e) {
      assertTrue(false);
    }

    Iterator<OMElement> iIteratorElements =
        testCtx.getEnvelope().getBody().getChildrenWithLocalName(strOperation);
    OMElement element = iIteratorElements.next();
    iIteratorElements = element.getChildren();
    if (iIteratorElements.hasNext()) {
      assertTrue(true);
    } else {
      assertTrue(false);
    }
  }
    private void send(MessageContext msgctx) throws AxisFault {

      // create the responseMessageContext and set that its related to the current outgoing
      // message, so that it could be tied back to the original request even if the response
      // envelope does not contain addressing headers
      MessageContext responseMessageContext = new MessageContext();
      responseMessageContext.setMessageID(msgctx.getMessageID());
      responseMessageContext.setProperty(
          SynapseConstants.RELATES_TO_FOR_POX, msgctx.getMessageID());
      responseMessageContext.setOptions(options);
      responseMessageContext.setServerSide(true);
      addMessageContext(responseMessageContext);
      responseMessageContext.setProperty("synapse.send", "true");

      AxisEngine.send(msgctx);

      // did the engine receive a immediate synchronous response?
      // e.g. sometimes the transport sender may listen for a syncronous reply
      if (msgctx.getProperty(MessageContext.TRANSPORT_IN) != null) {

        responseMessageContext.setOperationContext(msgctx.getOperationContext());
        responseMessageContext.setAxisMessage(
            msgctx
                .getOperationContext()
                .getAxisOperation()
                .getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
        responseMessageContext.setAxisService(msgctx.getAxisService());

        responseMessageContext.setProperty(
            MessageContext.TRANSPORT_OUT, msgctx.getProperty(MessageContext.TRANSPORT_OUT));
        responseMessageContext.setProperty(
            org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
            msgctx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));

        responseMessageContext.setProperty(
            org.apache.synapse.SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
        responseMessageContext.setTransportIn(msgctx.getTransportIn());
        responseMessageContext.setTransportOut(msgctx.getTransportOut());

        // If request is REST assume that the responseMessageContext is REST too
        responseMessageContext.setDoingREST(msgctx.isDoingREST());

        responseMessageContext.setProperty(
            MessageContext.TRANSPORT_IN, msgctx.getProperty(MessageContext.TRANSPORT_IN));
        responseMessageContext.setTransportIn(msgctx.getTransportIn());
        responseMessageContext.setTransportOut(msgctx.getTransportOut());

        // Options object reused above so soapAction needs to be removed so
        // that soapAction+wsa:Action on response don't conflict
        responseMessageContext.setSoapAction("");

        if (responseMessageContext.getEnvelope() == null) {
          // If request is REST we assume the responseMessageContext is
          // REST, so set the variable

          Options options = responseMessageContext.getOptions();
          if (options != null) {
            RelatesTo relatesTo = options.getRelatesTo();
            if (relatesTo != null) {
              relatesTo.setValue(msgctx.getMessageID());
            } else {
              options.addRelatesTo(new RelatesTo(msgctx.getMessageID()));
            }
          }

          SOAPEnvelope resenvelope = TransportUtils.createSOAPMessage(responseMessageContext);

          if (resenvelope != null) {
            responseMessageContext.setEnvelope(resenvelope);
            AxisEngine.receive(responseMessageContext);
            if (responseMessageContext.getReplyTo() != null) {
              sc.setTargetEPR(responseMessageContext.getReplyTo());
            }

            complete(msgctx);
          } else {
            throw new AxisFault(Messages.getMessage("blockingInvocationExpectsResponse"));
          }
        }
      }
    }
Exemplo n.º 12
0
  public void invokeBusinessLogic(
      org.apache.axis2.context.MessageContext msgContext,
      org.apache.axis2.context.MessageContext newMsgContext)
      throws org.apache.axis2.AxisFault {

    try {

      // get the implementation class for the Web Service
      Object obj = getTheImplementationObject(msgContext);

      SiteSkeletonInterface skel = (SiteSkeletonInterface) obj;
      // Out Envelop
      org.apache.axiom.soap.SOAPEnvelope envelope = null;
      // Find the axisOperation that has been set by the Dispatch phase.
      org.apache.axis2.description.AxisOperation op =
          msgContext.getOperationContext().getAxisOperation();
      if (op == null) {
        throw new org.apache.axis2.AxisFault(
            "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider");
      }

      java.lang.String methodName;
      if ((op.getName() != null)
          && ((methodName =
                  org.apache.axis2.util.JavaUtils.xmlNameToJavaIdentifier(
                      op.getName().getLocalPart()))
              != null)) {

        if ("passInfo".equals(methodName)) {

          org.example.www.site.PassInfoResponse passInfoResponse9 = null;
          org.example.www.site.PassInfo wrappedParam =
              (org.example.www.site.PassInfo)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.PassInfo.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          passInfoResponse9 = skel.passInfo(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), passInfoResponse9, false);
        } else if ("searchSite".equals(methodName)) {

          org.example.www.site.SearchSiteResponse searchSiteResponse11 = null;
          org.example.www.site.SearchSite wrappedParam =
              (org.example.www.site.SearchSite)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.SearchSite.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          searchSiteResponse11 = skel.searchSite(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), searchSiteResponse11, false);
        } else if ("getSite".equals(methodName)) {

          org.example.www.site.GetSiteResponse getSiteResponse13 = null;
          org.example.www.site.GetSite wrappedParam =
              (org.example.www.site.GetSite)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.GetSite.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getSiteResponse13 = skel.getSite(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getSiteResponse13, false);
        } else if ("parallelInfo".equals(methodName)) {

          org.example.www.site.ParallelInfoResponse parallelInfoResponse15 = null;
          org.example.www.site.ParallelInfo wrappedParam =
              (org.example.www.site.ParallelInfo)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.example.www.site.ParallelInfo.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          parallelInfoResponse15 = skel.parallelInfo(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), parallelInfoResponse15, false);

        } else {
          throw new java.lang.RuntimeException("method not found");
        }

        newMsgContext.setEnvelope(envelope);
      }
    } catch (java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  public void invokeBusinessLogic(
      org.apache.axis2.context.MessageContext msgContext,
      org.apache.axis2.context.MessageContext newMsgContext)
      throws org.apache.axis2.AxisFault {

    try {

      // get the implementation class for the Web Service
      Object obj = getTheImplementationObject(msgContext);

      GSNWebServiceSkeleton skel = (GSNWebServiceSkeleton) obj;
      // Out Envelop
      org.apache.axiom.soap.SOAPEnvelope envelope = null;
      // Find the axisOperation that has been set by the Dispatch phase.
      org.apache.axis2.description.AxisOperation op =
          msgContext.getOperationContext().getAxisOperation();
      if (op == null) {
        throw new org.apache.axis2.AxisFault(
            "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider");
      }

      java.lang.String methodName;
      if ((op.getName() != null)
          && ((methodName =
                  org.apache.axis2.util.JavaUtils.xmlNameToJava(op.getName().getLocalPart()))
              != null)) {

        if ("getVirtualSensorsDetails".equals(methodName)) {

          gsn.webservice.standard.GetVirtualSensorsDetailsResponse
              getVirtualSensorsDetailsResponse1 = null;
          gsn.webservice.standard.GetVirtualSensorsDetails wrappedParam =
              (gsn.webservice.standard.GetVirtualSensorsDetails)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetVirtualSensorsDetails.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getVirtualSensorsDetailsResponse1 = skel.getVirtualSensorsDetails(wrappedParam);

          envelope =
              toEnvelope(getSOAPFactory(msgContext), getVirtualSensorsDetailsResponse1, false);
        } else if ("getNextData".equals(methodName)) {

          gsn.webservice.standard.GetNextDataResponse getNextDataResponse3 = null;
          gsn.webservice.standard.GetNextData wrappedParam =
              (gsn.webservice.standard.GetNextData)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetNextData.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getNextDataResponse3 = skel.getNextData(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getNextDataResponse3, false);
        } else if ("listWrapperURLs".equals(methodName)) {

          gsn.webservice.standard.ListWrapperURLsResponse listWrapperURLsResponse5 = null;
          gsn.webservice.standard.ListWrapperURLs wrappedParam =
              (gsn.webservice.standard.ListWrapperURLs)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.ListWrapperURLs.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          listWrapperURLsResponse5 = skel.listWrapperURLs(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), listWrapperURLsResponse5, false);
        } else if ("getLatestMultiData".equals(methodName)) {

          gsn.webservice.standard.GetLatestMultiDataResponse getLatestMultiDataResponse7 = null;
          gsn.webservice.standard.GetLatestMultiData wrappedParam =
              (gsn.webservice.standard.GetLatestMultiData)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetLatestMultiData.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getLatestMultiDataResponse7 = skel.getLatestMultiData(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getLatestMultiDataResponse7, false);
        } else if ("unregisterQuery".equals(methodName)) {

          gsn.webservice.standard.UnregisterQueryResponse unregisterQueryResponse9 = null;
          gsn.webservice.standard.UnregisterQuery wrappedParam =
              (gsn.webservice.standard.UnregisterQuery)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.UnregisterQuery.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          unregisterQueryResponse9 = skel.unregisterQuery(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), unregisterQueryResponse9, false);
        } else if ("createVirtualSensor".equals(methodName)) {

          gsn.webservice.standard.CreateVirtualSensorResponse createVirtualSensorResponse11 = null;
          gsn.webservice.standard.CreateVirtualSensor wrappedParam =
              (gsn.webservice.standard.CreateVirtualSensor)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.CreateVirtualSensor.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          createVirtualSensorResponse11 = skel.createVirtualSensor(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), createVirtualSensorResponse11, false);
        } else if ("getMultiData".equals(methodName)) {

          gsn.webservice.standard.GetMultiDataResponse getMultiDataResponse13 = null;
          gsn.webservice.standard.GetMultiData wrappedParam =
              (gsn.webservice.standard.GetMultiData)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetMultiData.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getMultiDataResponse13 = skel.getMultiData(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getMultiDataResponse13, false);
        } else if ("registerQuery".equals(methodName)) {

          gsn.webservice.standard.RegisterQueryResponse registerQueryResponse15 = null;
          gsn.webservice.standard.RegisterQuery wrappedParam =
              (gsn.webservice.standard.RegisterQuery)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.RegisterQuery.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          registerQueryResponse15 = skel.registerQuery(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), registerQueryResponse15, false);
        } else if ("getContainerInfo".equals(methodName)) {

          gsn.webservice.standard.GetContainerInfoResponse getContainerInfoResponse17 = null;
          gsn.webservice.standard.GetContainerInfo wrappedParam =
              (gsn.webservice.standard.GetContainerInfo)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.GetContainerInfo.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getContainerInfoResponse17 = skel.getContainerInfo(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), getContainerInfoResponse17, false);
        } else if ("listVirtualSensorNames".equals(methodName)) {

          gsn.webservice.standard.ListVirtualSensorNamesResponse listVirtualSensorNamesResponse19 =
              null;
          gsn.webservice.standard.ListVirtualSensorNames wrappedParam =
              (gsn.webservice.standard.ListVirtualSensorNames)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.ListVirtualSensorNames.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          listVirtualSensorNamesResponse19 = skel.listVirtualSensorNames(wrappedParam);

          envelope =
              toEnvelope(getSOAPFactory(msgContext), listVirtualSensorNamesResponse19, false);
        } else if ("deleteVirtualSensor".equals(methodName)) {

          gsn.webservice.standard.DeleteVirtualSensorResponse deleteVirtualSensorResponse21 = null;
          gsn.webservice.standard.DeleteVirtualSensor wrappedParam =
              (gsn.webservice.standard.DeleteVirtualSensor)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      gsn.webservice.standard.DeleteVirtualSensor.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          deleteVirtualSensorResponse21 = skel.deleteVirtualSensor(wrappedParam);

          envelope = toEnvelope(getSOAPFactory(msgContext), deleteVirtualSensorResponse21, false);

        } else {
          throw new java.lang.RuntimeException("method not found");
        }

        newMsgContext.setEnvelope(envelope);
      }
    } catch (java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  public void invokeBusinessLogic(
      org.apache.axis2.context.MessageContext msgContext,
      org.apache.axis2.context.MessageContext newMsgContext)
      throws org.apache.axis2.AxisFault {

    try {

      // get the implementation class for the Web Service
      Object obj = getTheImplementationObject(msgContext);

      MultitenancyBillingServiceSkeletonInterface skel =
          (MultitenancyBillingServiceSkeletonInterface) obj;
      // Out Envelop
      org.apache.axiom.soap.SOAPEnvelope envelope = null;
      // Find the axisOperation that has been set by the Dispatch phase.
      org.apache.axis2.description.AxisOperation op =
          msgContext.getOperationContext().getAxisOperation();
      if (op == null) {
        throw new org.apache.axis2.AxisFault(
            "Operation is not located, if this is doclit style the SOAP-ACTION should specified via the SOAP Action to use the RawXMLProvider");
      }

      java.lang.String methodName;
      if ((op.getName() != null)
          && ((methodName =
                  org.apache.axis2.util.JavaUtils.xmlNameToJavaIdentifier(
                      op.getName().getLocalPart()))
              != null)) {

        if ("getOutstandingBalance".equals(methodName)) {

          org.wso2.carbon.billing.mgt.services.GetOutstandingBalanceResponse
              getOutstandingBalanceResponse13 = null;
          org.wso2.carbon.billing.mgt.services.GetOutstandingBalance wrappedParam =
              (org.wso2.carbon.billing.mgt.services.GetOutstandingBalance)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.billing.mgt.services.GetOutstandingBalance.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getOutstandingBalanceResponse13 = skel.getOutstandingBalance(wrappedParam);

          envelope =
              toEnvelope(
                  getSOAPFactory(msgContext),
                  getOutstandingBalanceResponse13,
                  false,
                  new javax.xml.namespace.QName(
                      "http://services.mgt.billing.carbon.wso2.org", "getOutstandingBalance"));
        } else if ("getCurrentInvoice".equals(methodName)) {

          org.wso2.carbon.billing.mgt.services.GetCurrentInvoiceResponse
              getCurrentInvoiceResponse15 = null;
          org.wso2.carbon.billing.mgt.services.GetCurrentInvoice wrappedParam =
              (org.wso2.carbon.billing.mgt.services.GetCurrentInvoice)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.billing.mgt.services.GetCurrentInvoice.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getCurrentInvoiceResponse15 = skel.getCurrentInvoice(wrappedParam);

          envelope =
              toEnvelope(
                  getSOAPFactory(msgContext),
                  getCurrentInvoiceResponse15,
                  false,
                  new javax.xml.namespace.QName(
                      "http://services.mgt.billing.carbon.wso2.org", "getCurrentInvoice"));
        } else if ("getPastInvoice".equals(methodName)) {

          org.wso2.carbon.billing.mgt.services.GetPastInvoiceResponse getPastInvoiceResponse17 =
              null;
          org.wso2.carbon.billing.mgt.services.GetPastInvoice wrappedParam =
              (org.wso2.carbon.billing.mgt.services.GetPastInvoice)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.billing.mgt.services.GetPastInvoice.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getPastInvoiceResponse17 = skel.getPastInvoice(wrappedParam);

          envelope =
              toEnvelope(
                  getSOAPFactory(msgContext),
                  getPastInvoiceResponse17,
                  false,
                  new javax.xml.namespace.QName(
                      "http://services.mgt.billing.carbon.wso2.org", "getPastInvoice"));
        } else if ("addPayment".equals(methodName)) {

          org.wso2.carbon.billing.mgt.services.AddPaymentResponse addPaymentResponse19 = null;
          org.wso2.carbon.billing.mgt.services.AddPayment wrappedParam =
              (org.wso2.carbon.billing.mgt.services.AddPayment)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.billing.mgt.services.AddPayment.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          addPaymentResponse19 = skel.addPayment(wrappedParam);

          envelope =
              toEnvelope(
                  getSOAPFactory(msgContext),
                  addPaymentResponse19,
                  false,
                  new javax.xml.namespace.QName(
                      "http://services.mgt.billing.carbon.wso2.org", "addPayment"));
        } else if ("getAvailableBillingPeriods".equals(methodName)) {

          org.wso2.carbon.billing.mgt.services.GetAvailableBillingPeriodsResponse
              getAvailableBillingPeriodsResponse21 = null;
          org.wso2.carbon.billing.mgt.services.GetAvailableBillingPeriods wrappedParam =
              (org.wso2.carbon.billing.mgt.services.GetAvailableBillingPeriods)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.billing.mgt.services.GetAvailableBillingPeriods.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getAvailableBillingPeriodsResponse21 = skel.getAvailableBillingPeriods(wrappedParam);

          envelope =
              toEnvelope(
                  getSOAPFactory(msgContext),
                  getAvailableBillingPeriodsResponse21,
                  false,
                  new javax.xml.namespace.QName(
                      "http://services.mgt.billing.carbon.wso2.org", "getAvailableBillingPeriods"));
        } else if ("getPaginatedBalances".equals(methodName)) {

          org.wso2.carbon.billing.mgt.services.GetPaginatedBalancesResponse
              getPaginatedBalancesResponse23 = null;
          org.wso2.carbon.billing.mgt.services.GetPaginatedBalances wrappedParam =
              (org.wso2.carbon.billing.mgt.services.GetPaginatedBalances)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.billing.mgt.services.GetPaginatedBalances.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          getPaginatedBalancesResponse23 = skel.getPaginatedBalances(wrappedParam);

          envelope =
              toEnvelope(
                  getSOAPFactory(msgContext),
                  getPaginatedBalancesResponse23,
                  false,
                  new javax.xml.namespace.QName(
                      "http://services.mgt.billing.carbon.wso2.org", "getPaginatedBalances"));

        } else {
          throw new java.lang.RuntimeException("method not found");
        }

        newMsgContext.setEnvelope(envelope);
      }
    } catch (MultitenancyBillingServiceExceptionException e) {

      msgContext.setProperty(
          org.apache.axis2.Constants.FAULT_NAME, "MultitenancyBillingServiceException");
      org.apache.axis2.AxisFault f = createAxisFault(e);
      if (e.getFaultMessage() != null) {
        f.setDetail(toOM(e.getFaultMessage(), false));
      }
      throw f;
    } catch (java.lang.Exception e) {
      throw org.apache.axis2.AxisFault.makeFault(e);
    }
  }
  /**
   * Auto generated method signature
   *
   * @see com.pa.SecondFileService#getEmp
   * @param getEmp4
   */
  public com.pa.GetEmpResponse getEmp(com.pa.GetEmp getEmp4) throws java.rmi.RemoteException {

    org.apache.axis2.context.MessageContext _messageContext = null;
    try {
      org.apache.axis2.client.OperationClient _operationClient =
          _serviceClient.createClient(_operations[1].getName());
      _operationClient.getOptions().setAction("urn:getEmp");
      _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

      addPropertyToOperationClient(
          _operationClient,
          org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
          "&");

      // create a message context
      _messageContext = new org.apache.axis2.context.MessageContext();

      // create SOAP envelope with that payload
      org.apache.axiom.soap.SOAPEnvelope env = null;

      env =
          toEnvelope(
              getFactory(_operationClient.getOptions().getSoapVersionURI()),
              getEmp4,
              optimizeContent(new javax.xml.namespace.QName("http://pa.com", "getEmp")),
              new javax.xml.namespace.QName("http://pa.com", "getEmp"));

      // adding SOAP soap_headers
      _serviceClient.addHeadersToEnvelope(env);
      // set the message context with that soap envelope
      _messageContext.setEnvelope(env);

      // add the message contxt to the operation client
      _operationClient.addMessageContext(_messageContext);

      // execute the operation client
      _operationClient.execute(true);

      org.apache.axis2.context.MessageContext _returnMessageContext =
          _operationClient.getMessageContext(
              org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
      org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();

      java.lang.Object object =
          fromOM(
              _returnEnv.getBody().getFirstElement(),
              com.pa.GetEmpResponse.class,
              getEnvelopeNamespaces(_returnEnv));

      return (com.pa.GetEmpResponse) object;

    } catch (org.apache.axis2.AxisFault f) {

      org.apache.axiom.om.OMElement faultElt = f.getDetail();
      if (faultElt != null) {
        if (faultExceptionNameMap.containsKey(
            new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"))) {
          // make the fault by reflection
          try {
            java.lang.String exceptionClassName =
                (java.lang.String)
                    faultExceptionClassNameMap.get(
                        new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"));
            java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName);
            java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class);
            java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage());
            // message class
            java.lang.String messageClassName =
                (java.lang.String)
                    faultMessageMap.get(
                        new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"));
            java.lang.Class messageClass = java.lang.Class.forName(messageClassName);
            java.lang.Object messageObject = fromOM(faultElt, messageClass, null);
            java.lang.reflect.Method m =
                exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] {messageClass});
            m.invoke(ex, new java.lang.Object[] {messageObject});

            throw new java.rmi.RemoteException(ex.getMessage(), ex);
          } catch (java.lang.ClassCastException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.ClassNotFoundException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.NoSuchMethodException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.reflect.InvocationTargetException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.IllegalAccessException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          } catch (java.lang.InstantiationException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          }
        } else {
          throw f;
        }
      } else {
        throw f;
      }
    } finally {
      if (_messageContext.getTransportOut() != null) {
        _messageContext.getTransportOut().getSender().cleanup(_messageContext);
      }
    }
  }
Exemplo n.º 16
0
  /**
   * Process a single file through Axis2
   *
   * @param entry the PollTableEntry for the file (or its parent directory or archive)
   * @param file the file that contains the actual message pumped into Axis2
   * @throws AxisFault on error
   */
  private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {

    try {
      FileContent content = file.getContent();
      String fileName = file.getName().getBaseName();
      String filePath = file.getName().getPath();

      metrics.incrementBytesReceived(content.getSize());

      Map<String, Object> transportHeaders = new HashMap<String, Object>();
      transportHeaders.put(VFSConstants.FILE_PATH, filePath);
      transportHeaders.put(VFSConstants.FILE_NAME, fileName);

      try {
        transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
        transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
      } catch (FileSystemException ignore) {
      }

      MessageContext msgContext = entry.createMessageContext();

      String contentType = entry.getContentType();
      if (BaseUtils.isBlank(contentType)) {
        if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
          contentType = "text/xml";
        } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
          contentType = "text/plain";
        }
      } else {
        // Extract the charset encoding from the configured content type and
        // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
        String charSetEnc = null;
        try {
          if (contentType != null) {
            charSetEnc = new ContentType(contentType).getParameter("charset");
          }
        } catch (ParseException ex) {
          // ignore
        }
        msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
      }

      // if the content type was not found, but the service defined it.. use it
      if (contentType == null) {
        if (entry.getContentType() != null) {
          contentType = entry.getContentType();
        } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
          contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
        }
      }

      // does the service specify a default reply file URI ?
      String replyFileURI = entry.getReplyFileURI();
      if (replyFileURI != null) {
        msgContext.setProperty(
            Constants.OUT_TRANSPORT_INFO,
            new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
      }

      // Determine the message builder to use
      Builder builder;
      if (contentType == null) {
        log.debug("No content type specified. Using SOAP builder.");
        builder = new SOAPBuilder();
      } else {
        int index = contentType.indexOf(';');
        String type = index > 0 ? contentType.substring(0, index) : contentType;
        builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
        if (builder == null) {
          if (log.isDebugEnabled()) {
            log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
          }
          builder = new SOAPBuilder();
        }
      }

      // set the message payload to the message context
      InputStream in;
      ManagedDataSource dataSource;
      if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
        in = null;
        dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
      } else {
        in = new AutoCloseInputStream(content.getInputStream());
        dataSource = null;
      }

      try {
        OMElement documentElement;
        if (in != null) {
          documentElement = builder.processDocument(in, contentType, msgContext);
        } else {
          documentElement =
              ((DataSourceMessageBuilder) builder)
                  .processDocument(dataSource, contentType, msgContext);
        }
        msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

        handleIncomingMessage(
            msgContext,
            transportHeaders,
            null, // * SOAP Action - not applicable *//
            contentType);
      } finally {
        if (dataSource != null) {
          dataSource.destroy();
        }
      }

      if (log.isDebugEnabled()) {
        log.debug("Processed file : " + file + " of Content-type : " + contentType);
      }

    } catch (FileSystemException e) {
      handleException("Error reading file content or attributes : " + file, e);

    } finally {
      try {
        file.close();
      } catch (FileSystemException warn) {
        //  log.warn("Cannot close file after processing : " + file.getName().getPath(), warn);
        // ignore the warning, since we handed over the stream close job to AutocloseInputstream..
      }
    }
  }
  /**
   * This method creates 3 soap envelopes for 3 different client based sessions. Then it randomly
   * choose one envelope for each iteration and send it to the ESB. ESB should be configured with
   * session affinity load balancer and the SampleClientInitiatedSession dispatcher. This will
   * output request number, session number and the server ID for each iteration. So it can be
   * observed that one session number always associated with one server ID.
   */
  private void sessionfullClient() {

    String synapsePort = "8280";
    int iterations = 100;
    boolean infinite = true;

    String pPort = getProperty("port", synapsePort);
    String pIterations = getProperty("i", null);
    String addUrl = getProperty("addurl", null);
    String trpUrl = getProperty("trpurl", null);
    String prxUrl = getProperty("prxurl", null);
    String sleep = getProperty("sleep", null);
    String session = getProperty("session", null);

    long sleepTime = -1;
    if (sleep != null) {
      try {
        sleepTime = Long.parseLong(sleep);
      } catch (NumberFormatException ignored) {
      }
    }

    if (pPort != null) {
      try {

        Integer.parseInt(pPort);
        synapsePort = pPort;
      } catch (NumberFormatException e) {
        // run with default value
      }
    }

    if (pIterations != null) {
      try {
        iterations = Integer.parseInt(pIterations);
        if (iterations != -1) {
          infinite = false;
        }
      } catch (NumberFormatException e) {
        // run with default values
      }
    }

    Options options = new Options();
    options.setTo(
        new EndpointReference("http://localhost:" + synapsePort + "/services/LBService1"));
    options.setAction("urn:sampleOperation");
    options.setTimeOutInMilliSeconds(10000000);

    try {

      SOAPEnvelope env1 = buildSoapEnvelope("c1", "v1");
      SOAPEnvelope env2 = buildSoapEnvelope("c2", "v1");
      SOAPEnvelope env3 = buildSoapEnvelope("c3", "v1");
      SOAPEnvelope[] envelopes = {env1, env2, env3};

      ConfigurationContext configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem("client_repo", null);
      ServiceClient client = new ServiceClient(configContext, null);

      // set addressing, transport and proxy url
      if (addUrl != null && !"null".equals(addUrl)) {
        client.engageModule("addressing");
        options.setTo(new EndpointReference(addUrl));
      }
      if (trpUrl != null && !"null".equals(trpUrl)) {
        options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
      } else {
        client.engageModule("addressing");
      }
      if (prxUrl != null && !"null".equals(prxUrl)) {
        HttpTransportProperties.ProxyProperties proxyProperties =
            new HttpTransportProperties.ProxyProperties();
        try {
          URL url = new URL(prxUrl);
          proxyProperties.setProxyName(url.getHost());
          proxyProperties.setProxyPort(url.getPort());
          proxyProperties.setUserName("");
          proxyProperties.setPassWord("");
          proxyProperties.setDomain("");
          options.setProperty(HTTPConstants.PROXY, proxyProperties);
        } catch (MalformedURLException e) {
          throw new AxisFault("Error creating proxy URL", e);
        }
      }
      client.setOptions(options);

      int i = 0;
      int sessionNumber = 0;
      String[] cookies = new String[3];
      boolean httpSession = session != null && "http".equals(session);
      int cookieNumber = 0;
      while (i < iterations || infinite) {

        i++;
        if (sleepTime != -1) {
          try {
            Thread.sleep(sleepTime);
          } catch (InterruptedException ignored) {
          }
        }

        MessageContext messageContext = new MessageContext();
        sessionNumber = getSessionTurn(envelopes.length);

        messageContext.setEnvelope(envelopes[sessionNumber]);
        cookieNumber = getSessionTurn(cookies.length);
        String cookie = cookies[cookieNumber];
        if (httpSession) {
          setSessionID(messageContext, cookie);
        }
        try {
          OperationClient op = client.createClient(ServiceClient.ANON_OUT_IN_OP);
          op.addMessageContext(messageContext);
          op.execute(true);

          MessageContext responseContext =
              op.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
          String receivedCookie = extractSessionID(responseContext);
          String receivedSetCookie = getSetCookieHeader(responseContext);
          if (httpSession) {

            if (receivedSetCookie != null && !"".equals(receivedSetCookie)) {
              cookies[cookieNumber] = receivedCookie;
            }
          }

          SOAPEnvelope responseEnvelope = responseContext.getEnvelope();

          OMElement vElement = responseEnvelope.getBody().getFirstChildWithName(new QName("Value"));
          System.out.println(
              "Request: "
                  + i
                  + " with Session ID: "
                  + (httpSession ? cookie : sessionNumber)
                  + " ---- "
                  + "Response : with  "
                  + (httpSession && receivedCookie != null
                      ? (receivedSetCookie != null ? receivedSetCookie : receivedCookie)
                      : " ")
                  + " "
                  + vElement.getText());
        } catch (AxisFault axisFault) {
          System.out.println(
              "Request with session id "
                  + (httpSession ? cookie : sessionNumber)
                  + " "
                  + "- Get a Fault : "
                  + axisFault.getMessage());
        }
      }

    } catch (AxisFault axisFault) {
      System.out.println(axisFault.getMessage());
    }
  }
  /**
   * Auto generated method signature for Asynchronous Invocations
   *
   * @see com.pa.SecondFileService#startgetEmp
   * @param getEmp4
   */
  public void startgetEmp(
      com.pa.GetEmp getEmp4, final com.pa.SecondFileServiceCallbackHandler callback)
      throws java.rmi.RemoteException {

    org.apache.axis2.client.OperationClient _operationClient =
        _serviceClient.createClient(_operations[1].getName());
    _operationClient.getOptions().setAction("urn:getEmp");
    _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

    addPropertyToOperationClient(
        _operationClient,
        org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
        "&");

    // create SOAP envelope with that payload
    org.apache.axiom.soap.SOAPEnvelope env = null;
    final org.apache.axis2.context.MessageContext _messageContext =
        new org.apache.axis2.context.MessageContext();

    // Style is Doc.

    env =
        toEnvelope(
            getFactory(_operationClient.getOptions().getSoapVersionURI()),
            getEmp4,
            optimizeContent(new javax.xml.namespace.QName("http://pa.com", "getEmp")),
            new javax.xml.namespace.QName("http://pa.com", "getEmp"));

    // adding SOAP soap_headers
    _serviceClient.addHeadersToEnvelope(env);
    // create message context with that soap envelope
    _messageContext.setEnvelope(env);

    // add the message context to the operation client
    _operationClient.addMessageContext(_messageContext);

    _operationClient.setCallback(
        new org.apache.axis2.client.async.AxisCallback() {
          public void onMessage(org.apache.axis2.context.MessageContext resultContext) {
            try {
              org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope();

              java.lang.Object object =
                  fromOM(
                      resultEnv.getBody().getFirstElement(),
                      com.pa.GetEmpResponse.class,
                      getEnvelopeNamespaces(resultEnv));
              callback.receiveResultgetEmp((com.pa.GetEmpResponse) object);

            } catch (org.apache.axis2.AxisFault e) {
              callback.receiveErrorgetEmp(e);
            }
          }

          public void onError(java.lang.Exception error) {
            if (error instanceof org.apache.axis2.AxisFault) {
              org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error;
              org.apache.axiom.om.OMElement faultElt = f.getDetail();
              if (faultElt != null) {
                if (faultExceptionNameMap.containsKey(
                    new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getEmp"))) {
                  // make the fault by reflection
                  try {
                    java.lang.String exceptionClassName =
                        (java.lang.String)
                            faultExceptionClassNameMap.get(
                                new org.apache.axis2.client.FaultMapKey(
                                    faultElt.getQName(), "getEmp"));
                    java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName);
                    java.lang.reflect.Constructor constructor =
                        exceptionClass.getConstructor(String.class);
                    java.lang.Exception ex =
                        (java.lang.Exception) constructor.newInstance(f.getMessage());
                    // message class
                    java.lang.String messageClassName =
                        (java.lang.String)
                            faultMessageMap.get(
                                new org.apache.axis2.client.FaultMapKey(
                                    faultElt.getQName(), "getEmp"));
                    java.lang.Class messageClass = java.lang.Class.forName(messageClassName);
                    java.lang.Object messageObject = fromOM(faultElt, messageClass, null);
                    java.lang.reflect.Method m =
                        exceptionClass.getMethod(
                            "setFaultMessage", new java.lang.Class[] {messageClass});
                    m.invoke(ex, new java.lang.Object[] {messageObject});

                    callback.receiveErrorgetEmp(new java.rmi.RemoteException(ex.getMessage(), ex));
                  } catch (java.lang.ClassCastException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.ClassNotFoundException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.NoSuchMethodException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.reflect.InvocationTargetException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.IllegalAccessException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (java.lang.InstantiationException e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  } catch (org.apache.axis2.AxisFault e) {
                    // we cannot intantiate the class - throw the original Axis fault
                    callback.receiveErrorgetEmp(f);
                  }
                } else {
                  callback.receiveErrorgetEmp(f);
                }
              } else {
                callback.receiveErrorgetEmp(f);
              }
            } else {
              callback.receiveErrorgetEmp(error);
            }
          }

          public void onFault(org.apache.axis2.context.MessageContext faultContext) {
            org.apache.axis2.AxisFault fault =
                org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext);
            onError(fault);
          }

          public void onComplete() {
            try {
              _messageContext.getTransportOut().getSender().cleanup(_messageContext);
            } catch (org.apache.axis2.AxisFault axisFault) {
              callback.receiveErrorgetEmp(axisFault);
            }
          }
        });

    org.apache.axis2.util.CallbackReceiver _callbackReceiver = null;
    if (_operations[1].getMessageReceiver() == null
        && _operationClient.getOptions().isUseSeparateListener()) {
      _callbackReceiver = new org.apache.axis2.util.CallbackReceiver();
      _operations[1].setMessageReceiver(_callbackReceiver);
    }

    // execute the operation client
    _operationClient.execute(false);
  }
Exemplo n.º 19
0
  public CadConsultaCadastro2Stub.ConsultaCadastro2Result consultaCadastro2(
      final CadConsultaCadastro2Stub.NfeDadosMsg nfeDadosMsg,
      final CadConsultaCadastro2Stub.NfeCabecMsgE nfeCabecMsg)
      throws java.rmi.RemoteException {

    org.apache.axis2.context.MessageContext _messageContext = null;
    try {
      final org.apache.axis2.client.OperationClient _operationClient =
          this._serviceClient.createClient(this._operations[0].getName());
      _operationClient
          .getOptions()
          .setAction(
              "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2/consultaCadastro2");
      _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true);

      this.addPropertyToOperationClient(
          _operationClient,
          org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR,
          "&");

      // create a message context
      _messageContext = new org.apache.axis2.context.MessageContext();

      // create SOAP envelope with that payload
      org.apache.axiom.soap.SOAPEnvelope env = null;

      env =
          this.toEnvelope(
              Stub.getFactory(_operationClient.getOptions().getSoapVersionURI()),
              nfeDadosMsg,
              this.optimizeContent(
                  new javax.xml.namespace.QName(
                      "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2",
                      "consultaCadastro2")),
              new javax.xml.namespace.QName(
                  "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2",
                  "consultaCadastro2"));

      env.build();

      // add the children only if the parameter is not null
      if (nfeCabecMsg != null) {

        final org.apache.axiom.om.OMElement omElementnfeCabecMsg =
            this.toOM(
                nfeCabecMsg,
                this.optimizeContent(
                    new javax.xml.namespace.QName(
                        "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2",
                        "consultaCadastro2")));
        this.addHeader(omElementnfeCabecMsg, env);
      }

      // adding SOAP soap_headers
      this._serviceClient.addHeadersToEnvelope(env);
      // set the message context with that soap envelope
      _messageContext.setEnvelope(env);

      // add the message contxt to the operation client
      _operationClient.addMessageContext(_messageContext);

      // execute the operation client
      _operationClient.execute(true);

      final org.apache.axis2.context.MessageContext _returnMessageContext =
          _operationClient.getMessageContext(
              org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE);
      final org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope();

      final java.lang.Object object =
          this.fromOM(
              _returnEnv.getBody().getFirstElement(),
              CadConsultaCadastro2Stub.ConsultaCadastro2Result.class,
              this.getEnvelopeNamespaces(_returnEnv));

      return (CadConsultaCadastro2Stub.ConsultaCadastro2Result) object;

    } catch (final org.apache.axis2.AxisFault f) {

      final org.apache.axiom.om.OMElement faultElt = f.getDetail();
      if (faultElt != null) {
        if (this.faultExceptionNameMap.containsKey(
            new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "consultaCadastro2"))) {
          // make the fault by reflection
          try {
            final java.lang.String exceptionClassName =
                (java.lang.String)
                    this.faultExceptionClassNameMap.get(
                        new org.apache.axis2.client.FaultMapKey(
                            faultElt.getQName(), "consultaCadastro2"));
            final Class<?> exceptionClass = java.lang.Class.forName(exceptionClassName);
            final Constructor<?> constructor = exceptionClass.getConstructor(String.class);
            final java.lang.Exception ex =
                (java.lang.Exception) constructor.newInstance(f.getMessage());
            // message class
            final java.lang.String messageClassName =
                (java.lang.String)
                    this.faultMessageMap.get(
                        new org.apache.axis2.client.FaultMapKey(
                            faultElt.getQName(), "consultaCadastro2"));
            final Class<?> messageClass = java.lang.Class.forName(messageClassName);
            final java.lang.Object messageObject = this.fromOM(faultElt, messageClass, null);
            final java.lang.reflect.Method m =
                exceptionClass.getMethod("setFaultMessage", messageClass);
            m.invoke(ex, messageObject);

            throw new java.rmi.RemoteException(ex.getMessage(), ex);
          } catch (final ClassCastException
              | InstantiationException
              | IllegalAccessException
              | java.lang.reflect.InvocationTargetException
              | NoSuchMethodException
              | ClassNotFoundException e) {
            // we cannot intantiate the class - throw the original Axis fault
            throw f;
          }
        } else {
          throw f;
        }
      } else {
        throw f;
      }
    } finally {
      if (_messageContext.getTransportOut() != null) {
        _messageContext.getTransportOut().getSender().cleanup(_messageContext);
      }
    }
  }