コード例 #1
0
  private void populateAxisService() throws org.apache.axis2.AxisFault {

    // creating the Service with a unique name
    _service =
        new org.apache.axis2.description.AxisService("SecondFileService" + getUniqueSuffix());
    addAnonymousOperations();

    // creating the operations
    org.apache.axis2.description.AxisOperation __operation;

    _operations = new org.apache.axis2.description.AxisOperation[2];

    __operation = new org.apache.axis2.description.OutOnlyAxisOperation();

    __operation.setName(new javax.xml.namespace.QName("http://pa.com", "setEmp"));
    _service.addOperation(__operation);

    _operations[0] = __operation;

    __operation = new org.apache.axis2.description.OutInAxisOperation();

    __operation.setName(new javax.xml.namespace.QName("http://pa.com", "getEmp"));
    _service.addOperation(__operation);

    _operations[1] = __operation;
  }
コード例 #2
0
ファイル: ServiceBuilder.java プロジェクト: isuruw/wso2-axis2
  private boolean generateWsdl(AxisService axisService) {
    Iterator operatins = axisService.getOperations();
    if (operatins.hasNext()) {
      while (operatins.hasNext()) {
        AxisOperation axisOperation = (AxisOperation) operatins.next();

        if (axisOperation.isControlOperation()) {
          continue;
        }

        if (axisOperation.getMessageReceiver() == null) {
          continue;
        }
        String messageReceiverClass = axisOperation.getMessageReceiver().getClass().getName();
        if (!("org.apache.axis2.rpc.receivers.RPCMessageReceiver".equals(messageReceiverClass)
            || "org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"
                .equals(messageReceiverClass)
            || "org.apache.axis2.rpc.receivers.RPCInOutAsyncMessageReceiver"
                .equals(messageReceiverClass)
            || "org.apache.axis2.jaxws.server.JAXWSMessageReceiver".equals(messageReceiverClass))) {
          return false;
        }
      }
    }
    return true;
  }
コード例 #3
0
  /**
   * 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);
    }
  }
  public void invokeBusinessLogic(org.apache.axis2.context.MessageContext msgContext)
      throws org.apache.axis2.AxisFault {

    try {

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

      MultitenancyThrottlingServiceSkeletonInterface skel =
          (MultitenancyThrottlingServiceSkeletonInterface) 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 ("executeThrottlingRules".equals(methodName)) {

          // doc style
          org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules wrappedParam =
              (org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules)
                  fromOM(
                      msgContext.getEnvelope().getBody().getFirstElement(),
                      org.wso2.carbon.throttling.manager.services.ExecuteThrottlingRules.class,
                      getEnvelopeNamespaces(msgContext.getEnvelope()));

          skel.executeThrottlingRules(wrappedParam);

          envelope = getSOAPFactory(msgContext).getDefaultEnvelope();

        } else {
          throw new java.lang.RuntimeException("method not found");
        }
      }
    } catch (MultitenancyThrottlingServiceExceptionException e) {
      msgContext.setProperty(
          org.apache.axis2.Constants.FAULT_NAME, "MultitenancyThrottlingServiceException");
      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);
    }
  }
コード例 #5
0
ファイル: AdminAgent.java プロジェクト: isuruw/wso2-axis2
 public void processdisengageModule(HttpServletRequest req, HttpServletResponse res)
     throws IOException, ServletException {
   String type = req.getParameter("type");
   String serviceName = req.getParameter("serviceName");
   String moduleName = req.getParameter("module");
   AxisConfiguration axisConfiguration = configContext.getAxisConfiguration();
   AxisService service = axisConfiguration.getService(serviceName);
   AxisModule module = axisConfiguration.getModule(moduleName);
   if (type.equals("operation")) {
     if (service.isEngaged(module.getName()) || axisConfiguration.isEngaged(module.getName())) {
       req.getSession()
           .setAttribute(
               "status",
               "Can not disengage module "
                   + moduleName
                   + ". This module is engaged at a higher level.");
     } else {
       String opName = req.getParameter("operation");
       AxisOperation op = service.getOperation(new QName(opName));
       op.disengageModule(module);
       req.getSession()
           .setAttribute(
               "status",
               "Module "
                   + moduleName
                   + " was disengaged from "
                   + "operation "
                   + opName
                   + " in service "
                   + serviceName
                   + ".");
     }
   } else {
     if (axisConfiguration.isEngaged(module.getName())) {
       req.getSession()
           .setAttribute(
               "status",
               "Can not disengage module "
                   + moduleName
                   + ". "
                   + "This module is engaged at a higher level.");
     } else {
       service.disengageModule(axisConfiguration.getModule(moduleName));
       req.getSession()
           .setAttribute(
               "status",
               "Module " + moduleName + " was disengaged from" + " service " + serviceName + ".");
     }
   }
   renderView("disengage.jsp", req, res);
 }
コード例 #6
0
ファイル: AdminAgent.java プロジェクト: isuruw/wso2-axis2
  public void processListOperations(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    Map<String, AxisModule> modules = configContext.getAxisConfiguration().getModules();

    req.getSession().setAttribute(Constants.MODULE_MAP, modules);

    String moduleName = req.getParameter("modules");

    req.getSession().setAttribute(Constants.ENGAGE_STATUS, null);
    req.getSession().setAttribute("modules", null);

    String serviceName = req.getParameter("axisService");

    if (serviceName != null) {
      req.getSession().setAttribute("service", serviceName);
    } else {
      serviceName = (String) req.getSession().getAttribute("service");
    }

    req.getSession()
        .setAttribute(
            Constants.OPERATION_MAP,
            configContext.getAxisConfiguration().getService(serviceName).getOperations());
    req.getSession().setAttribute(Constants.ENGAGE_STATUS, null);

    String operationName = req.getParameter("axisOperation");

    if ((serviceName != null) && (moduleName != null) && (operationName != null)) {
      try {
        AxisOperation od =
            configContext
                .getAxisConfiguration()
                .getService(serviceName)
                .getOperation(new QName(operationName));

        od.engageModule(configContext.getAxisConfiguration().getModule(moduleName));
        req.getSession()
            .setAttribute(
                Constants.ENGAGE_STATUS,
                moduleName + " module engaged to the operation successfully");
      } catch (AxisFault axisFault) {
        req.getSession().setAttribute(Constants.ENGAGE_STATUS, axisFault.getMessage());
      }
    }

    req.getSession().setAttribute("operation", null);
    renderView(ENGAGE_TO_OPERATION_JSP_NAME, req, res);
  }
コード例 #7
0
ファイル: ServiceBuilder.java プロジェクト: isuruw/wso2-axis2
  private void processMessages(Iterator messages, AxisOperation operation)
      throws DeploymentException {
    while (messages.hasNext()) {
      OMElement messageElement = (OMElement) messages.next();
      OMAttribute label = messageElement.getAttribute(new QName(TAG_LABEL));

      if (label == null) {
        throw new DeploymentException(Messages.getMessage("messagelabelcannotfound"));
      }

      AxisMessage message = operation.getMessage(label.getAttributeValue());

      Iterator parameters = messageElement.getChildrenWithName(new QName(TAG_PARAMETER));

      // processing <wsp:Policy> .. </..> elements
      Iterator policyElements =
          messageElement.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY));

      if (policyElements != null) {
        processPolicyElements(policyElements, message.getPolicySubject());
      }

      // processing <wsp:PolicyReference> .. </..> elements
      Iterator policyRefElements =
          messageElement.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY_REF));

      if (policyRefElements != null) {
        processPolicyRefElements(policyRefElements, message.getPolicySubject());
      }

      processParameters(parameters, message, operation);
    }
  }
コード例 #8
0
ファイル: AdminAgent.java プロジェクト: isuruw/wso2-axis2
  public void processEditServicePara(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    String serviceName = req.getParameter("axisService");
    if (req.getParameter("changePara") != null) {
      AxisService service = configContext.getAxisConfiguration().getService(serviceName);
      if (service != null) {
        for (Parameter parameter : service.getParameters()) {
          String para = req.getParameter(serviceName + "_" + parameter.getName());
          service.addParameter(new Parameter(parameter.getName(), para));
        }

        for (Iterator<AxisOperation> iterator = service.getOperations(); iterator.hasNext(); ) {
          AxisOperation axisOperation = iterator.next();
          String op_name = axisOperation.getName().getLocalPart();

          for (Parameter parameter : axisOperation.getParameters()) {
            String para = req.getParameter(op_name + "_" + parameter.getName());

            axisOperation.addParameter(new Parameter(parameter.getName(), para));
          }
        }
      }
      res.setContentType("text/html");
      req.setAttribute("status", "Parameters Changed Successfully.");
      req.getSession().removeAttribute(Constants.SERVICE);
    } else {
      AxisService serviceTemp =
          configContext.getAxisConfiguration().getServiceForActivation(serviceName);
      if (serviceTemp.isActive()) {

        if (serviceName != null) {
          req.getSession()
              .setAttribute(
                  Constants.SERVICE, configContext.getAxisConfiguration().getService(serviceName));
        }
      } else {
        req.setAttribute(
            "status",
            "Service "
                + serviceName
                + " is not an active service"
                + ". \n Only parameters of active services can be edited.");
      }
    }
    renderView(SERVICE_PARA_EDIT_JSP_NAME, req, res);
  }
コード例 #9
0
ファイル: ServiceBuilder.java プロジェクト: isuruw/wso2-axis2
 private void setDefaultMessageReceivers() {
   Iterator operations = service.getPublishedOperations().iterator();
   while (operations.hasNext()) {
     AxisOperation operation = (AxisOperation) operations.next();
     if (operation.getMessageReceiver() == null) {
       MessageReceiver messageReceiver =
           loadDefaultMessageReceiver(operation.getMessageExchangePattern(), service);
       if (messageReceiver == null
           &&
           // we assume that if the MEP is ROBUST_IN_ONLY then the in-out
           // MR can handle that
           WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(operation.getMessageExchangePattern())) {
         messageReceiver = loadDefaultMessageReceiver(WSDL2Constants.MEP_URI_IN_OUT, service);
       }
       operation.setMessageReceiver(messageReceiver);
     }
   }
 }
コード例 #10
0
  private void populateAxisService() throws org.apache.axis2.AxisFault {

    // creating the Service with a unique name
    _service = new org.apache.axis2.description.AxisService("LabService" + getUniqueSuffix());
    addAnonymousOperations();

    // creating the operations
    org.apache.axis2.description.AxisOperation __operation;

    _operations = new org.apache.axis2.description.AxisOperation[1];

    __operation = new org.apache.axis2.description.OutInAxisOperation();

    __operation.setName(
        new javax.xml.namespace.QName("http://www.PAHospital.org/LabService/", "orderLabTest"));
    _service.addOperation(__operation);

    _operations[0] = __operation;
  }
コード例 #11
0
  /**
   * Process statistics for this message
   *
   * @param synCtx the current message
   */
  protected void prepareForEndpointStatistics(MessageContext synCtx) {
    // Setting Required property to reportForComponent the End Point aspects
    if (definition != null && definition.isStatisticsEnable()) {
      String opName = null;

      if (synCtx.getProperty(SynapseConstants.ENDPOINT_OPERATION) != null) {
        opName = synCtx.getProperty(SynapseConstants.ENDPOINT_OPERATION).toString();
      } else if (synCtx instanceof Axis2MessageContext) {
        AxisOperation operation =
            ((Axis2MessageContext) synCtx).getAxis2MessageContext().getAxisOperation();
        if (operation != null) {
          opName = operation.getName().getLocalPart();
        }
        if (opName == null
            || SynapseConstants.SYNAPSE_OPERATION_NAME.getLocalPart().equals(opName)) {
          String soapAction = synCtx.getSoapAction();
          opName = null;
          if (soapAction != null) {
            int index = soapAction.indexOf("urn:");
            if (index >= 0) {
              opName = soapAction.substring("urn:".length());
            } else {
              opName = soapAction;
            }
          }
        }
      }

      AspectConfiguration oldConfiguration = definition.getAspectConfiguration();
      if (opName != null) {
        AspectConfiguration newConfiguration =
            new AspectConfiguration(
                oldConfiguration.getId() + SynapseConstants.STATISTICS_KEY_SEPARATOR + opName);
        if (oldConfiguration.isStatisticsEnable()) {
          newConfiguration.enableStatistics();
        }
        if (oldConfiguration.isTracingEnabled()) {
          newConfiguration.enableTracing();
        }
      }
    }
  }
