@Test
  public void testJsonObjectInList() throws Exception {
    ModelNode description = createDescription(ModelType.LIST, ModelType.OBJECT);

    TypeConverter converter = getConverter(description);

    ArrayType<String> arrayType = assertCast(ArrayType.class, converter.getOpenType());
    Assert.assertEquals(
        SimpleType.STRING, assertCast(SimpleType.class, arrayType.getElementOpenType()));

    ModelNode list = new ModelNode();
    ModelNode value1 = new ModelNode();
    value1.get("long").set(5L);
    value1.get("string").set("Value");
    value1.get("a", "b").set(true);
    value1.get("c", "d").set(40);
    list.add(value1);
    ModelNode value2 = new ModelNode();
    value2.get("long").set(10L);
    list.add(value2);

    String json1 = value1.toJSONString(false);
    String json2 = value2.toJSONString(false);
    String[] data = assertCast(String[].class, converter.fromModelNode(list));
    Assert.assertEquals(2, data.length);
    Assert.assertEquals(json1, data[0]);
    Assert.assertEquals(json2, data[1]);

    Assert.assertEquals(
        ModelNode.fromJSONString(list.toJSONString(false)), converter.toModelNode(data));
  }
 protected static void executeWithFailure(ModelControllerClient client, ModelNode operation)
     throws IOException {
   ModelNode result = client.execute(operation);
   assertEquals(result.toJSONString(true), FAILED, result.get(OUTCOME).asString());
   assertTrue(
       result.toJSONString(true),
       result.get(FAILURE_DESCRIPTION).asString().contains("WFLYMSGAMQ0066"));
   assertFalse(result.has(RESULT));
 }
  @Test
  public void testJson() throws Exception {
    ModelNode node = new ModelNode();
    node.get("realm").set("demo");
    node.get("resource").set("customer-portal");
    node.get("realm-public-key")
        .set(
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB");
    node.get("auth-url")
        .set("http://localhost:8080/auth-server/rest/realms/demo/protocol/openid-connect/login");
    node.get("code-url")
        .set(
            "http://localhost:8080/auth-server/rest/realms/demo/protocol/openid-connect/access/codes");
    node.get("ssl-required").set("external");
    node.get("expose-token").set(true);

    ModelNode jwtCredential = new ModelNode();
    jwtCredential.get("client-keystore-file").set("/tmp/keystore.jks");
    jwtCredential.get("client-keystore-password").set("changeit");
    ModelNode credential = new ModelNode();
    credential.get("jwt").set(jwtCredential);
    node.get("credentials").set(credential);

    System.out.println("json=" + node.toJSONString(false));
  }
  @Test
  public void testJsonObjectInComplexValue() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT);
    ModelNode complexValueType = new ModelNode();
    complexValueType.get("value", DESCRIPTION).set("A  value");
    complexValueType.get("value", TYPE).set(ModelType.OBJECT);
    description.get(VALUE_TYPE).set(complexValueType);

    TypeConverter converter = getConverter(description);

    CompositeType type = assertCast(CompositeType.class, converter.getOpenType());
    Set<String> keys = type.keySet();
    Assert.assertEquals(1, keys.size());

    Assert.assertEquals(SimpleType.STRING, type.getType("value"));

    ModelNode node = new ModelNode();
    node.get("value", "long").set(1L);
    node.get("value", "string").set("test");

    CompositeData data = assertCast(CompositeData.class, converter.fromModelNode(node));
    Assert.assertEquals(type, data.getCompositeType());
    Assert.assertEquals(
        ModelNode.fromJSONString(node.toJSONString(false)), converter.toModelNode(data));
  }
 private ContentBody getOperationBody(final ModelNode operation, final boolean encoded)
     throws IOException {
   if (encoded) {
     return new DMRContentEncodedBody(operation);
   } else {
     return new StringBody(operation.toJSONString(true));
   }
 }
  private void writeRemoveRequest(BufferedOutputStream os) throws IOException {

    ModelNode op = new ModelNode();
    op.get("operation").set("remove");
    op.get("address").add("deployment", "test-http-deployment.sar");

    os.write(op.toJSONString(true).getBytes());
    os.flush();
  }
  @Test
  @InSequence(1)
  public void testModClusterAdd() throws Exception {
    final CommandContext ctx = CLITestUtil.getCommandContext();
    final ModelControllerClient controllerClient = managementClient.getControllerClient();

    try {
      ctx.connectController();

      // Add the mod_cluster extension first (not in this profile by default)
      ModelNode request = ctx.buildRequest("/extension=org.wildfly.extension.mod_cluster:add");
      ModelNode response = controllerClient.execute(request);
      String outcome = response.get("outcome").asString();
      Assert.assertEquals(
          "Adding mod_cluster extension failed! " + request.toJSONString(false),
          "success",
          outcome);

      // Now lets execute subsystem add operation but we need to specify a connector
      ctx.getBatchManager().activateNewBatch();
      Batch b = ctx.getBatchManager().getActiveBatch();
      b.add(
          ctx.toBatchedCommand(
              "/socket-binding-group=standard-sockets/socket-binding=mod_cluster:add(multicast-port=23364, multicast-address=224.0.1.105)"));
      b.add(ctx.toBatchedCommand("/subsystem=modcluster:add"));
      b.add(
          ctx.toBatchedCommand(
              "/subsystem=modcluster/mod-cluster-config=configuration:add(connector=http,advertise-socket=mod_cluster)"));
      request = b.toRequest();
      b.clear();
      ctx.getBatchManager().discardActiveBatch();

      response = controllerClient.execute(request);
      outcome = response.get("outcome").asString();
      Assert.assertEquals(
          "Adding mod_cluster subsystem failed! " + request.toJSONString(false),
          "success",
          outcome);
    } finally {
      ctx.terminateSession();
    }
  }
  private void writeAddRequest(BufferedOutputStream os, byte[] hash) throws IOException {

    ModelNode op = new ModelNode();
    op.get("operation").set("add");
    op.get("address").add("deployment", "test-http-deployment.sar");
    op.get("content").get(0).get("hash").set(hash);
    op.get("enabled").set(true);

    os.write(op.toJSONString(true).getBytes());
    os.flush();
  }
  @Test
  @InSequence(2)
  public void testModClusterRemove() throws Exception {
    final CommandContext ctx = CLITestUtil.getCommandContext();
    final ModelControllerClient controllerClient = managementClient.getControllerClient();

    try {
      ctx.connectController();

      // Test subsystem remove
      ModelNode request = ctx.buildRequest("/subsystem=modcluster:remove");
      ModelNode response = controllerClient.execute(request);
      String outcome = response.get("outcome").asString();
      Assert.assertEquals(
          "Removing mod_cluster subsystem failed! " + request.toJSONString(false),
          "success",
          outcome);

      // Cleanup socket binding
      request =
          ctx.buildRequest(
              "/socket-binding-group=standard-sockets/socket-binding=mod_cluster:remove");
      response = controllerClient.execute(request);
      outcome = response.get("outcome").asString();
      Assert.assertEquals(
          "Removing socket binding failed! " + request.toJSONString(false), "success", outcome);

      // Cleanup and remove the extension
      request = ctx.buildRequest("/extension=org.wildfly.extension.mod_cluster:remove");
      response = controllerClient.execute(request);
      outcome = response.get("outcome").asString();
      Assert.assertEquals(
          "Removing mod_cluster extension failed! " + request.toJSONString(false),
          "success",
          outcome);
    } finally {
      ctx.terminateSession();
    }
  }
  @Test
  public void testCertificateKeyStore() throws Exception {
    cmdAssert(
        "/subsystem=elytron-testing/keystoretester=KeyStoreTester/:write-attribute(name=alias,value=testingserver)");
    cmdAssert(
        "/subsystem=elytron-testing/keystoretester=KeyStoreTester/:write-attribute(name=password,value=123456)"); // password of keystore item

    ModelNode result =
        cmdAssert("/subsystem=elytron-testing/keystoretester=KeyStoreTester/:getCertificate");
    System.out.println(result.toJSONString(false));
    Assert.assertTrue(result.get("contains").asBoolean());
    Assert.assertTrue(result.get("certificate").asString().contains("CN=Testing server"));
    Assert.assertEquals(2, result.get("certificateChain").asList().size());
  }
  private HttpPost getHttpPost(URL url) throws URISyntaxException, UnsupportedEncodingException {
    // For POST we are using the custom op instead read-attribute that we use for GET
    // but this is just a convenient way to exercise the op (GET can't call custom ops),
    // and isn't some limitation of POST
    ModelNode cmd =
        Util.createEmptyOperation(
            LogStreamExtension.STREAM_LOG_FILE,
            PathAddress.pathAddress(SUBSYSTEM, LogStreamExtension.SUBSYSTEM_NAME));
    String cmdStr = cmd.toJSONString(true);
    HttpPost post = new HttpPost(url.toURI());
    StringEntity entity = new StringEntity(cmdStr);
    entity.setContentType(APPLICATION_JSON);
    post.setEntity(entity);

    return post;
  }
  @Test
  public void testJsonObject() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT);

    TypeConverter converter = getConverter(description);

    Assert.assertEquals(SimpleType.STRING, converter.getOpenType());

    ModelNode node = new ModelNode();
    node.get("long").set(5L);
    node.get("string").set("Value");
    node.get("a", "b").set(true);
    node.get("c", "d").set(40);

    String json = node.toJSONString(false);
    String data = assertCast(String.class, converter.fromModelNode(node));
    Assert.assertEquals(json, data);

    Assert.assertEquals(ModelNode.fromJSONString(json), converter.toModelNode(data));
  }
