Пример #1
0
  private ServiceClient getServiceClient(String trpUrl, String addUrl, String operation)
      throws AxisFault {

    ServiceClient serviceClient;
    Options options = new Options();

    if (addUrl != null && !"null".equals(addUrl)) {
      serviceClient =
          new ServiceClient(
              ConfigurationContextProvider.getInstance().getConfigurationContext(), null);
      serviceClient.engageModule("addressing");
      options.setTo(new EndpointReference(addUrl));
    } else {
      // otherwise it will engage addressing all the time once addressing is engaged by
      // ConfigurationContext to service client
      serviceClient = new ServiceClient();
    }

    if (trpUrl != null && !"null".equals(trpUrl)) {
      options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }

    options.setAction("urn:" + operation);
    if (httpHeaders.size() > 0) {
      options.setProperty(HTTPConstants.HTTP_HEADERS, httpHeaders);
    }
    options.setTimeOutInMilliSeconds(45000);
    /*  options.setProperty(HTTPConstants.CHUNKED, Constants.VALUE_FALSE);
    options.setProperty(Constants.Configuration.MESSAGE_TYPE,HTTPConstants.MEDIA_TYPE_APPLICATION_ECHO_XML);
    options.setProperty(Constants.Configuration.DISABLE_SOAP_ACTION,Boolean.TRUE);*/
    serviceClient.setOptions(options);

    return serviceClient;
  }
  /**
   * Retrieve all entries from service.
   *
   * @return All entries of type Entry from the service.
   * @exception FailureFaultException If an error communication with the service occurs.
   */
  public Entry[] retrieve() throws FailureFaultException {
    final String method = "retrieve";
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace namespace = factory.createOMNamespace(SERVICE, method);

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

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

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

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

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

      // Parse and return result
      Entry[] result = XMLUtil.parseScores(response);
      return result;
    } catch (AxisFault e) {
      throw new FailureFaultException("Exception from service: ", e);
    }
  }
Пример #3
0
  private static boolean JARServiceTest() {
    boolean JARServiceStatus = false;
    OMElement result;
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = fac.createOMNamespace("http://ws.apache.org/axis2", "ns1");
    OMElement payload = fac.createOMElement("echo", omNs);
    OMElement value = fac.createOMElement("args0", omNs);
    value.addChild(fac.createOMText(value, "Hello-World"));
    payload.addChild(value);

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

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

      serviceclient.setOptions(opts);

      result = serviceclient.sendReceive(payload);

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

    } catch (AxisFault axisFault) {
      log.error("Jar service invocation failed:" + axisFault.getMessage());
      fail("Jar service invocation failed:" + axisFault.getMessage());
    }
    return JARServiceStatus;
  }
  public static OMElement sendReceive(
      OMElement payload, String endPointReference, String operation, String contentType)
      throws AxisFault {

    ServiceClient sender;
    Options options;
    OMElement response = null;
    if (log.isDebugEnabled()) {
      log.debug("Service Endpoint : " + endPointReference);
      log.debug("Service Operation : " + operation);
      log.debug("Payload : " + payload);
    }
    try {
      sender = new ServiceClient();
      options = new Options();
      options.setTo(new EndpointReference(endPointReference));
      options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
      options.setTimeOutInMilliSeconds(45000);
      options.setAction("urn:" + operation);
      options.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);
      options.setProperty(Constants.Configuration.MESSAGE_TYPE, contentType);
      sender.setOptions(options);

      response = sender.sendReceive(payload);
      if (log.isDebugEnabled()) {
        log.debug("Response Message : " + response);
      }
    } catch (AxisFault axisFault) {
      log.error(axisFault.getMessage());
      throw new AxisFault("AxisFault while getting response :" + axisFault.getMessage(), axisFault);
    }
    return response;
  }