コード例 #12
0
  /**
   * Adds Synapse Service to Axis2 configuration which enables the main message mediation.
   *
   * @throws AxisFault if an error occurs during Axis2 service initialization
   */
  private void deploySynapseService() throws AxisFault {

    log.info("Deploying the Synapse service...");
    // Dynamically initialize the Synapse Service and deploy it into Axis2
    AxisConfiguration axisCfg = configurationContext.getAxisConfiguration();
    AxisService synapseService = new AxisService(SynapseConstants.SYNAPSE_SERVICE_NAME);
    AxisOperation mediateOperation =
        new InOutAxisOperation(SynapseConstants.SYNAPSE_OPERATION_NAME);
    mediateOperation.setMessageReceiver(new SynapseMessageReceiver());
    synapseService.addOperation(mediateOperation);
    List<String> transports = new ArrayList<String>();
    transports.add(Constants.TRANSPORT_HTTP);
    transports.add(Constants.TRANSPORT_HTTPS);
    synapseService.setExposedTransports(transports);
    AxisServiceGroup synapseServiceGroup = new AxisServiceGroup(axisCfg);
    synapseServiceGroup.setServiceGroupName(SynapseConstants.SYNAPSE_SERVICE_NAME);
    synapseServiceGroup.addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    synapseServiceGroup.addService(synapseService);
    axisCfg.addServiceGroup(synapseServiceGroup);
  }
コード例 #13
0
  public void testSEIBasedEndpoint() {
    ServiceDescription serviceDesc =
        DescriptionFactory.createServiceDescription(SEIBasedEndpoint.class);
    assertNotNull(serviceDesc);
    EndpointDescription endpointDesc =
        serviceDesc.getEndpointDescriptions_AsCollection().iterator().next();
    assertNotNull(endpointDesc);
    AxisService axisSvc = endpointDesc.getAxisService();
    assertNotNull(axisSvc);

    EndpointInterfaceDescription interfaceDesc = endpointDesc.getEndpointInterfaceDescription();
    assertNotNull(interfaceDesc);

    // There should be a single OpDesc with a single AxisOperation based on the SEI below
    // But it should not be the special named operation and the special dispatcher should not
    // return null for operation dispatch
    OperationDescription opDescs[] = interfaceDesc.getOperations();
    assertNotNull(opDescs);
    assertEquals(1, opDescs.length);
    AxisOperation axisOperation = opDescs[0].getAxisOperation();
    assertNotNull(axisOperation);
    if (EndpointInterfaceDescription.JAXWS_NOWSDL_PROVIDER_OPERATION_NAME.equals(
        axisOperation.getName().getLocalPart())) {
      fail("Operation has the generic provider name");
    }

    // Now verify that the special dispather doesn't find the special operation
    GenericProviderDispatcher dispatcher = new GenericProviderDispatcher();
    MessageContext messageContext = new MessageContext();
    messageContext.setAxisService(axisSvc);

    try {
      // The dispatcher will not try to resolve an AxisService
      assertNull(dispatcher.findService(messageContext));

      // The dispatcher should find the special AxisOperation
      assertNull(dispatcher.findOperation(axisSvc, messageContext));
    } catch (AxisFault e) {
      fail("Unexpected exception" + e);
    }
  }
コード例 #14
0
  private void populateAxisService() throws org.apache.axis2.AxisFault {

    // creating the Service with a unique name
    this._service =
        new org.apache.axis2.description.AxisService(
            "CadConsultaCadastro2" + CadConsultaCadastro2Stub.getUniqueSuffix());
    this.addAnonymousOperations();

    // creating the operations
    org.apache.axis2.description.AxisOperation __operation;

    this._operations = new org.apache.axis2.description.AxisOperation[1];

    __operation = new org.apache.axis2.description.OutInAxisOperation();

    __operation.setName(
        new javax.xml.namespace.QName(
            "http://www.portalfiscal.inf.br/nfe/wsdl/CadConsultaCadastro2", "consultaCadastro2"));
    this._service.addOperation(__operation);

    this._operations[0] = __operation;
  }
コード例 #15
0
ファイル: ServiceBuilder.java プロジェクト: isuruw/wso2-axis2
 /**
  * To get the methods which do not use RPC* MessageReceivers
  *
  * @param axisService the AxisService to search
  * @return an ArrayList of the LOCAL PARTS of the QNames of any non-RPC operations TODO: Why not
  *     just return the AxisOperations themselves??
  */
 private ArrayList<String> getNonRPCMethods(AxisService axisService) {
   ArrayList<String> excludeOperations = new ArrayList<String>();
   Iterator<AxisOperation> operatins = axisService.getOperations();
   if (operatins.hasNext()) {
     while (operatins.hasNext()) {
       AxisOperation axisOperation = operatins.next();
       if (axisOperation.getMessageReceiver() == null) {
         continue;
       }
       String messageReceiverClass = axisOperation.getMessageReceiver().getClass().getName();
       if (!("org.apache.axis2.rpc.receivers.RPCMessageReceiver".equals(messageReceiverClass)
           || "org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"
               .equals(messageReceiverClass)
           || "org.apache.axis2.rpc.receivers.RPCInOutAsyncMessageReceiver"
               .equals(messageReceiverClass)
           || "org.apache.axis2.jaxws.server.JAXWSMessageReceiver".equals(messageReceiverClass))) {
         excludeOperations.add(axisOperation.getName().getLocalPart());
       }
     }
   }
   return excludeOperations;
 }
コード例 #16
0
  public void testGenericHTTPBindingOperation() {
    // The HTTP binding supports a generic operation for WSDL-less endpoints.
    ServiceDescription serviceDesc =
        DescriptionFactory.createServiceDescription(HTTPBindingProviderImpl.class);
    assertNotNull(serviceDesc);
    EndpointDescription endpointDesc =
        serviceDesc.getEndpointDescriptions_AsCollection().iterator().next();
    assertNotNull(endpointDesc);
    AxisService axisSvc = endpointDesc.getAxisService();
    assertNotNull(axisSvc);

    EndpointInterfaceDescription interfaceDesc = endpointDesc.getEndpointInterfaceDescription();
    assertNotNull(interfaceDesc);

    // There should be a single OpDesc with a single AxisOperation with a specific name
    OperationDescription opDescs[] = interfaceDesc.getOperations();
    assertNotNull(opDescs);
    assertEquals(1, opDescs.length);
    AxisOperation axisOperation = opDescs[0].getAxisOperation();
    assertNotNull(axisOperation);
    assertEquals(
        EndpointInterfaceDescription.JAXWS_NOWSDL_PROVIDER_OPERATION_NAME,
        axisOperation.getName().getLocalPart());

    // Now verify that the special dispather can find this operation
    GenericProviderDispatcher dispatcher = new GenericProviderDispatcher();
    MessageContext messageContext = new MessageContext();
    messageContext.setAxisService(axisSvc);

    try {
      // The dispatcher will not try to resolve an AxisService
      assertNull(dispatcher.findService(messageContext));

      // The dispatcher should find the special AxisOperation
      assertEquals(axisOperation, dispatcher.findOperation(axisSvc, messageContext));
    } catch (AxisFault e) {
      fail("Unexpected exception" + e);
    }
  }