Пример #13
0
  /** @param args */
  public static void main(String[] args) {

    BufferedOutputStream os = null;
    BufferedInputStream is = null;

    try {

      // I. We need to upload content to the server.

      /* The following mimics what would happen as part of submitting an HTML form like the
       * following where the selected file is the "war-example.war" created above:
      <form method="post" action="http://localhost:9990/management/add-content" enctype="multipart/form-data">
        file: <input type="file" name="file">
        <input type="submit">
      </form>
      */

      // Create the test WAR file and get a stream to its contents to be included in the POST.
      WebArchive archive = ShrinkWrap.create(WebArchive.class, "war-example.war");
      archive.addPackage(SimpleServlet.class.getPackage());
      addAsResources("archives/war-example.war", archive);
      is = new BufferedInputStream(archive.as(ZipExporter.class).exportAsInputStream());

      // Write the POST request and read the response from the HTTP server.
      URL uploadContent = new URL("http://localhost:9990/management/add-content");
      HttpURLConnection connection = (HttpURLConnection) uploadContent.openConnection();
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty(
          "Content-Type",
          "multipart/form-data;boundary=---------------------------261773107125236");
      os = new BufferedOutputStream(connection.getOutputStream());

      StringBuilder builder = new StringBuilder();
      builder.append("-----------------------------261773107125236");
      builder.append("\r\n");
      builder.append("Content-Disposition: form-data; name=\"file\"; filename=\"war-example.war\"");
      builder.append("\r\n");
      builder.append("Content-Type: application/octet-stream");
      builder.append("\r\n");
      builder.append("\r\n");
      os.write(builder.toString().getBytes());

      final byte[] buffer = new byte[1024];
      int numRead = 0;

      while (numRead > -1) {
        numRead = is.read(buffer);
        if (numRead > 0) {
          os.write(buffer, 0, numRead);
        }
      }

      is.close();

      builder = new StringBuilder();
      builder.append("\r\n");
      builder.append("-----------------------------261773107125236");
      builder.append("--");
      builder.append("\r\n");

      os.write(builder.toString().getBytes());
      os.flush();

      // Read the response and get the hash of the new content from it
      ModelNode node = ModelNode.fromJSONStream(connection.getInputStream());
      System.out.println("Response to content upload request:");
      System.out.println(node);

      if (!"success".equals(node.require("outcome").asString())) {
        throw new IllegalStateException("Deployment request did not succeed");
      }

      byte[] hash = node.require("result").asBytes();

      // II. Deploy the new content

      connection =
          (HttpURLConnection) new URL("http://localhost:9990/management/").openConnection();
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      os = new BufferedOutputStream(connection.getOutputStream());

      ModelNode op = new ModelNode();
      op.get("operation").set("add");
      op.get("address").add("deployment", "war-example.war");
      ModelNode hashNode = new ModelNode();
      hashNode.get("hash").set(hash);
      op.get("content").set(Collections.singletonList(hashNode));
      op.get("enabled").set(true);

      String json = op.toJSONString(true);
      System.out.println(json);
      os.write(json.getBytes());
      os.flush();

      node = ModelNode.fromJSONStream(connection.getInputStream());
      System.out.println("Response to deployment add request:");
      System.out.println(node);
      if (!"success".equals(node.require("outcome").asString())) {
        throw new IllegalStateException("Deployment request did not succeed");
      }

      // III. Access the deployment
      URL url = new URL("http://localhost:8080/war-example/simple?input=Hello");
      System.out.println("Reading response from " + url + ":");
      connection = (HttpURLConnection) url.openConnection();
      connection.setDoInput(true);
      is = new BufferedInputStream(connection.getInputStream());
      int i = is.read();
      while (i != -1) {
        System.out.print((char) i);
        i = is.read();
      }
      System.out.println("");

      is.close();

      // IV. Redeploy the content

      connection =
          (HttpURLConnection) new URL("http://localhost:9990/management/").openConnection();
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      os = new BufferedOutputStream(connection.getOutputStream());

      op = new ModelNode();
      op.get("operation").set("redeploy");
      op.get("address").add("deployment", "war-example.war");

      json = op.toJSONString(true);
      System.out.println(json);
      os.write(json.getBytes());
      os.flush();

      node = ModelNode.fromJSONStream(connection.getInputStream());
      System.out.println("Response to deployment redeploy request:");
      System.out.println(node);
      if (!"success".equals(node.require("outcome").asString())) {
        throw new IllegalStateException("Deployment request did not succeed");
      }

      // V. Undeploy and remove the deployment

      connection =
          (HttpURLConnection) new URL("http://localhost:9990/management/").openConnection();
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      os = new BufferedOutputStream(connection.getOutputStream());

      op = new ModelNode();
      op.get("operation").set("remove");
      op.get("address").add("deployment", "war-example.war");

      json = op.toJSONString(true);
      System.out.println(json);
      os.write(json.getBytes());
      os.flush();

      node = ModelNode.fromJSONStream(connection.getInputStream());
      System.out.println("Response to deployment remove request:");
      System.out.println(node);
      if (!"success".equals(node.require("outcome").asString())) {
        throw new IllegalStateException("Deployment request did not succeed");
      }

    } catch (final Exception e) {
      e.printStackTrace(System.out);
    } finally {
      closeQuietly(is);
      closeQuietly(os);
    }
  }