Пример #5
0
  private static boolean axis2ServiceTest() {
    boolean axis2ServiceStatus = false;

    OMElement result;
    try {
      OMElement payload = createPayLoad();
      ServiceClient serviceclient = new ServiceClient();
      Options opts = new Options();

      opts.setTo(new EndpointReference(HTTP_APPSERVER_STRATOSLIVE_URL + "/Axis2Service"));
      opts.setAction("http://service.carbon.wso2.org/echoString");
      opts.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
      serviceclient.setOptions(opts);

      result = serviceclient.sendReceive(payload);

      if ((result.toString().indexOf("Hello World")) > 0) {
        axis2ServiceStatus = true;
      }
      assertTrue("Axis2Service invocation failed", axis2ServiceStatus);

    } catch (AxisFault axisFault) {
      log.error("Axis2Service invocation failed :" + axisFault.getMessage());
      fail("Axis2Service invocation failed :" + axisFault.getMessage());
    }

    return axis2ServiceStatus;
  }
  public void sendUsingMTOM(String fileName, String targetEPR) throws IOException {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
    OMElement payload = factory.createOMElement("uploadFileUsingMTOM", ns);
    OMElement request = factory.createOMElement("request", ns);
    OMElement image = factory.createOMElement("image", ns);

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

    ServiceClient serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference(targetEPR));
    options.setAction("urn:uploadFileUsingMTOM");
    options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
    options.setCallTransportCleanup(true);
    serviceClient.setOptions(options);
    OMElement response = serviceClient.sendReceive(payload);
    Assert.assertTrue(
        response
            .toString()
            .contains(
                "<m:testMTOM xmlns:m=\"http://services.samples/xsd\">"
                    + "<m:test1>testMTOM</m:test1></m:testMTOM>"));
  }
  /** @param args */
  public static void main(String[] args) throws org.apache.axis2.AxisFault {
    ServiceClient sc = new ServiceClient();

    Options opts = new Options(); // need to create soap option object for assign soap options.
    opts.setTo(new EndpointReference(args[0]));
    opts.setAction("urn:OP_Count"); // soap action field copied from the wsdl file
    sc.setOptions(opts);

    OMElement result = sc.sendReceive(CreatePayload());
    System.out.println(result);
  }
Пример #8
0
  public static MessageContext sendUsingSwA(String fileName, String targetEPR) throws IOException {

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

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

    MessageContext mc = new MessageContext();

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

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

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

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

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

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

    return response;
  }
Пример #9
0
  public static void transferFile(File file, String destinationFile) throws Exception {

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

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

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

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

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

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

    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element =
        body.getFirstElement()
            .getFirstChildWithName(
                new QName("http://service.soapwithattachments.sample", "return"));
    System.out.println(element.getText());
  }
Пример #10
0
  public static void main(String[] args) throws AxisFault {

    toEpr = args[0];

    Options options = new Options();
    options.setTo(new EndpointReference(toEpr));
    options.setAction("urn:add");
    options.setSoapVersionURI(Constants.URI_SOAP12_ENV);
    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    OMElement result = sender.sendReceive(getPayload());
    System.out.println(result);
  }
Пример #11
0
  @Test(
      groups = {"wso2.brs"},
      enabled = true)
  public void testAddProduct() throws XMLStreamException, AxisFault {
    ClientConnectionUtil.waitForPort(9763);
    ServiceClient serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference("http://localhost:9763/services/ShoppingService"));
    options.setAction("urn:addProduct");
    serviceClient.setOptions(options);

    serviceClient.sendRobust(createAddProductPayload());
  }
Пример #12
0
  public void testEchoXMLASync() throws Exception {
    OMElement payload = createPayload();
    Options clientOptions = new Options();
    clientOptions.setTo(targetEPR);
    clientOptions.setTransportInProtocol(Constants.TRANSPORT_HTTP);

    AxisCallback callback =
        new AxisCallback() {

          public void onMessage(MessageContext msgContext) {
            SOAPEnvelope envelope = msgContext.getEnvelope();

            OMElement data = (OMElement) envelope.getBody().getFirstElement().getFirstOMChild();
            compareWithCreatedOMText(data.getText());
            finish = true;
          }

          public void onFault(MessageContext msgContext) {
            SOAPEnvelope envelope = msgContext.getEnvelope();

            OMElement data = (OMElement) envelope.getBody().getFirstElement().getFirstOMChild();
            compareWithCreatedOMText(data.getText());
            finish = true;
          }

          public void onError(Exception e) {
            log.info(e.getMessage());
            finish = true;
          }

          public void onComplete() {}
        };

    ConfigurationContext configContext =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            TestingUtils.prefixBaseDirectory("target/test-resources/integrationRepo"), null);
    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(clientOptions);

    sender.sendReceiveNonBlocking(payload, callback);

    int index = 0;
    while (!finish) {
      Thread.sleep(1000);
      index++;
      if (index > 10) {
        throw new AxisFault("Server was shutdown as the async response take too long to complete");
      }
    }
  }