コード例 #17
0
  private Method findOperation(AxisOperation op, Class implClass) throws AxisFault {

    Method method = (Method) (op.getParameterValue("myMethod"));

    if (method != null) return method;

    String methodName = op.getName().getLocalPart();

    try {

      // Looking for a method of the form "void method(OMElement)"

      method = implClass.getMethod(methodName, new Class[] {OMElement.class});

      //			if (1 == 1)
      //				throw new Exception("return type is " + method.getReturnType().getName() + "\n" +
      //						"methodName is " + methodName + "\n" +
      //						"class is " + implClass.getName());

      if (method.getReturnType().getName().equals("void")) {
        try {
          op.addParameter("myMethod", method);
        } catch (AxisFault axisFault) {
          throw AxisFault.makeFault(axisFault);
        }
        return method;
      }

    } catch (Exception e) {
      throw AxisFault.makeFault(e);
    }

    if (logger.isDebugEnabled()) {
      logger.debug("return class is " + method.getReturnType().getName());
    }

    return null;
  }
コード例 #18
0
  private Method findOperation(AxisOperation op, Class implClass) {
    Method method = (Method) (op.getParameterValue("myMethod"));
    if (method != null && method.getDeclaringClass() == implClass) return method;

    String methodName = op.getName().getLocalPart();

    try {
      // Looking for a method of the form "OMElement method(OMElement)"
      method = implClass.getMethod(methodName, new Class[] {OMElement.class});
      if (method.getReturnType().equals(OMElement.class)) {
        try {
          op.addParameter("myMethod", method);
        } catch (AxisFault axisFault) {
          // Do nothing here
        }
        return method;
      }
    } catch (NoSuchMethodException e) {
      // Fault through
    }

    return null;
  }
コード例 #19
0
ファイル: ServiceBuilder.java プロジェクト: isuruw/wso2-axis2
  protected void processOperationModuleConfig(
      Iterator moduleConfigs, ParameterInclude parent, AxisOperation operation)
      throws DeploymentException {
    while (moduleConfigs.hasNext()) {
      OMElement moduleConfig = (OMElement) moduleConfigs.next();
      OMAttribute moduleName_att = moduleConfig.getAttribute(new QName(ATTRIBUTE_NAME));

      if (moduleName_att == null) {
        throw new DeploymentException(
            Messages.getMessage(DeploymentErrorMsgs.INVALID_MODULE_CONFIG));
      } else {
        String module = moduleName_att.getAttributeValue();
        ModuleConfiguration moduleConfiguration = new ModuleConfiguration(module, parent);
        Iterator parameters = moduleConfig.getChildrenWithName(new QName(TAG_PARAMETER));

        processParameters(parameters, moduleConfiguration, parent);
        operation.addModuleConfig(moduleConfiguration);
      }
    }
  }
