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 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;
  }
Esempio n. 3
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);
  }
Esempio n. 4
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;
  }
Esempio n. 5
0
  private void run() {
    try {
      loadConfigurations();

      // set the trust store as a system property for communication over
      // TLS.
      System.setProperty("javax.net.ssl.trustStore", keystorePath);
      System.setProperty("javax.net.ssl.trustStorePassword", keystorePwd);

      // create configuration context
      ConfigurationContext configCtx =
          ConfigurationContextFactory.createConfigurationContextFromFileSystem(repoPath);

      // create STS client
      STSClient stsClient = new STSClient(configCtx);
      stsClient.setRstTemplate(getRSTTemplate());

      String action = null;
      String responseTokenID = null;

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

      // request the security token from STS.
      Token responseToken;

      Policy stsPolicy = loadPolicy(stsPolicyPath);

      // add rampart config assertion to the ws-sec policies
      RampartConfig rampartConfig = buildRampartConfig();
      stsPolicy.addAssertion(rampartConfig);

      responseToken = stsClient.requestSecurityToken(null, stsEPR, stsPolicy, relyingPartyEPR);

      // store the obtained token in token store to be used in future
      // communication.
      TokenStorage store = TrustUtil.getTokenStore(configCtx);
      responseTokenID = responseToken.getId();
      store.add(responseToken);

      // print token
      System.out.println(responseToken.getToken().toString());
      // sending token renew request
      String renewedTokenID = null;
      if (enableRenewing) {
        System.out.println("Renewing " + tokenType);
        String TokenProfile = null;
        if (tokenType.equals(ClientConstants.SAML_TOKEN_TYPE_11)) {
          TokenProfile = RahasConstants.TOK_TYPE_SAML_10;
        } else if (tokenType.equals(ClientConstants.SAML_TOKEN_TYPE_20)) {
          TokenProfile = RahasConstants.TOK_TYPE_SAML_20;
        }

        stsClient.setRstTemplate(getRSTTemplate());
        boolean tokenRenewed =
            stsClient.renewToken(responseTokenID, TokenProfile, stsEPR, stsPolicy, store);
        System.out.println("tokenRenewed : " + tokenRenewed);

        Token renewedToken = store.getRenewedTokens()[0];
        renewedTokenID = renewedToken.getId();
        System.out.println("Renewed Token : \n" + renewedToken.getToken().toString());
      }
      // Validate the token
      if (enableValidateBinding) {
        // validating the token.
        stsClient = new STSClient(configCtx);
        action =
            TrustUtil.getActionValue(
                RahasConstants.VERSION_05_02, RahasConstants.RST_ACTION_VALIDATE);
        stsClient.setAction(action);
        String tokenID = null;
        if (renewedTokenID != null) {
          tokenID = renewedTokenID;
        } else {
          tokenID = responseTokenID;
        }
        boolean isValid = stsClient.validateToken(tokenID, stsEPR, stsPolicy);

        if (isValid) {
          if (enableRenewing) {
            System.out.println("Renewed SAML " + tokenType + " Token is valid");
          } else {
            System.out.println("Response SAML " + tokenType + " Token is valid");
          }
        } else {
          if (enableRenewing) {
            System.out.println("Renewed SAML " + tokenType + " Token is invalid");
          } else {
            System.out.println("Response SAML " + tokenType + " Token is invalid");
          }
        }
      }

      // Send the token to relying party
      if (enableRelyingParty) {
        /* Invoke secured service using the obtained token */
        OMElement responseElem = null;

        // create service client
        ServiceClient serClient = new ServiceClient(configCtx, null);

        // engage modules
        serClient.engageModule("addressing");
        serClient.engageModule("rampart");

        // load policy of secured service
        Policy sec_policy = loadPolicy(relyingPartyPolicyPath);

        // add rampart config to the ws-sec policies
        sec_policy.addAssertion(rampartConfig);

        // set in/out security policies in client opts
        serClient.getOptions().setProperty(RampartMessageData.KEY_RAMPART_POLICY, sec_policy);

        // Set the token id as a property in the Axis2 client scope, so
        // that this will be picked up when creating the secure message to
        // invoke
        // the endpoint.
        serClient
            .getOptions()
            .setProperty(RampartMessageData.KEY_CUSTOM_ISSUED_TOKEN, renewedTokenID);

        // set action of the Hello Service to be invoked.
        serClient.getOptions().setAction("urn:echoString");
        serClient.getOptions().setTo(new EndpointReference(relyingPartyEPR));

        // invoke the service
        // System.out.println(serClient.sendReceive(getPayload(echoRequestMsg)).toString());
        responseElem = serClient.sendReceive(getPayload(echoRequestMsg));
        // cleanup transports
        serClient.getOptions().setCallTransportCleanup(true);

        System.out.println(responseElem.toString());

        System.exit(0);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      System.exit(0);
    }
  }
  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;
  }
  /**
   * 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());
    }
  }