Пример #13
0
  @Test(
      groups = {"wso2.brs"},
      dependsOnMethods = {"testAddProduct"},
      enabled = false)
  public void testPurchase() throws XMLStreamException, AxisFault {
    ClientConnectionUtil.waitForPort(9763);
    ServiceClient serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference("http://localhost:9763/services/ShoppingService"));
    options.setAction("urn:purchase");
    serviceClient.setOptions(options);

    OMElement result = serviceClient.sendReceive(createPurchasePayload());
    assertNotNull(result, "Result cannot be null");
  }
  public static void main(String[] args) throws AxisFault {

    ConfigurationContext cc =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            args[0], args[1] + "/axis2.xml");
    OMElement payload = createPayLoad();
    ServiceClient serviceclient = new ServiceClient(cc, null);

    Options opts = new Options();
    opts.setTo(new EndpointReference(args[2] + "/RMProxy"));
    opts.setAction("urn:add");
    opts.setUseSeparateListener(true);
    opts.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);

    serviceclient.setOptions(opts);
    serviceclient.engageModule("Mercury");
    serviceclient.engageModule("addressing");

    for (int i = 0; i < 4; i++) {
      try {
        OMElement response = serviceclient.sendReceive(payload);
        System.out.println(response);
      } catch (RemoteException e) {
        e.printStackTrace();
      }

      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    // Setting the last message
    serviceclient.getOptions().setProperty("MercuryLastMessage", Constants.VALUE_TRUE);

    try {
      OMElement response = serviceclient.sendReceive(payload);
    } catch (RemoteException e) {
      e.printStackTrace();
    }

    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    cc.getListenerManager().stop();
  }
  private void sendRobust(String trpUrl, String symbol) throws AxisFault {
    ServiceClient sender;
    Options options;

    sender = new ServiceClient();
    options = new Options();
    options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
    options.setAction("urn:placeOrder");

    if (trpUrl != null && !"null".equals(trpUrl)) {
      options.setProperty(Constants.Configuration.TRANSPORT_URL, trpUrl);
    }

    sender.setOptions(options);

    sender.sendRobust(getPlaceOrderPayload(symbol));
  }
Пример #16
0
  public void testSoapOverUdpWithEchoService() throws Exception {
    Options options = new Options();
    options.setTo(new EndpointReference("udp://127.0.0.1:3333?contentType=text/xml+soap"));
    options.setAction(Constants.AXIS2_NAMESPACE_URI + "/echoOMElement");
    options.setUseSeparateListener(true);
    options.setTimeOutInMilliSeconds(Long.MAX_VALUE);

    ServiceClient serviceClient = new ServiceClient(getClientCfgCtx(), null);
    serviceClient.setOptions(options);
    // We need to set up the anonymous service Axis uses to get the response
    AxisService clientService = serviceClient.getServiceContext().getAxisService();
    clientService.addParameter(UDPConstants.PORT_KEY, 4444);
    clientService.addParameter(UDPConstants.CONTENT_TYPE_KEY, "text/xml+soap");
    OMElement response = serviceClient.sendReceive(createPayload());

    assertEchoResponse(response);
  }
Пример #17
0
  public static void main(String[] args) throws Exception {

    if (args.length != 3) {
      System.out.println("Usage: $java Client endpoint_address client_repo_path policy_xml_path");
    }

    ConfigurationContext ctx =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(args[1], null);

    STSClient stsClient = new STSClient(ctx);

    stsClient.setRstTemplate(getRSTTemplate());
    String action =
        TrustUtil.getActionValue(RahasConstants.VERSION_05_02, RahasConstants.RST_ACTION_ISSUE);
    stsClient.setAction(action);

    Token responseToken =
        stsClient.requestSecurityToken(
            loadPolicy("sample05/policy.xml"),
            "http://localhost:8080/axis2/services/STS",
            loadPolicy("sample05/sts_policy.xml"),
            null);

    System.out.println(
        "\n############################# Requested Token ###################################\n");
    System.out.println(responseToken.getToken().toString());

    TokenStorage store = TrustUtil.getTokenStore(ctx);
    store.add(responseToken);

    ServiceClient client = new ServiceClient(ctx, null);

    Options options = new Options();
    options.setAction("urn:echo");
    options.setTo(new EndpointReference(args[0]));
    options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("sample05/policy.xml"));
    options.setProperty(RampartMessageData.KEY_CUSTOM_ISSUED_TOKEN, responseToken.getId());
    client.setOptions(options);

    client.engageModule("addressing");
    client.engageModule("rampart");

    OMElement response = client.sendReceive(getPayload("Hello world1"));
    System.out.println("Response  : " + response);
  }
  /**
   * Sends multiple entries of type Entry to the service.
   *
   * @param entries The entries to send.
   * @return The responses.
   * @exception FailureFaultException If an error communication with the service occurs.
   */
  public String[] store(Entry[] entries) throws FailureFaultException {
    final String method = "store";

    // Create a request
    OMElement request = XMLUtil.createScoreElements("StoreRequest", method, entries);

    // Print debug if system property "debug.messages" is set.
    printDebug("REQUEST", request);

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

    // Create a client
    try {
      ServiceClient client = new ServiceClient();
      client.setOptions(options);
      // Could throw AxisFault
      OMElement response = client.sendReceive(request);

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

      // Return possible results from elements of type:
      // <xsd:element name="StoreResponse" type="tns:StoreResponseType"/>
      // StoreResponseType = <xsd:simpleType name="StoreResponseType"/>
      ArrayList<String> resultList = new ArrayList<String>();
      @SuppressWarnings("unchecked") // Doesn't support generics
      Iterator<OMElement> elementIterator = response.getChildElements();
      while (elementIterator.hasNext()) {
        OMElement ge = elementIterator.next();
        @SuppressWarnings("unchecked") // Doesn't support generics
        Iterator<OMElement> it = ge.getChildElements();
        String responseText = it.next().getText();
        resultList.add(responseText);
      }
      String[] result = new String[resultList.size()];
      resultList.toArray(result);
      return result;
    } catch (AxisFault e) {
      throw new FailureFaultException("Exception from service: ", e);
    }
  }
  @Test(
      groups = {"wso2.brs"},
      dependsOnMethods = {"uploadHealthCareService"})
  public void testRecommendDose() throws Exception {

    requestSender.waitForProcessDeployment(
        getContext().getContextUrls().getServiceUrl() + "/HealthCareService");
    serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(
        new EndpointReference(
            getContext().getContextUrls().getServiceUrl() + "/HealthCareService"));
    options.setAction("urn:recommendDose");
    serviceClient.setOptions(options);

    OMElement result = serviceClient.sendReceive(createPayload());
    assertNotNull(result, "Result cannot be null");
  }