コード例 #20
0
ファイル: ServiceBuilder.java プロジェクト: isuruw/wso2-axis2
  /**
   * Populates service from corresponding OM.
   *
   * @param service_element an OMElement for the &lt;service&gt; tag
   * @return a filled-in AxisService, configured from the passed XML
   * @throws DeploymentException if there is a problem
   */
  public AxisService populateService(OMElement service_element) throws DeploymentException {
    try {
      // Determine whether service should be activated.
      String serviceActivate = service_element.getAttributeValue(new QName(ATTRIBUTE_ACTIVATE));
      if (serviceActivate != null) {
        if ("true".equals(serviceActivate)) {
          service.setActive(true);
        } else if ("false".equals(serviceActivate)) {
          service.setActive(false);
        }
      }

      // Processing service level parameters
      OMAttribute serviceNameatt = service_element.getAttribute(new QName(ATTRIBUTE_NAME));

      // If the service name is explicitly specified in the services.xml
      // then use that as the service name
      if (serviceNameatt != null) {
        if (!"".equals(serviceNameatt.getAttributeValue().trim())) {
          AxisService wsdlService = wsdlServiceMap.get(serviceNameatt.getAttributeValue());
          if (wsdlService != null) {
            wsdlService.setClassLoader(service.getClassLoader());
            wsdlService.setParent(service.getAxisServiceGroup());
            service = wsdlService;
            service.setWsdlFound(true);
            service.setCustomWsdl(true);
          }
          service.setName(serviceNameatt.getAttributeValue());
          // To be on the safe side
          if (service.getDocumentation() == null) {
            service.setDocumentation(serviceNameatt.getAttributeValue());
          }
        }
      }

      Iterator itr = service_element.getChildrenWithName(new QName(TAG_PARAMETER));
      processParameters(itr, service, service.getParent());

      Parameter childFirstClassLoading =
          service.getParameter(Constants.Configuration.ENABLE_CHILD_FIRST_CLASS_LOADING);
      if (childFirstClassLoading != null) {
        ClassLoader cl = service.getClassLoader();
        if (cl instanceof DeploymentClassLoader) {
          DeploymentClassLoader deploymentClassLoader = (DeploymentClassLoader) cl;
          if (JavaUtils.isTrueExplicitly(childFirstClassLoading.getValue())) {
            deploymentClassLoader.setChildFirstClassLoading(true);
          } else if (JavaUtils.isFalseExplicitly(childFirstClassLoading.getValue())) {
            deploymentClassLoader.setChildFirstClassLoading(false);
          }
        }
      }

      // If multiple services in one service group have different values
      // for the PARENT_FIRST
      // parameter then the final value become the value specified by the
      // last service in the group
      // Parameter parameter =
      // service.getParameter(DeploymentClassLoader.PARENT_FIRST);
      // if (parameter !=null && "false".equals(parameter.getValue())) {
      // ClassLoader serviceClassLoader = service.getClassLoader();
      // ((DeploymentClassLoader)serviceClassLoader).setParentFirst(false);
      // }
      // process service description
      OMElement descriptionElement =
          service_element.getFirstChildWithName(new QName(TAG_DESCRIPTION));
      if (descriptionElement != null) {
        OMElement descriptionValue = descriptionElement.getFirstElement();
        if (descriptionValue != null) {
          service.setDocumentation(descriptionValue);
        } else {
          service.setDocumentation(descriptionElement.getText());
        }
      } else {
        serviceNameatt = service_element.getAttribute(new QName(ATTRIBUTE_NAME));

        if (serviceNameatt != null) {
          if (!"".equals(serviceNameatt.getAttributeValue().trim())
              && service.getDocumentation() == null) {
            service.setDocumentation(serviceNameatt.getAttributeValue());
          }
        }
      }

      if (service.getParameter("ServiceClass") == null) {
        log.debug("The Service " + service.getName() + " does not specify a Service Class");
      }

      // Process WS-Addressing flag attribute
      OMAttribute addressingRequiredatt =
          service_element.getAttribute(new QName(ATTRIBUTE_WSADDRESSING));
      if (addressingRequiredatt != null) {
        String addressingRequiredString = addressingRequiredatt.getAttributeValue();
        AddressingHelper.setAddressingRequirementParemeterValue(service, addressingRequiredString);
      }

      // Setting service target namespace if any
      OMAttribute targetNameSpace = service_element.getAttribute(new QName(TARGET_NAME_SPACE));

      if (targetNameSpace != null) {
        String nameSpeceVale = targetNameSpace.getAttributeValue();
        if (nameSpeceVale != null && !"".equals(nameSpeceVale)) {
          service.setTargetNamespace(nameSpeceVale);
        }
      } else {
        if (service.getTargetNamespace() == null || "".equals(service.getTargetNamespace())) {
          service.setTargetNamespace(Java2WSDLConstants.DEFAULT_TARGET_NAMESPACE);
        }
      }

      // Processing service lifecycle attribute
      OMAttribute serviceLifeCycleClass = service_element.getAttribute(new QName(TAG_CLASS_NAME));
      if (serviceLifeCycleClass != null) {
        String className = serviceLifeCycleClass.getAttributeValue();
        loadServiceLifeCycleClass(className);
      }
      // Setting schema namespece if any
      OMElement schemaElement = service_element.getFirstChildWithName(new QName(SCHEMA));
      if (schemaElement != null) {
        OMAttribute schemaNameSpace = schemaElement.getAttribute(new QName(SCHEMA_NAME_SPACE));
        if (schemaNameSpace != null) {
          String nameSpeceVale = schemaNameSpace.getAttributeValue();
          if (nameSpeceVale != null && !"".equals(nameSpeceVale)) {
            service.setSchemaTargetNamespace(nameSpeceVale);
          }
        }
        OMAttribute elementFormDefault =
            schemaElement.getAttribute(new QName(SCHEMA_ELEMENT_QUALIFIED));
        if (elementFormDefault != null) {
          String value = elementFormDefault.getAttributeValue();
          if ("true".equals(value)) {
            service.setElementFormDefault(true);
          } else if ("false".equals(value)) {
            service.setElementFormDefault(false);
          }
        }

        // package to namespace mapping. This will be an element that
        // maps pkg names to a namespace
        // when this is doing AxisService.getSchemaTargetNamespace will
        // be overridden
        // This will be <mapping/> with @namespace and @package
        Iterator mappingIterator = schemaElement.getChildrenWithName(new QName(MAPPING));
        if (mappingIterator != null) {
          Map<String, String> pkg2nsMap = new Hashtable<String, String>();
          while (mappingIterator.hasNext()) {
            OMElement mappingElement = (OMElement) mappingIterator.next();
            OMAttribute namespaceAttribute =
                mappingElement.getAttribute(new QName(ATTRIBUTE_NAMESPACE));
            OMAttribute packageAttribute =
                mappingElement.getAttribute(new QName(ATTRIBUTE_PACKAGE));
            if (namespaceAttribute != null && packageAttribute != null) {
              String namespaceAttributeValue = namespaceAttribute.getAttributeValue();
              String packageAttributeValue = packageAttribute.getAttributeValue();
              if (namespaceAttributeValue != null && packageAttributeValue != null) {
                pkg2nsMap.put(packageAttributeValue.trim(), namespaceAttributeValue.trim());
              } else {
                log.warn(
                    "Either value of @namespce or @packagename not available. Thus, generated will be selected.");
              }
            } else {
              log.warn(
                  "Either @namespce or @packagename not available. Thus, generated will be selected.");
            }
          }
          service.setP2nMap(pkg2nsMap);
        }
      }

      // processing Default Message receivers
      OMElement messageReceiver =
          service_element.getFirstChildWithName(new QName(TAG_MESSAGE_RECEIVERS));
      if (messageReceiver != null) {
        HashMap<String, MessageReceiver> mrs =
            processMessageReceivers(service.getClassLoader(), messageReceiver);
        for (Map.Entry<String, MessageReceiver> entry : mrs.entrySet()) {
          service.addMessageReceiver(entry.getKey(), entry.getValue());
        }
      }

      // Removing exclude operations
      OMElement excludeOperations =
          service_element.getFirstChildWithName(new QName(TAG_EXCLUDE_OPERATIONS));
      ArrayList<String> excludeops = null;
      if (excludeOperations != null) {
        excludeops = processExcludeOperations(excludeOperations);
      }
      if (excludeops == null) {
        excludeops = new ArrayList<String>();
      }
      Utils.addExcludeMethods(excludeops);

      // <schema targetNamespace="http://x.y.z"/>
      // setting the PolicyInclude
      // processing <wsp:Policy> .. </..> elements
      Iterator policyElements =
          service_element.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY));

      if (policyElements != null && policyElements.hasNext()) {
        processPolicyElements(policyElements, service.getPolicySubject());
      }

      // processing <wsp:PolicyReference> .. </..> elements
      Iterator policyRefElements =
          service_element.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY_REF));

      if (policyRefElements != null && policyRefElements.hasNext()) {
        processPolicyRefElements(policyRefElements, service.getPolicySubject());
      }

      // processing service scope
      String sessionScope = service_element.getAttributeValue(new QName(ATTRIBUTE_SCOPE));
      if (sessionScope != null) {
        service.setScope(sessionScope);
      }

      // processing service-wide modules which required to engage globally
      Iterator moduleRefs = service_element.getChildrenWithName(new QName(TAG_MODULE));

      processModuleRefs(moduleRefs);

      // processing transports
      OMElement transports = service_element.getFirstChildWithName(new QName(TAG_TRANSPORTS));
      if (transports != null) {
        Iterator transport_itr = transports.getChildrenWithName(new QName(TAG_TRANSPORT));
        ArrayList<String> trs = new ArrayList<String>();
        while (transport_itr.hasNext()) {
          OMElement trsEle = (OMElement) transport_itr.next();
          String transportName = trsEle.getText().trim();
          if (axisConfig.getTransportIn(transportName) == null) {
            log.warn(
                "Service [ "
                    + service.getName()
                    + "] is trying to expose in a transport : "
                    + transportName
                    + " and which is not available in Axis2");
          } else {
            trs.add(transportName);
          }
        }

        if (trs.isEmpty()) {
          throw new AxisFault(
              "Service ["
                  + service.getName()
                  + "] is trying expose in tranpsorts: "
                  + transports
                  + " and which is/are not available in Axis2");
        }
        service.setExposedTransports(trs);
      }
      // processing operations
      Iterator operationsIterator = service_element.getChildrenWithName(new QName(TAG_OPERATION));
      ArrayList ops = processOperations(operationsIterator);

      for (int i = 0; i < ops.size(); i++) {
        AxisOperation operationDesc = (AxisOperation) ops.get(i);
        ArrayList wsamappings = operationDesc.getWSAMappingList();
        if (wsamappings == null) {
          continue;
        }
        if (service.getOperation(operationDesc.getName()) == null) {
          service.addOperation(operationDesc);
        }
        for (int j = 0; j < wsamappings.size(); j++) {
          String mapping = (String) wsamappings.get(j);
          if (mapping.length() > 0) {
            service.mapActionToOperation(mapping, operationDesc);
          }
        }
      }
      String objectSupplierValue = (String) service.getParameterValue(TAG_OBJECT_SUPPLIER);
      if (objectSupplierValue != null) {
        loadObjectSupplierClass(objectSupplierValue);
      }
      // Set the default message receiver for the operations that were
      // not listed in the services.xml
      setDefaultMessageReceivers();
      Utils.processBeanPropertyExclude(service);
      if (!service.isUseUserWSDL()) {
        // Generating schema for the service if the impl class is Java
        if (!service.isWsdlFound()) {
          // trying to generate WSDL for the service using JAM and
          // Java reflection
          try {
            if (generateWsdl(service)) {
              Utils.fillAxisService(service, axisConfig, excludeops, null);
            } else {
              ArrayList nonRpcOperations = getNonRPCMethods(service);
              Utils.fillAxisService(service, axisConfig, excludeops, nonRpcOperations);
            }
          } catch (Exception e) {
            throw new DeploymentException(
                Messages.getMessage("errorinschemagen", e.getMessage()), e);
          }
        }
      }
      if (service.isCustomWsdl()) {
        OMElement mappingElement =
            service_element.getFirstChildWithName(new QName(TAG_PACKAGE2QNAME));
        if (mappingElement != null) {
          processTypeMappings(mappingElement);
        }
      }

      for (String opName : excludeops) {
        service.removeOperation(new QName(opName));
      }

      // Need to call the same logic towice
      setDefaultMessageReceivers();
      Iterator moduleConfigs = service_element.getChildrenWithName(new QName(TAG_MODULE_CONFIG));
      processServiceModuleConfig(moduleConfigs, service, service);

      // Loading Data Locator(s) configured
      OMElement dataLocatorElement =
          service_element.getFirstChildWithName(new QName(DRConstants.DATA_LOCATOR_ELEMENT));
      if (dataLocatorElement != null) {
        processDataLocatorConfig(dataLocatorElement, service);
      }

      processEndpoints(service);
      processPolicyAttachments(service_element, service);

    } catch (AxisFault axisFault) {
      throw new DeploymentException(axisFault);
    }

    startupServiceLifecycle();
    return service;
  }
