private ModelNode getEndpointsNode() throws Exception {
   try (InputStream stream =
       openStream(
           url,
           headers,
           connectTimeout,
           readTimeout,
           operationAttempts,
           operationSleep,
           streamProvider)) {
     return ModelNode.fromJSONStream(stream);
   }
 }
 private ModelNode readResult(final InputStream is) throws IOException, NoSuchElementException {
   return ModelNode.fromJSONStream(is);
 }
Example #3
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);
    }
  }
 private ModelNode convertPostRequest(InputStream stream, boolean encode) throws IOException {
   return encode ? ModelNode.fromBase64(stream) : ModelNode.fromJSONStream(stream);
 }
  @Override
  public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final FormDataParser parser = formParserFactory.createParser(exchange);
    if (parser == null) {
      Common.UNSUPPORTED_MEDIA_TYPE.handleRequest(exchange);
    }

    // Prevent CSRF which can occur from standard a multipart/form-data submission from a standard
    // HTML form.
    // If the browser sends an Origin header (Chrome / Webkit) then the earlier origin check will
    // have passed
    // to reach this point. If the browser doesn't (FireFox), then  only requests which came from
    // Javascript,
    // which enforces same-origin policy when no Origin header is present, should be allowed. The
    // presence of
    // a custom header indicates usage of XHR since simple forms can not set them.
    HeaderMap headers = exchange.getRequestHeaders();
    if (!headers.contains(Headers.ORIGIN) && !headers.contains(CLIENT_NAME)) {
      ROOT_LOGGER.debug(
          "HTTP Origin or X-Management-Client-Name header is required for all multipart form data posts.");
      Common.UNAUTHORIZED.handleRequest(exchange);
      return;
    }

    // Parse the form data
    final FormData data = parser.parseBlocking();
    final OperationParameter.Builder operationParameterBuilder =
        new OperationParameter.Builder(false);

    // Process the operation
    final FormData.FormValue op = data.getFirst(OPERATION);
    final ModelNode operation;
    try {
      String type = op.getHeaders().getFirst(Headers.CONTENT_TYPE);
      if (Common.APPLICATION_DMR_ENCODED.equals(type)) {
        try (InputStream stream = convertToStream(op)) {
          operation = ModelNode.fromBase64(stream);
        }
        operationParameterBuilder.encode(true);
      } else if (Common.APPLICATION_JSON.equals(stripSuffix(type))) {
        try (InputStream stream = convertToStream(op)) {
          operation = ModelNode.fromJSONStream(stream);
        }
      } else {
        ROOT_LOGGER.debug("Content-type must be application/dmr-encoded or application/json");
        Common.UNAUTHORIZED.handleRequest(exchange);
        return;
      }
    } catch (Exception e) {
      ROOT_LOGGER.errorf("Unable to construct ModelNode '%s'", e.getMessage());
      Common.sendError(exchange, false, e.getLocalizedMessage());
      return;
    }

    // Process the input streams
    final OperationBuilder builder = OperationBuilder.create(operation, true);
    final Iterator<String> i = data.iterator();
    while (i.hasNext()) {
      final String name = i.next();
      final Deque<FormData.FormValue> contents = data.get(name);
      if (contents != null && !contents.isEmpty()) {
        for (final FormData.FormValue value : contents) {
          if (value.isFile()) {
            builder.addFileAsAttachment(value.getPath().toFile());
          }
        }
      }
    }

    operationParameterBuilder.pretty(
        operation.hasDefined("json.pretty") && operation.get("json.pretty").asBoolean());
    // Response callback to handle the :reload operation
    final OperationParameter opParam = operationParameterBuilder.build();
    final ResponseCallback callback =
        new ResponseCallback() {
          @Override
          void doSendResponse(final ModelNode response) {
            if (response.hasDefined(OUTCOME) && FAILED.equals(response.get(OUTCOME).asString())) {
              Common.sendError(exchange, opParam.isEncode(), response);
              return;
            }
            writeResponse(exchange, 200, response, opParam);
          }
        };

    final boolean sendPreparedResponse = sendPreparedResponse(operation);
    final ModelController.OperationTransactionControl control =
        sendPreparedResponse
            ? new ModelController.OperationTransactionControl() {
              @Override
              public void operationPrepared(
                  final ModelController.OperationTransaction transaction, final ModelNode result) {
                transaction.commit();
                // Fix prepared result
                result.get(OUTCOME).set(SUCCESS);
                result.get(RESULT);
                callback.sendResponse(result);
              }
            }
            : ModelController.OperationTransactionControl.COMMIT;

    ModelNode response;
    final Operation builtOp = builder.build();
    try {
      ModelNode opheaders = operation.get(OPERATION_HEADERS);
      opheaders.get(ACCESS_MECHANISM).set(AccessMechanism.HTTP.toString());
      opheaders.get(CALLER_TYPE).set(USER);
      // Don't allow a domain-uuid operation header from a user call
      if (opheaders.hasDefined(DOMAIN_UUID)) {
        opheaders.remove(DOMAIN_UUID);
      }
      response =
          modelController.execute(operation, OperationMessageHandler.DISCARD, control, builtOp);
    } catch (Throwable t) {
      ROOT_LOGGER.modelRequestError(t);
      Common.sendError(exchange, opParam.isEncode(), t.getLocalizedMessage());
      return;
    } finally {
      // Close any input streams that were open
      if (builtOp.isAutoCloseStreams()) {
        for (InputStream in : builtOp.getInputStreams()) {
          IoUtils.safeClose(in);
        }
      }
    }

    callback.sendResponse(response);
  }