Пример #20
0
  private static void executeService() throws IOException, SQLException, ParseException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.DATA);

    OMElement result;
    OMElement payload = createPayLoad();
    ServiceClient serviceclient = new ServiceClient();
    Options opts = new Options();
    opts.setTo(
        new EndpointReference(
            StatusMonitorConstants.DATA_HTTP
                + StatusMonitorAgentConstants.TENANT_SERVICES
                + authConfigBean.getTenant()
                + "/GSpreadSample"));
    opts.setAction("http://ws.wso2.org/dataservice/getCustomers");

    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.DATA_HOST, serviceID)) {
      serviceclient.setOptions(opts);
      try {
        result = serviceclient.sendReceive(payload);
        if (log.isDebugEnabled()) {
          log.debug(result);
        }

        if ((result.toString().indexOf("Signal Gift Stores")) > 0) {
          executeShoppingCartDSPlatformSample();

        } else {
          MySQLConnector.insertStats(serviceID, false);
          MySQLConnector.insertState(serviceID, false, "Service Invocation failed");
        }

      } catch (AxisFault e) {
        MySQLConnector.insertStats(serviceID, false);
        MySQLConnector.insertState(serviceID, false, e.getMessage());
        String msg = "Error in executing service for DSS Server client";
        log.warn(msg, e);
      } catch (NullPointerException e) {
        MySQLConnector.insertStats(serviceID, false);
        MySQLConnector.insertState(serviceID, false, e.getMessage());
        String msg = "NPE in executing the service for DSS client";
        log.warn(msg, e);
      }
    }
  }
Пример #21
0
  public static String sendREST(EndpointReference restEPR, String requestString) throws Exception {
    OMElement getPM = getPmPayLoad(requestString);

    Options options = new Options();
    log.debug(restEPR.toString());
    options.setTo(restEPR);
    options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

    options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
    options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(125000));
    options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(125000));

    ServiceClient sender = PmServiceClient.getServiceClient();
    sender.setOptions(options);

    OMElement result = sender.sendReceive(getPM);
    // String response = result.getFirstElement().toString();
    // return response;
    return result.toString();
  }
Пример #22
0
  private static OMElement sendRequest(
      String payloadStr, String action, EndpointReference targetEPR)
      throws XMLStreamException, AxisFault {
    OMElement payload = AXIOMUtil.stringToOM(payloadStr);
    Options options = new Options();
    options.setTo(targetEPR);
    options.setAction("urn:" + action); // since soapAction = ""

    // Blocking invocation
    ServiceClient sender = new ServiceClient();
    sender.setOptions(options);
    if (log.isDebugEnabled()) {
      log.debug("Request: " + payload.toString());
    }
    OMElement result = sender.sendReceive(payload);
    if (log.isDebugEnabled()) {
      log.debug("Response: " + payload.toString());
    }
    return result;
  }