コード例 #21
0
ファイル: ServiceBuilder.java プロジェクト: isuruw/wso2-axis2
  private ArrayList<AxisOperation> processOperations(Iterator operationsIterator) throws AxisFault {
    ArrayList<AxisOperation> operations = new ArrayList<AxisOperation>();
    while (operationsIterator.hasNext()) {
      OMElement operation = (OMElement) operationsIterator.next();
      // getting operation name
      OMAttribute op_name_att = operation.getAttribute(new QName(ATTRIBUTE_NAME));
      if (op_name_att == null) {
        throw new DeploymentException(
            Messages.getMessage(
                Messages.getMessage(DeploymentErrorMsgs.INVALID_OP, "operation name missing")));
      }

      // setting the MEP of the operation
      OMAttribute op_mep_att = operation.getAttribute(new QName(TAG_MEP));
      String mepurl = null;

      if (op_mep_att != null) {
        mepurl = op_mep_att.getAttributeValue();
      }

      String opname = op_name_att.getAttributeValue();
      AxisOperation op_descrip = null;

      // getting the namesapce from the attribute.
      OMAttribute operationNamespace = operation.getAttribute(new QName(ATTRIBUTE_NAMESPACE));
      if (operationNamespace != null) {
        String namespace = operationNamespace.getAttributeValue();
        op_descrip = service.getOperation(new QName(namespace, opname));
      }
      if (op_descrip == null) {
        op_descrip = service.getOperation(new QName(opname));
      }

      if (op_descrip == null) {
        op_descrip = service.getOperation(new QName(service.getTargetNamespace(), opname));
      }
      if (op_descrip == null) {
        if (mepurl == null) {
          // assumed MEP is in-out
          op_descrip = new InOutAxisOperation();
          op_descrip.setParent(service);

        } else {
          op_descrip = AxisOperationFactory.getOperationDescription(mepurl);
        }
        op_descrip.setName(new QName(opname));
        String MEP = op_descrip.getMessageExchangePattern();
        if (WSDL2Constants.MEP_URI_IN_ONLY.equals(MEP)
            || WSDL2Constants.MEP_URI_IN_OPTIONAL_OUT.equals(MEP)
            || WSDL2Constants.MEP_URI_OUT_OPTIONAL_IN.equals(MEP)
            || WSDL2Constants.MEP_URI_ROBUST_OUT_ONLY.equals(MEP)
            || WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(MEP)
            || WSDL2Constants.MEP_URI_IN_OUT.equals(MEP)) {
          AxisMessage inaxisMessage = op_descrip.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
          if (inaxisMessage != null) {
            inaxisMessage.setName(opname + Java2WSDLConstants.MESSAGE_SUFFIX);
          }
        }

        if (WSDL2Constants.MEP_URI_OUT_ONLY.equals(MEP)
            || WSDL2Constants.MEP_URI_OUT_OPTIONAL_IN.equals(MEP)
            || WSDL2Constants.MEP_URI_IN_OPTIONAL_OUT.equals(MEP)
            || WSDL2Constants.MEP_URI_ROBUST_OUT_ONLY.equals(MEP)
            || WSDL2Constants.MEP_URI_IN_OUT.equals(MEP)) {
          AxisMessage outAxisMessage = op_descrip.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
          if (outAxisMessage != null) {
            outAxisMessage.setName(opname + Java2WSDLConstants.RESPONSE);
          }
        }
      }

      // setting the PolicyInclude

      // processing <wsp:Policy> .. </..> elements
      Iterator policyElements = operation.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY));

      if (policyElements != null && policyElements.hasNext()) {
        processPolicyElements(policyElements, op_descrip.getPolicySubject());
      }

      // processing <wsp:PolicyReference> .. </..> elements
      Iterator policyRefElements =
          operation.getChildrenWithName(new QName(POLICY_NS_URI, TAG_POLICY_REF));

      if (policyRefElements != null && policyRefElements.hasNext()) {
        processPolicyRefElements(policyRefElements, op_descrip.getPolicySubject());
      }

      // Operation Parameters
      Iterator parameters = operation.getChildrenWithName(new QName(TAG_PARAMETER));
      processParameters(parameters, op_descrip, service);
      // To process wsamapping;
      processActionMappings(operation, op_descrip);

      // loading the message receivers
      OMElement receiverElement = operation.getFirstChildWithName(new QName(TAG_MESSAGE_RECEIVER));

      if (receiverElement != null) {
        MessageReceiver messageReceiver =
            loadMessageReceiver(service.getClassLoader(), receiverElement);

        op_descrip.setMessageReceiver(messageReceiver);
      } else {
        // setting default message receiver
        MessageReceiver msgReceiver =
            loadDefaultMessageReceiver(op_descrip.getMessageExchangePattern(), service);
        op_descrip.setMessageReceiver(msgReceiver);
      }

      // Process Module Refs
      Iterator modules = operation.getChildrenWithName(new QName(TAG_MODULE));

      processOperationModuleRefs(modules, op_descrip);

      // processing Messages
      Iterator messages = operation.getChildrenWithName(new QName(TAG_MESSAGE));

      processMessages(messages, op_descrip);

      // setting Operation phase
      if (axisConfig != null) {
        PhasesInfo info = axisConfig.getPhasesInfo();

        info.setOperationPhases(op_descrip);
      }
      Iterator moduleConfigs = operation.getChildrenWithName(new QName(TAG_MODULE_CONFIG));
      processOperationModuleConfig(moduleConfigs, op_descrip, op_descrip);
      // adding the operation
      operations.add(op_descrip);
    }
    return operations;
  }
  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);
    }
  }
コード例 #23
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);

      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);
    }
  }
コード例 #24
0
  @Override
  public Handler.InvocationResponse invoke(MessageContext messageContext) throws AxisFault {

    SystemStatisticsUtil systemStatisticsUtil;
    SystemStatistics systemStatistics;

    try {
      int tenantID = PublisherUtil.getTenantId(messageContext);
      Map<Integer, EventConfigNStreamDef> tenantSpecificEventConfig =
          TenantEventConfigData.getTenantSpecificEventingConfigData();
      EventConfigNStreamDef eventingConfigData = tenantSpecificEventConfig.get(tenantID);

      // Check service stats enable -- if true -- go
      if (eventingConfigData != null && eventingConfigData.isServiceStatsEnable()) {

        systemStatisticsUtil = StatisticsServiceComponent.getSystemStatisticsUtil();
        systemStatistics = systemStatisticsUtil.getSystemStatistics(messageContext);
        AxisOperation axisOperation = messageContext.getAxisOperation();

        AxisService axisService = messageContext.getAxisService();
        if (axisService == null
            || SystemFilter.isFilteredOutService(axisService.getAxisServiceGroup())
            || axisService.isClientSide()) {
          return Handler.InvocationResponse.CONTINUE;
        }

        MessageContext inMessageContext = MessageContext.getCurrentMessageContext();

        // If already set in the activity handlers get it or create new publish data
        /*
                        PublishData publishData = (PublishData) messageContext.getProperty(
                                BAMDataPublisherConstants.PUBLISH_DATA);

                        EventData eventData;
                        if (publishData != null) {
                            eventData = publishData.getEventData();
                        } else {
                            publishData = new PublishData();
                            eventData = new EventData();
                            Date date = new Date();
                            Timestamp timestamp = new Timestamp(date.getTime());
                            eventData.setTimestamp(timestamp);
                            if (axisOperation != null) {
                                eventData.setOperationName(axisOperation.getName().getLocalPart());
                            } else {
                                eventData.setOperationName(null);
                            }

                            if (axisService != null) {
                                eventData.setServiceName(messageContext.getAxisService().getName());
                            } else {
                                eventData.setServiceName(null);
                            }

                            //This is a hack for setting message id when sending request to a non-existing operation.
                            if (eventingConfigData.isMsgDumpingEnable() && axisService != null &&
                                axisOperation == null) {
                                eventData.setOutMessageId(new ActivityOutHandler().getUniqueId());
                            }

                        }
        */

        PublishData publishData = new PublishData();
        EventData eventData = new EventData();
        /*                Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        eventData.setTimestamp(timestamp);*/
        if (axisOperation != null) {
          eventData.setOperationName(axisOperation.getName().getLocalPart());
        } else {
          eventData.setOperationName(null);
        }

        if (axisService != null) {
          eventData.setServiceName(messageContext.getAxisService().getName());
        } else {
          eventData.setServiceName(null);
        }

        // This is a hack for setting message id when sending request to a non-existing operation.
        /*                if (eventingConfigData.isMsgDumpingEnable() && axisService != null &&
            axisOperation == null) {
            eventData.setOutMessageId(new ActivityOutHandler().getUniqueId());
        }*/

        // Skip resetting same info if already set by activity in/out handlers
        /*                if (!eventingConfigData.isMsgDumpingEnable()) {

            Timestamp timestamp = null;
            if (inMessageContext != null) {
                timestamp = new Timestamp(Long.parseLong(inMessageContext.getProperty(
                        StatisticsConstants.REQUEST_RECEIVED_TIME).toString()));
                Object requestProperty = inMessageContext.getProperty(
                        HTTPConstants.MC_HTTP_SERVLETREQUEST);
                ServiceAgentUtil.extractInfoFromHttpHeaders(eventData, requestProperty);
            } else {
                Date date = new Date();
                timestamp = new Timestamp(date.getTime());
            }

            eventData.setTimestamp(timestamp);

        }*/

        Timestamp timestamp = null;
        if (inMessageContext != null) {
          timestamp =
              new Timestamp(
                  Long.parseLong(
                      inMessageContext
                          .getProperty(StatisticsConstants.REQUEST_RECEIVED_TIME)
                          .toString()));
          Object requestProperty =
              inMessageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
          ServiceAgentUtil.extractInfoFromHttpHeaders(eventData, requestProperty);
        } else {
          Date date = new Date();
          timestamp = new Timestamp(date.getTime());
        }

        eventData.setTimestamp(timestamp);

        eventData.setSystemStatistics(systemStatistics);

        publishData.setEventData(eventData);

        // Skip if bam server info already set at activity handlers
        if (!eventingConfigData.isMsgDumpingEnable()) {
          BAMServerInfo bamServerInfo = ServiceAgentUtil.addBAMServerInfo(eventingConfigData);
          publishData.setBamServerInfo(bamServerInfo);
        }

        Event event = ServiceAgentUtil.makeEventList(publishData, eventingConfigData);
        EventPublisher publisher = new EventPublisher();
        publisher.publish(event, eventingConfigData);
      }
    } catch (Throwable ignore) {
      log.error(
          "Error at SystemStatisticsOutHandler. "
              + "But continuing message processing for message id: "
              + messageContext.getMessageID(),
          ignore);
    }

    return Handler.InvocationResponse.CONTINUE;
  }