Пример #23
0
  private void run() throws Exception {

    ConfigurationContext configurationContext = generateConfigContext();

    ServiceClient serviceClient = new ServiceClient(configurationContext, null);

    //		String replyAddress = serviceClient.getMyEPR(Constants.TRANSPORT_HTTP).getAddress() + "/" +
    // ServiceClient.ANON_OUT_ONLY_OP;
    String acksToAddress = serviceClient.getMyEPR(Constants.TRANSPORT_HTTP).getAddress();

    Options clientOptions = new Options();
    setUpOptions(clientOptions, acksToAddress);

    serviceClient.setOptions(clientOptions);

    serviceClient.fireAndForget(getPingOMBlock("ping1"));
    serviceClient.fireAndForget(getPingOMBlock("ping2"));
    serviceClient.fireAndForget(getPingOMBlock("ping3"));

    boolean complete = false;
    while (!complete) {
      SequenceReport sequenceReport = SandeshaClient.getOutgoingSequenceReport(serviceClient);
      if (sequenceReport != null && sequenceReport.getCompletedMessages().size() == 3)
        complete = true;
      else {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e1) {
          e1.printStackTrace();
        }
      }
    }

    SandeshaClient.terminateSequence(serviceClient);

    Thread.sleep(3000);

    configurationContext.getListenerManager().stop();
    serviceClient.cleanup();
  }
Пример #24
0
  public void testEchoXMLSync() throws Exception {
    for (int i = 0; i < 10; i++) {
      OMElement payload = createPayload();

      Options clientOptions = new Options();
      clientOptions.setTo(targetEPR);
      clientOptions.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
      clientOptions.setTransportInProtocol(Constants.TRANSPORT_HTTP);
      clientOptions.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);

      ConfigurationContext configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
      ServiceClient sender = new ServiceClient(configContext, null);
      sender.setOptions(clientOptions);

      OMElement result = sender.sendReceive(payload);

      OMElement data = (OMElement) result.getFirstOMChild();
      compareWithCreatedOMText(data.getText());
      log.info("" + i);
      UtilServer.unDeployClientService();
    }
  }
  /**
   * This method creates 3 soap envelopes for 3 different client based sessions. Then it randomly
   * choose one envelope for each iteration and send it to the ESB. ESB should be configured with
   * session affinity load balancer and the SampleClientInitiatedSession dispatcher. This will
   * output request number, session number and the server ID for each iteration. So it can be
   * observed that one session number always associated with one server ID.
   */
  private void sessionfullClient() {

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

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

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

    if (pPort != null) {
      try {

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

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

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

    try {

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

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

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

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

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

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

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

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

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

          SOAPEnvelope responseEnvelope = responseContext.getEnvelope();

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

    } catch (AxisFault axisFault) {
      System.out.println(axisFault.getMessage());
    }
  }
Пример #26
0
  private void run() throws Exception {

    if ("<SANDESHA2_HOME>".equals(SANDESHA2_HOME)) {
      System.out.println(
          "ERROR: Please set the directory you unzipped Sandesha2 as the first option.");
      return;
    }

    String axis2_xml = AXIS2_CLIENT_PATH + "client_axis2.xml";

    ConfigurationContext configContext =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(
            AXIS2_CLIENT_PATH, axis2_xml);

    ServiceClient serviceClient = new ServiceClient(configContext, null);

    Options clientOptions = new Options();

    clientOptions.setTo(new EndpointReference(toEPR));

    String acksTo =
        serviceClient.getMyEPR(Constants.TRANSPORT_HTTP).getAddress()
            + "/"
            + ServiceClient.ANON_OUT_IN_OP;
    clientOptions.setProperty(SandeshaClientConstants.AcksTo, acksTo);

    String sequenceKey = "sequence4";
    clientOptions.setProperty(SandeshaClientConstants.SEQUENCE_KEY, sequenceKey);

    clientOptions.setProperty(Configuration.TRANSPORT_URL, transportToEPR);

    //		clientOptions.setProperty(MessageContextConstants.CHUNKED,Constants.VALUE_FALSE);
    // //uncomment this to send messages without chunking.

    clientOptions.setSoapVersionURI(
        SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI); // uncomment this to send messages in SOAP 1.2

    //
    //	clientOptions.setProperty(SandeshaClient.RM_SPEC_VERSION,Sandesha2Constants.SPEC_VERSIONS.v1_1);  //uncomment this to send the messages according to the v1_1 spec.

    clientOptions.setProperty(
        AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE);
    clientOptions.setProperty(
        SandeshaClientConstants.OFFERED_SEQUENCE_ID,
        SandeshaUtil.getUUID()); // Uncomment this to offer a sequenceID for the incoming sequence.
    clientOptions.setAction("urn:wsrm:EchoString");

    // You must set the following two properties in the request-reply case.
    clientOptions.setTransportInProtocol(Constants.TRANSPORT_HTTP);
    clientOptions.setUseSeparateListener(true);

    serviceClient.setOptions(clientOptions);

    clientOptions.setTimeOutInMilliSeconds(40000);

    OMElement result = serviceClient.sendReceive(getEchoOMBlock("echo1", sequenceKey));
    showResult(result);

    result = serviceClient.sendReceive(getEchoOMBlock("echo2", sequenceKey));
    showResult(result);

    result = serviceClient.sendReceive(getEchoOMBlock("echo3", sequenceKey));
    showResult(result);

    result = serviceClient.sendReceive(getEchoOMBlock("echo4", sequenceKey));
    showResult(result);

    clientOptions.setProperty(SandeshaClientConstants.LAST_MESSAGE, "true");
    OMElement bodyElem = getEchoOMBlock("echo5", sequenceKey);

    result = serviceClient.sendReceive(bodyElem);
    showResult(result);

    Thread.sleep(4000);
  }
  /**
   * 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);
      }
    }
  }
Пример #28
0
  public OMElement runSecurityClient(
      int scenarioNo, String serviceName, String soapAction, String body) throws Exception {

    FrameworkSettings.getProperty();
    String clientRepo = null;
    String trustStore = null;
    String endpointHttpS = null;
    String endpointHttp = null;
    String securityPolicy = null;
    String clientKey = null;

    File filePath = new File("./");
    String relativePath = filePath.getCanonicalPath();
    File findFile =
        new File(
            relativePath + File.separator + "config" + File.separator + "framework.properties");
    if (!findFile.isFile()) {
      filePath = new File("./../");
      relativePath = filePath.getCanonicalPath();
    }

    /*Properties properties = new Properties();
    FileInputStream freader = new FileInputStream(relativePath + File.separator + "proxyservices" + File.separator + "src" + File.separator + "test" + File.separator + "resources"+ File.separator + "ClientSecurityFiles" + File.separator + "client.properties");
    properties.load(freader);*/
    if (FrameworkSettings.STRATOS.equalsIgnoreCase("true")) {
      clientRepo =
          FrameworkSettings.TEST_FRAMEWORK_HOME
              + File.separator
              + "lib"
              + File.separator
              + "stratos-artifacts"
              + File.separator
              + "client_repo";
      endpointHttpS =
          "https://"
              + FrameworkSettings.HOST_NAME
              + ":"
              + FrameworkSettings.HTTPS_PORT
              + "/services/"
              + FrameworkSettings.TENANT_NAME
              + "/"
              + serviceName;
      endpointHttp =
          "http://"
              + FrameworkSettings.HOST_NAME
              + ":"
              + FrameworkSettings.HTTP_PORT
              + "/services/"
              + FrameworkSettings.TENANT_NAME
              + "/"
              + serviceName;
      clientKey =
          FrameworkSettings.TEST_FRAMEWORK_HOME
              + File.separator
              + "lib"
              + File.separator
              + "stratos-artifacts"
              + File.separator
              + "wso2carbon.jks";
      trustStore =
          FrameworkSettings.TEST_FRAMEWORK_HOME
              + File.separator
              + "lib"
              + File.separator
              + "stratos-artifacts"
              + File.separator
              + "wso2carbon.jks";
      securityPolicy =
          relativePath
              + File.separator
              + "proxyservices"
              + File.separator
              + "src"
              + File.separator
              + "test"
              + File.separator
              + "resources"
              + File.separator
              + "ClientSecurityFiles";

    } else if (FrameworkSettings.STRATOS.equalsIgnoreCase("false")) {
      clientRepo =
          FrameworkSettings.CARBON_HOME
              + File.separator
              + "samples"
              + File.separator
              + "axis2Client"
              + File.separator
              + "client_repo";
      endpointHttpS =
          "https://"
              + FrameworkSettings.HOST_NAME
              + ":"
              + FrameworkSettings.HTTPS_PORT
              + "/services/"
              + serviceName;
      endpointHttp =
          "http://"
              + FrameworkSettings.HOST_NAME
              + ":"
              + FrameworkSettings.HTTP_PORT
              + "/services/"
              + serviceName;
      clientKey =
          FrameworkSettings.CARBON_HOME
              + File.separator
              + "resources"
              + File.separator
              + "security"
              + File.separator
              + "wso2carbon.jks";
      trustStore =
          FrameworkSettings.CARBON_HOME
              + File.separator
              + "resources"
              + File.separator
              + "security"
              + File.separator
              + "wso2carbon.jks";
      securityPolicy =
          relativePath
              + File.separator
              + "proxyservices"
              + File.separator
              + "src"
              + File.separator
              + "test"
              + File.separator
              + "resources"
              + File.separator
              + "ClientSecurityFiles";
    }
    OMElement result;

    System.setProperty("javax.net.ssl.trustStore", trustStore);
    System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");

    ConfigurationContext ctx =
        ConfigurationContextFactory.createConfigurationContextFromFileSystem(clientRepo, null);
    ServiceClient sc = new ServiceClient(ctx, null);
    sc.engageModule("rampart");
    sc.engageModule("addressing");

    Options opts = new Options();

    if (scenarioNo == 1) {
      opts.setTo(new EndpointReference(endpointHttpS));
    } else {
      opts.setTo(new EndpointReference(endpointHttp));
    }

    opts.setAction(soapAction);

    if (scenarioNo != 0) {
      try {
        String securityPolicyPath =
            securityPolicy + File.separator + "scenario" + scenarioNo + "-policy.xml";
        opts.setProperty(
            RampartMessageData.KEY_RAMPART_POLICY, loadPolicy(securityPolicyPath, clientKey));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    sc.setOptions(opts);
    result = sc.sendReceive(AXIOMUtil.stringToOM(body));
    System.out.println(result.getFirstElement().getText());
    return result;
  }
  public String sessionlessClient() throws AxisFault {

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

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

    String sleep = getProperty("sleep", null);

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

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

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

    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMElement value = fac.createOMElement("Value", null);
    value.setText("Sample string");

    Options options = new Options();
    options.setTo(
        new EndpointReference("http://localhost:" + synapsePort + "/services/LBService1"));

    options.setAction("urn:sampleOperation");

    String repo = System.getProperty("repository");
    ConfigurationContext configContext;
    if (repo != null) {
      configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(
              repo, repo + File.separator + "conf" + File.separator + "axis2.xml");
    } else {
      configContext =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem("client_repo", null);
    }
    ServiceClient client = new ServiceClient(configContext, null);
    long timeout = Integer.parseInt(getProperty("timeout", "10000000"));
    System.out.println("timeout=" + timeout);
    options.setTimeOutInMilliSeconds(timeout);

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

    client.setOptions(options);
    String testString = "";

    long i = 0;
    while (i < iterations || infinite) {

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

      client.getOptions().setManageSession(true);
      OMElement responseElement = client.sendReceive(value);
      String response = responseElement.getText();

      i++;
      System.out.println("Request: " + i + " ==> " + response);
      testString += (":" + i + ">" + response + ":");
    }

    return testString;
  }
Пример #30
0
  /*
   * 获取某个项目一天之类的所有订单
   */
  public static void getBusinessOrderList(
      String modulename,
      Connection conn,
      Hashtable htwsinfo,
      String grouponid,
      Date starttime,
      Date endtime)
      throws JException {
    OMFactory soapFactory = OMAbstractFactory.getOMFactory();
    OMNamespace omNs = soapFactory.createOMNamespace(htwsinfo.get("namespace").toString(), "");
    OMElement soapResponse = soapFactory.createOMElement("groupon", omNs);
    DisneyRequestBean requestBean = new DisneyRequestBean();
    String s = (new StringBuilder(String.valueOf(System.currentTimeMillis()))).toString();
    requestBean.setRequest_time(s);
    requestBean.setSign(
        MD5Util.MD5Encode(
            (new StringBuilder(grouponid))
                .append(s)
                .append(htwsinfo.get("key").toString())
                .toString()));
    requestBean.setGrouponid(grouponid);
    requestBean.setLimit(htwsinfo.get("limit").toString());
    requestBean.setTotal(htwsinfo.get("total").toString());

    requestBean.setStartTime(String.valueOf(starttime.getTime())); // 增加一秒
    requestBean.setEndTime(String.valueOf(endtime.getTime())); // 增加一天
    soapResponse.addChild(ObjBodyWriter.convertBeanToXml(requestBean, "request"));
    Options options = new Options();
    options.setTo(new EndpointReference(htwsinfo.get("wsurl").toString()));
    options.setAction("getBusinessProjectList");
    options.setProperty("__CHUNKED__", Boolean.valueOf(false));
    ServiceClient sender = null;
    try {
      sender = new ServiceClient();
      sender.setOptions(options);
      OMElement result = sender.sendReceive(soapResponse);

      Document doc = DOMHelper.newDocument(result.toString(), htwsinfo.get("encoding").toString());
      Element urlset = doc.getDocumentElement();
      NodeList orderinfonodes = urlset.getElementsByTagName("order_info");
      if (orderinfonodes.getLength() > 0) {
        for (int i = 0; i < orderinfonodes.getLength(); i++) {

          Element orderinfoelement = (Element) orderinfonodes.item(i);
          Order o = OrderUtils.getOrder(orderinfoelement);
          String orderid = o.getOrderId();
          String status = o.getStatus();
          String sku = o.getSKU();
          long qty = Long.valueOf(o.getBuyNum());
          Date updatetime = Formatter.parseDate(o.getPaymentTime(), Formatter.DATE_TIME_FORMAT);

          /*
           *1、如果状态为等待卖家发货则生成接口订单
           *2、删除等待买家付款时的锁定库存
           */
          Log.info(o.getOrderId() + " " + o.getStatus() + " " + o.getPaymentTime());
          if (status.equals("1")) {
            // 即使取订单时不需要判断订单是否存在,每天检查订单时需检查订单是否已经存在
            if (htwsinfo.get("style").toString().equals("0")) {
              try {
                createInterOrder(
                    conn,
                    htwsinfo.get("tradecontactid").toString(),
                    htwsinfo.get("username").toString(),
                    o);
                StockManager.deleteWaitPayStock(
                    modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku);
              } catch (SQLException sqle) {
                throw new JException("生成接口订单出错!" + sqle.getMessage());
              }
            } else {
              if (!OrderManager.TidExists("检查团宝未入订单", conn, String.valueOf(o.getOrderId()))) {
                if (OrderManager.TidIntfExists("检查团宝未入订单", conn, String.valueOf(o.getOrderId()))) {
                  Log.info(
                      "接口中存在,客户订单中不存在:"
                          + o.getOrderId()
                          + " "
                          + o.getStatus()
                          + " "
                          + o.getPaymentTime());
                } else {
                  Log.info(
                      "接口中不存在,客户订单中不存在:"
                          + o.getOrderId()
                          + " "
                          + o.getStatus()
                          + " "
                          + o.getPaymentTime());
                }
                try {
                  createInterOrder(
                      conn,
                      htwsinfo.get("tradecontactid").toString(),
                      htwsinfo.get("username").toString(),
                      o);
                  StockManager.deleteWaitPayStock(
                      modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku);
                } catch (SQLException sqle) {
                  throw new JException("生成接口订单出错!" + sqle.getMessage());
                }
              }
            }
          }
          // 等待买家付款时记录锁定库存
          else if (status.equals("0")) {
            StockManager.addWaitPayStock(
                modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku, qty);
            StockManager.addSynReduceStore(
                modulename,
                conn,
                htwsinfo.get("tradecontactid").toString(),
                status,
                orderid,
                sku,
                -qty,
                false);
            // 付款以后用户退款成功,交易自动关闭
            // 释放库存,数量为正数
          } else if (status.equals("6")) {
            StockManager.addSynReduceStore(
                modulename,
                conn,
                htwsinfo.get("tradecontactid").toString(),
                status,
                orderid,
                sku,
                qty,
                false);
            // 付款以前,卖家或买家主动关闭交易
            // 释放等待买家付款时锁定的库存
          } else if (status.equals("4")) {
            StockManager.deleteWaitPayStock(
                modulename, conn, htwsinfo.get("tradecontactid").toString(), orderid, sku);
            StockManager.addSynReduceStore(
                modulename,
                conn,
                htwsinfo.get("tradecontactid").toString(),
                status,
                orderid,
                sku,
                qty,
                false);
          }

          // 更新同步订单最新时间
          if (updatetime.compareTo(
                  Formatter.parseDate(
                      PublicUtils.getConfig(conn, htwsinfo.get("lasttimeconfvalue").toString(), ""),
                      Formatter.DATE_TIME_FORMAT))
              > 0)
            PublicUtils.setConfig(
                conn,
                htwsinfo.get("lasttimeconfvalue").toString(),
                Formatter.format(updatetime, Formatter.DATE_TIME_FORMAT));
        }
      } else {
        try {
          // 如该段时间之内都取不到订单,而且当前天大于配置天,则将取订单最新时间更新为当前天的零点
          if (dateformat
                  .parse(Formatter.format(new Date(), Formatter.DATE_FORMAT))
                  .compareTo(
                      dateformat.parse(
                          Formatter.format(
                              Formatter.parseDate(
                                  PublicUtils.getConfig(
                                      conn, htwsinfo.get("lasttimeconfvalue").toString(), ""),
                                  Formatter.DATE_TIME_FORMAT),
                              Formatter.DATE_FORMAT)))
              > 0) {

            PublicUtils.setConfig(
                conn,
                htwsinfo.get("lasttimeconfvalue").toString(),
                Formatter.format(
                        (new Date(
                            Formatter.parseDate(
                                        PublicUtils.getConfig(
                                            conn, htwsinfo.get("lasttimeconfvalue").toString(), ""),
                                        Formatter.DATE_TIME_FORMAT)
                                    .getTime()
                                + daymillis)),
                        Formatter.DATE_FORMAT)
                    + " 00:00:00");
          }
        } catch (ParseException e) {
          throw new JException("不可用的日期格式!" + e.getMessage());
        }
      }

    } catch (JException ja) {
      Log.error(modulename, ja.getMessage());
    } catch (AxisFault af) {
      throw new JException("访问远程服务出错!" + af.getMessage());
    } catch (Exception e) {
      throw new JException("解析XML出错!" + e.getMessage());
    }
  }