コード例 #25
0
  /**
   * @param additionalSchemas
   * @throws RuntimeException
   */
  public static TypeMapper processSchemas(
      final List schemas, Element[] additionalSchemas, CodeGenConfiguration cgconfig)
      throws RuntimeException {
    try {

      // check for the imported types. Any imported types are supposed to be here also
      if (schemas == null || schemas.isEmpty()) {
        // there are no types to be code generated
        // However if the type mapper is left empty it will be a problem for the other
        // processes. Hence the default type mapper is set to the configuration
        return new DefaultTypeMapper();
      }

      final Map schemaToInputSourceMap = new HashMap();
      final Map<String, StringBuffer> publicIDToStringMap = new HashMap<String, StringBuffer>();

      // create the type mapper
      JavaTypeMapper mapper = new JavaTypeMapper();

      String baseURI = cgconfig.getBaseURI();
      if (!baseURI.endsWith("/")) {
        baseURI = baseURI + "/";
      }

      for (int i = 0; i < schemas.size(); i++) {
        XmlSchema schema = (XmlSchema) schemas.get(i);
        InputSource inputSource = new InputSource(new StringReader(getSchemaAsString(schema)));
        // here we have to set a proper system ID. otherwise when processing the
        // included schaemas for this schema we have a problem
        // it creates the system ID using this target namespace value

        inputSource.setSystemId(baseURI + "xsd" + i + ".xsd");
        inputSource.setPublicId(schema.getTargetNamespace());
        schemaToInputSourceMap.put(schema, inputSource);
      }

      File outputDir = new File(cgconfig.getOutputLocation(), "src");
      // outputDir.mkdir();
      createDir(outputDir);

      Map nsMap = cgconfig.getUri2PackageNameMap();
      EntityResolver resolver =
          new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException {
              InputSource returnInputSource = null;
              XmlSchema key = null;
              for (Iterator iter = schemaToInputSourceMap.keySet().iterator(); iter.hasNext(); ) {
                key = (XmlSchema) iter.next();
                String nsp = key.getTargetNamespace();
                if (nsp != null && nsp.equals(publicId)) {

                  // when returning the input stream we have to always return a new
                  // input stream.
                  // sinc jaxbri internally consumes the input stream it gives an
                  // exception.
                  returnInputSource = new InputSource(new StringReader(getSchemaAsString(key)));
                  InputSource existingInputSource = (InputSource) schemaToInputSourceMap.get(key);
                  returnInputSource.setSystemId(existingInputSource.getSystemId());
                  returnInputSource.setPublicId(existingInputSource.getPublicId());
                  break;
                }
              }
              if (returnInputSource == null) {
                // then we have to find this using the file system
                if (systemId != null) {
                  returnInputSource = new InputSource(systemId);
                  returnInputSource.setSystemId(systemId);
                }
              }

              if (returnInputSource == null) {
                if (publicId != null) {

                  if (!publicIDToStringMap.containsKey(publicId)) {
                    URL url = new URL(publicId);
                    BufferedReader bufferedReader =
                        new BufferedReader(new InputStreamReader(url.openStream()));
                    StringBuffer stringBuffer = new StringBuffer();
                    String str = null;
                    while ((str = bufferedReader.readLine()) != null) {
                      stringBuffer.append(str);
                    }
                    publicIDToStringMap.put(publicId, stringBuffer);
                  }

                  String schemaString = publicIDToStringMap.get(publicId).toString();
                  returnInputSource = new InputSource(new StringReader(schemaString));
                  returnInputSource.setPublicId(publicId);
                  returnInputSource.setSystemId(publicId);
                }
              }
              return returnInputSource;
            }
          };

      Map properties = cgconfig.getProperties();
      String bindingFileName = (String) properties.get(BINDING_FILE_NAME);

      XmlSchema key = null;
      for (Iterator schemaIter = schemaToInputSourceMap.keySet().iterator();
          schemaIter.hasNext(); ) {

        SchemaCompiler sc = XJC.createSchemaCompiler();
        if (bindingFileName != null) {
          if (bindingFileName.endsWith(".jar")) {
            scanEpisodeFile(new File(bindingFileName), sc);
          } else {
            InputSource inputSoruce = new InputSource(new FileInputStream(bindingFileName));
            inputSoruce.setSystemId(new File(bindingFileName).toURI().toString());
            sc.getOptions().addBindFile(inputSoruce);
          }
        }

        key = (XmlSchema) schemaIter.next();

        if (nsMap != null) {
          Iterator iterator = nsMap.entrySet().iterator();
          while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String namespace = (String) entry.getKey();
            String pkg = (String) nsMap.get(namespace);
            registerNamespace(sc, namespace, pkg);
          }
        }

        sc.setEntityResolver(resolver);

        sc.setErrorListener(
            new ErrorListener() {
              public void error(SAXParseException saxParseException) {
                log.error(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }

              public void fatalError(SAXParseException saxParseException) {
                log.error(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }

              public void warning(SAXParseException saxParseException) {
                log.warn(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }

              public void info(SAXParseException saxParseException) {
                log.info(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }
            });

        sc.parseSchema((InputSource) schemaToInputSourceMap.get(key));
        sc.getOptions().addGrammar((InputSource) schemaToInputSourceMap.get(key));

        for (Object property : properties.keySet()) {
          String propertyName = (String) property;
          if (propertyName.startsWith("X")) {
            String[] args = null;
            String propertyValue = (String) properties.get(property);
            if (propertyValue != null) {
              args = new String[] {"-" + propertyName, propertyValue};
            } else {
              args = new String[] {"-" + propertyName};
            }
            sc.getOptions().parseArguments(args);
          }
        }

        // Bind the XML
        S2JJAXBModel jaxbModel = sc.bind();

        if (jaxbModel == null) {
          throw new RuntimeException("Unable to generate code using jaxbri");
        }

        // Code change to sort Object factory classes start -SOA2.8
        sortGeneratedObjectFactoryClasses(jaxbModel);
        // Code change to sort Object factory classes end -SOA2.8

        // Emit the code artifacts
        JCodeModel codeModel = jaxbModel.generateCode(null, null);
        FileCodeWriter writer = new FileCodeWriter(outputDir);
        codeModel.build(writer);

        Collection mappings = jaxbModel.getMappings();

        Iterator iter = mappings.iterator();

        while (iter.hasNext()) {
          Mapping mapping = (Mapping) iter.next();
          QName qn = mapping.getElement();
          String typeName = mapping.getType().getTypeClass().fullName();

          mapper.addTypeMappingName(qn, typeName);
        }

        // process the unwrapped parameters
        if (!cgconfig.isParametersWrapped()) {
          // figure out the unwrapped operations
          List axisServices = cgconfig.getAxisServices();
          for (Iterator servicesIter = axisServices.iterator(); servicesIter.hasNext(); ) {
            AxisService axisService = (AxisService) servicesIter.next();
            for (Iterator operations = axisService.getOperations(); operations.hasNext(); ) {
              AxisOperation op = (AxisOperation) operations.next();

              if (WSDLUtil.isInputPresentForMEP(op.getMessageExchangePattern())) {
                AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
                if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) {

                  Mapping mapping = jaxbModel.get(message.getElementQName());
                  List elementProperties = mapping.getWrapperStyleDrilldown();
                  for (int j = 0; j < elementProperties.size(); j++) {
                    Property elementProperty = (Property) elementProperties.get(j);

                    QName partQName =
                        WSDLUtil.getPartQName(
                            op.getName().getLocalPart(),
                            WSDLConstants.INPUT_PART_QNAME_SUFFIX,
                            elementProperty.elementName().getLocalPart());
                    // this type is based on a primitive type- use the
                    // primitive type name in this case
                    String fullJaveName = elementProperty.type().fullName();
                    if (elementProperty.type().isArray()) {
                      fullJaveName = fullJaveName.concat("[]");
                    }
                    mapper.addTypeMappingName(partQName, fullJaveName);

                    if (elementProperty.type().isPrimitive()) {
                      mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                    }
                    if (elementProperty.type().isArray()) {
                      mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE);
                    }
                  }
                }
              }

              if (WSDLUtil.isOutputPresentForMEP(op.getMessageExchangePattern())) {
                AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) {

                  Mapping mapping = jaxbModel.get(message.getElementQName());
                  List elementProperties = mapping.getWrapperStyleDrilldown();
                  for (int j = 0; j < elementProperties.size(); j++) {
                    Property elementProperty = (Property) elementProperties.get(j);

                    QName partQName =
                        WSDLUtil.getPartQName(
                            op.getName().getLocalPart(),
                            WSDLConstants.OUTPUT_PART_QNAME_SUFFIX,
                            elementProperty.elementName().getLocalPart());
                    // this type is based on a primitive type- use the
                    // primitive type name in this case
                    String fullJaveName = elementProperty.type().fullName();
                    if (elementProperty.type().isArray()) {
                      fullJaveName = fullJaveName.concat("[]");
                    }
                    mapper.addTypeMappingName(partQName, fullJaveName);

                    if (elementProperty.type().isPrimitive()) {
                      mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                    }
                    if (elementProperty.type().isArray()) {
                      mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE);
                    }
                  }
                }
              }
            }
          }
        }
      }

      // Return the type mapper
      return mapper;

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
コード例 #26
0
  /**
   * Based on the Axis2 client code. Sends the Axis2 Message context out and returns the Axis2
   * message context for the response.
   *
   * <p>Here Synapse works as a Client to the service. It would expect 200 ok, 202 ok and 500
   * internal server error as possible responses.
   *
   * @param endpoint the endpoint being sent to, maybe null
   * @param synapseOutMessageContext the outgoing synapse message
   * @throws AxisFault on errors
   */
  public static void send(
      EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext)
      throws AxisFault {

    boolean separateListener = false;
    boolean wsSecurityEnabled = false;
    String wsSecPolicyKey = null;
    String inboundWsSecPolicyKey = null;
    String outboundWsSecPolicyKey = null;
    boolean wsRMEnabled = false;
    String wsRMPolicyKey = null;
    boolean wsAddressingEnabled = false;
    String wsAddressingVersion = null;

    if (endpoint != null) {
      separateListener = endpoint.isUseSeparateListener();
      wsSecurityEnabled = endpoint.isSecurityOn();
      wsSecPolicyKey = endpoint.getWsSecPolicyKey();
      inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey();
      outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey();
      wsRMEnabled = endpoint.isReliableMessagingOn();
      wsRMPolicyKey = endpoint.getWsRMPolicyKey();
      wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled;
      wsAddressingVersion = endpoint.getAddressingVersion();
    }

    if (log.isDebugEnabled()) {
      String to;
      if (endpoint != null && endpoint.getAddress() != null) {
        to = endpoint.getAddress(synapseOutMessageContext);
      } else {
        to = synapseOutMessageContext.getTo().toString();
      }

      log.debug(
          "Sending [add = "
              + wsAddressingEnabled
              + "] [sec = "
              + wsSecurityEnabled
              + "] [rm = "
              + wsRMEnabled
              + (endpoint != null
                  ? "] [mtom = "
                      + endpoint.isUseMTOM()
                      + "] [swa = "
                      + endpoint.isUseSwa()
                      + "] [format = "
                      + endpoint.getFormat()
                      + "] [force soap11="
                      + endpoint.isForceSOAP11()
                      + "] [force soap12="
                      + endpoint.isForceSOAP12()
                      + "] [pox="
                      + endpoint.isForcePOX()
                      + "] [get="
                      + endpoint.isForceGET()
                      + "] [encoding="
                      + endpoint.getCharSetEncoding()
                  : "")
              + "] [to="
              + to
              + "]");
    }

    // save the original message context without altering it, so we can tie the response
    MessageContext originalInMsgCtx =
        ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext();

    // TODO Temp hack: ESB removes the session id from request in a random manner.
    Map headers = (Map) originalInMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    String session = (String) synapseOutMessageContext.getProperty("LB_COOKIE_HEADER");
    if (session != null) {
      headers.put("Cookie", session);
    }

    // create a new MessageContext to be sent out as this should not corrupt the original
    // we need to create the response to the original message later on
    String preserveAddressingProperty =
        (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_WS_ADDRESSING);
    MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx, preserveAddressingProperty);

    if (log.isDebugEnabled()) {
      log.debug(
          "Message [Original Request Message ID : "
              + synapseOutMessageContext.getMessageID()
              + "]"
              + " [New Cloned Request Message ID : "
              + axisOutMsgCtx.getMessageID()
              + "]");
    }
    // set all the details of the endpoint only to the cloned message context
    // so that we can use the original message context for resending through different endpoints
    if (endpoint != null) {

      if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(true);
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
        axisOutMsgCtx.setProperty(
            Constants.Configuration.CONTENT_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);

        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE,
              org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
        }

      } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(true);
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET);
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_X_WWW_FORM);

      } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(false);
        axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        // We need to set this explicitly here in case the request was not a POST
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
        if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
          axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
        }
        if (!axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx);
        }
        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_TEXT_XML);
        }

      } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(false);
        axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        // We need to set this explicitly here in case the request was not a POST
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
        if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
          axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
        }
        if (axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx);
        }
        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE,
              org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
        }

      } else if (SynapseConstants.FORMAT_REST.equals(endpoint.getFormat())) {
        /*format=rest is kept only backword compatibility. We no longer needed that.*/
        /* Remove Message Type  for GET and DELETE Request */
        if (originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD) != null) {
          if (originalInMsgCtx
                  .getProperty(Constants.Configuration.HTTP_METHOD)
                  .toString()
                  .equals(Constants.Configuration.HTTP_METHOD_GET)
              || originalInMsgCtx
                  .getProperty(Constants.Configuration.HTTP_METHOD)
                  .toString()
                  .equals(Constants.Configuration.HTTP_METHOD_DELETE)) {
            axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
          }
        }
        axisOutMsgCtx.setDoingREST(true);
      } else {
        processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
      }

      if (endpoint.isUseMTOM()) {
        axisOutMsgCtx.setDoingMTOM(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
            org.apache.axis2.Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingMTOM(true);

      } else if (endpoint.isUseSwa()) {
        axisOutMsgCtx.setDoingSwA(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_SWA,
            org.apache.axis2.Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingSwA(true);
      }

      if (endpoint.getCharSetEncoding() != null) {
        axisOutMsgCtx.setProperty(
            Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding());
        // Need to Clean this up. TargetRequest line 176 contains a code block which over writes the
        // Content-Type returned by the message formatter with the Content-Type in
        // TRANSPORT_HEADERS. Because of that, even when
        // the Character set encoding is set by the message formatter, it will be replaced by the
        // Content-Type header in TRANSPORT_HEADERS.
        // So Im setting a property to check in TargetRequest before over writing the header.
        axisOutMsgCtx.setProperty("EndpointCharEncodingSet", "true");
      }

      // HTTP Endpoint : use the specified HTTP method and remove REST_URL_POSTFIX, it's not
      // supported in HTTP Endpoint
      if (endpoint.isHTTPEndpoint()) {
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD,
            synapseOutMessageContext.getProperty(Constants.Configuration.HTTP_METHOD));
        axisOutMsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
      }

      // add rest request' suffix URI
      String restSuffix = (String) axisOutMsgCtx.getProperty(NhttpConstants.REST_URL_POSTFIX);
      boolean isRest = SynapseConstants.FORMAT_REST.equals(endpoint.getFormat());

      if (!isRest && !endpoint.isForceSOAP11() && !endpoint.isForceSOAP12()) {
        isRest = isRequestRest(originalInMsgCtx);
      }

      if (endpoint.getAddress() != null) {
        String address = endpoint.getAddress(synapseOutMessageContext);
        if (isRest && restSuffix != null && !"".equals(restSuffix)) {

          String url;
          if (!address.endsWith("/")
              && !restSuffix.startsWith("/")
              && !restSuffix.startsWith("?")) {
            url = address + "/" + restSuffix;
          } else if (address.endsWith("/") && restSuffix.startsWith("/")) {
            url = address + restSuffix.substring(1);
          } else if (address.endsWith("/") && restSuffix.startsWith("?")) {
            url = address.substring(0, address.length() - 1) + restSuffix;
          } else {
            url = address + restSuffix;
          }
          axisOutMsgCtx.setTo(new EndpointReference(url));

        } else {
          axisOutMsgCtx.setTo(new EndpointReference(address));
        }
        axisOutMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, address);
        synapseOutMessageContext.setProperty(SynapseConstants.ENDPOINT_PREFIX, address);
      } else {
        // Supporting RESTful invocation
        if (isRest && restSuffix != null && !"".equals(restSuffix)) {
          EndpointReference epr = axisOutMsgCtx.getTo();
          if (epr != null) {
            String address = epr.getAddress();
            String url;
            if (!address.endsWith("/")
                && !restSuffix.startsWith("/")
                && !restSuffix.startsWith("?")) {
              url = address + "/" + restSuffix;
            } else {
              url = address + restSuffix;
            }
            axisOutMsgCtx.setTo(new EndpointReference(url));
          }
        }
      }

      if (endpoint.isUseSeparateListener()) {
        axisOutMsgCtx.getOptions().setUseSeparateListener(true);
      }
    } else {
      processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
    }

    // only put whttp:location for the REST (GET) requests, otherwise causes issues for POX messages
    if (axisOutMsgCtx.isDoingREST()
        && HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(
            axisOutMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE))) {
      if (axisOutMsgCtx.getProperty(WSDL2Constants.ATTR_WHTTP_LOCATION) == null
          && axisOutMsgCtx.getEnvelope().getBody().getFirstElement() != null) {
        axisOutMsgCtx.setProperty(
            WSDL2Constants.ATTR_WHTTP_LOCATION,
            axisOutMsgCtx.getEnvelope().getBody().getFirstElement().getQName().getLocalPart());
      }
    }

    if (wsAddressingEnabled) {

      if (wsAddressingVersion != null
          && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) {

        axisOutMsgCtx.setProperty(
            AddressingConstants.WS_ADDRESSING_VERSION,
            AddressingConstants.Submission.WSA_NAMESPACE);

      } else if (wsAddressingVersion != null
          && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) {

        axisOutMsgCtx.setProperty(
            AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE);
      }

      axisOutMsgCtx.setProperty(
          AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE);
    } else {
      axisOutMsgCtx.setProperty(
          AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
    }

    // remove the headers if we don't need to preserve them.
    // determine weather we need to preserve the processed headers
    String preserveHeaderProperty =
        (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_PROCESSED_HEADERS);
    if (preserveHeaderProperty == null || !Boolean.parseBoolean(preserveHeaderProperty)) {
      // default behaviour is to remove the headers
      MessageHelper.removeProcessedHeaders(
          axisOutMsgCtx,
          (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)));
    }

    ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext();
    AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration();

    AxisService anoymousService =
        AnonymousServiceFactory.getAnonymousService(
            synapseOutMessageContext.getConfiguration(),
            axisCfg,
            wsAddressingEnabled,
            wsRMEnabled,
            wsSecurityEnabled);
    // mark the anon services created to be used in the client side of synapse as hidden
    // from the server side of synapse point of view
    anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    ServiceGroupContext sgc =
        new ServiceGroupContext(axisCfgCtx, (AxisServiceGroup) anoymousService.getParent());
    ServiceContext serviceCtx = sgc.getServiceContext(anoymousService);

    boolean outOnlyMessage =
        "true".equals(synapseOutMessageContext.getProperty(SynapseConstants.OUT_ONLY));

    // get a reference to the DYNAMIC operation of the Anonymous Axis2 service
    AxisOperation axisAnonymousOperation =
        anoymousService.getOperation(
            outOnlyMessage
                ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION)
                : new QName(AnonymousServiceFactory.OUT_IN_OPERATION));

    Options clientOptions = MessageHelper.cloneOptions(originalInMsgCtx.getOptions());
    clientOptions.setUseSeparateListener(separateListener);
    // if RM is requested,
    if (wsRMEnabled) {
      // if a WS-RM policy is specified, use it
      if (wsRMPolicyKey != null) {
        Object property = synapseOutMessageContext.getEntry(wsRMPolicyKey);
        if (property instanceof OMElement) {
          OMElement policyOMElement = (OMElement) property;
          RMAssertionBuilder builder = new RMAssertionBuilder();
          SandeshaPolicyBean sandeshaPolicyBean =
              (SandeshaPolicyBean) builder.build(policyOMElement, null);
          Parameter policyParam =
              new Parameter(Sandesha2Constants.SANDESHA_PROPERTY_BEAN, sandeshaPolicyBean);
          anoymousService.addParameter(policyParam);
        }
      }
    }

    // if security is enabled,
    if (wsSecurityEnabled) {
      // if a WS-Sec policy is specified, use it
      if (wsSecPolicyKey != null) {
        clientOptions.setProperty(
            SynapseConstants.RAMPART_POLICY,
            MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey));
      } else {
        if (inboundWsSecPolicyKey != null) {
          clientOptions.setProperty(
              SynapseConstants.RAMPART_IN_POLICY,
              MessageHelper.getPolicy(synapseOutMessageContext, inboundWsSecPolicyKey));
        }
        if (outboundWsSecPolicyKey != null) {
          clientOptions.setProperty(
              SynapseConstants.RAMPART_OUT_POLICY,
              MessageHelper.getPolicy(synapseOutMessageContext, outboundWsSecPolicyKey));
        }
      }
      // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197
      if (axisOutMsgCtx.getEnvelope().getHeader() == null) {
        SOAPFactory fac =
            axisOutMsgCtx.isSOAP11()
                ? OMAbstractFactory.getSOAP11Factory()
                : OMAbstractFactory.getSOAP12Factory();
        fac.createSOAPHeader(axisOutMsgCtx.getEnvelope());
      }
    }

    OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions);
    mepClient.addMessageContext(axisOutMsgCtx);
    axisOutMsgCtx.setAxisMessage(
        axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));

    // set the SEND_TIMEOUT for transport sender
    if (endpoint != null && endpoint.getTimeoutDuration() > 0) {
      axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration());
    }

    // always set a callback as we decide if the send it blocking or non blocking within
    // the MEP client. This does not cause an overhead, as we simply create a 'holder'
    // object with a reference to the outgoing synapse message context
    // synapseOutMessageContext
    AsyncCallback callback = new AsyncCallback(axisOutMsgCtx, synapseOutMessageContext);
    if (!outOnlyMessage) {
      if (endpoint != null) {
        // set the timeout time and the timeout action to the callback, so that the
        // TimeoutHandler can detect timed out callbacks and take approprite action.
        callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration());
        callback.setTimeOutAction(endpoint.getTimeoutAction());
      } else {
        callback.setTimeOutOn(System.currentTimeMillis());
      }
    }
    mepClient.setCallback(callback);
    //
    //        if (Utils.isClientThreadNonBlockingPropertySet(axisOutMsgCtx)) {
    //            SynapseCallbackReceiver synapseCallbackReceiver = (SynapseCallbackReceiver)
    // axisOutMsgCtx.getAxisOperation().getMessageReceiver();
    //            synapseCallbackReceiver.addCallback(axisOutMsgCtx.getMessageID(), new
    // FaultCallback(axisOutMsgCtx, synapseOutMessageContext));
    //        }

    // this is a temporary fix for converting messages from HTTP 1.1 chunking to HTTP 1.0.
    // Without this HTTP transport can block & become unresponsive because we are streaming
    // HTTP 1.1 messages and HTTP 1.0 require the whole message to caculate the content length
    if (originalInMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
      synapseOutMessageContext.getEnvelope().toString();
    }

    // with the nio transport, this causes the listener not to write a 202
    // Accepted response, as this implies that Synapse does not yet know if
    // a 202 or 200 response would be written back.
    originalInMsgCtx
        .getOperationContext()
        .setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");

    // if the transport out is explicitly set use it
    Object o = originalInMsgCtx.getProperty("TRANSPORT_OUT_DESCRIPTION");
    if (o != null && o instanceof TransportOutDescription) {
      axisOutMsgCtx.setTransportOut((TransportOutDescription) o);
      clientOptions.setTransportOut((TransportOutDescription) o);
      clientOptions.setProperty("TRANSPORT_OUT_DESCRIPTION", o);
    }

    mepClient.execute(true);
    if (wsRMEnabled) {
      Object rm11 = clientOptions.getProperty(SandeshaClientConstants.RM_SPEC_VERSION);
      if ((rm11 != null) && rm11.equals(Sandesha2Constants.SPEC_VERSIONS.v1_1)) {
        ServiceClient serviceClient =
            new ServiceClient(
                axisOutMsgCtx.getConfigurationContext(), axisOutMsgCtx.getAxisService());
        serviceClient.setTargetEPR(
            new EndpointReference(endpoint.getAddress(synapseOutMessageContext)));
        serviceClient.setOptions(clientOptions);
        serviceClient
            .getOptions()
            .setTo(new EndpointReference(endpoint.getAddress(synapseOutMessageContext)));
        SandeshaClient.terminateSequence(serviceClient);
      }
    }
  }
コード例 #27
0
  /**
   * 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) throws AxisFault {

    Object obj = null;
    try {

      String in_action = msgContext.getWSAAction();

      if (logger.isDebugEnabled()) {
        logger.debug("In MEP: in_action = " + in_action);
      }

      validate_action(msgContext);

      // get the implementation class for the Web Service

      obj = getTheImplementationObject(msgContext);

      // make return message context available to service
      if (obj instanceof AppendixV) {
        AppendixV xo = (AppendixV) obj;
      }

    } catch (Exception e) {

      logger.error(
          "Error in XDSRawXMLIn:\n"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }

    // find the WebService method

    Class implClass = obj.getClass();

    AxisOperation opDesc = msgContext.getAxisOperation();

    Method method = findOperation(opDesc, implClass);

    Method methodDisplay;
    try {
      methodDisplay =
          implClass.getMethod("setMessageContextIn", new Class[] {MessageContext.class});
    } catch (SecurityException e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    } catch (NoSuchMethodException e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }

    try {
      methodDisplay.invoke(obj, new Object[] {msgContext});
    } catch (Exception e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }

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

    try {
      method.invoke(obj, new Object[] {msgContext.getEnvelope().getBody().getFirstElement()});

    } catch (Exception e) {
      logger.error(
          "Error in XDSRawXMLIn:\n"
              + "class is "
              + implClass.getName()
              + " method is setMessageContextIn"
              + ExceptionUtil.exception_details(e)
              + "\ngetSoapAction = "
              + msgContext.getSoapAction());

      throw AxisFault.makeFault(e);
    }
  }
コード例 #28
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);
    }
  }
コード例 #29
0
  /**
   * Loads a throttle metadata for a particular throttle type
   *
   * @param messageContext - The messageContext
   * @param throttleType - The type of throttle
   * @return IPBaseThrottleConfiguration - The IPBaseThrottleConfiguration - load from
   *     AxisConfiguration
   * @throws ThrottleException Throws if the throttle type is unsupported
   */
  public Throttle loadThrottle(MessageContext messageContext, int throttleType)
      throws ThrottleException {

    Throttle throttle = null;
    ConfigurationContext configContext = messageContext.getConfigurationContext();
    // the Parameter which hold throttle ipbase object
    // to get throttles map from the configuration context

    Map throttles = (Map) configContext.getPropertyNonReplicable(ThrottleConstants.THROTTLES_MAP);
    if (throttles == null) {
      if (debugOn) {
        log.debug("Couldn't find throttles object map .. thottlling will not be occurred ");
      }
      return null;
    }
    switch (throttleType) {
      case ThrottleConstants.GLOBAL_THROTTLE:
        {
          throttle = (Throttle) throttles.get(ThrottleConstants.GLOBAL_THROTTLE_KEY);
          break;
        }
      case ThrottleConstants.OPERATION_BASED_THROTTLE:
        {
          AxisOperation axisOperation = messageContext.getAxisOperation();
          if (axisOperation != null) {
            QName opName = axisOperation.getName();
            if (opName != null) {
              AxisService service = (AxisService) axisOperation.getParent();
              if (service != null) {
                String currentServiceName = service.getName();
                if (currentServiceName != null) {
                  throttle = (Throttle) throttles.get(currentServiceName + opName.getLocalPart());
                }
              }
            }
          } else {
            if (debugOn) {
              log.debug("Couldn't find axis operation ");
            }
            return null;
          }
          break;
        }
      case ThrottleConstants.SERVICE_BASED_THROTTLE:
        {
          AxisService axisService = messageContext.getAxisService();
          if (axisService != null) {
            throttle = (Throttle) throttles.get(axisService.getName());
          } else {
            if (debugOn) {
              log.debug("Couldn't find axis service ");
            }
            return null;
          }
          break;
        }
      default:
        {
          throw new ThrottleException("Unsupported Throttle type");
        }
    }
    return throttle;
  }