/* (non-Javadoc)
   * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
   */
  @Override
  protected void doHandle(CommandContext ctx) throws CommandFormatException {

    BatchManager batchManager = ctx.getBatchManager();
    if (!batchManager.isBatchActive()) {
      throw new CommandFormatException("No active batch to holdback.");
    }

    String name = null;
    ParsedCommandLine args = ctx.getParsedCommandLine();
    if (args.hasProperties()) {
      name = args.getOtherProperties().get(0);
    }

    if (batchManager.isHeldback(name)) {
      throw new CommandFormatException(
          "There already is "
              + (name == null ? "unnamed" : "'" + name + "'")
              + " batch held back.");
    }

    if (!batchManager.holdbackActiveBatch(name)) {
      throw new CommandFormatException("Failed to holdback the batch.");
    }
  }
  protected ModelNode buildWritePropertyRequest(CommandContext ctx) throws CommandFormatException {

    final String name = this.name.getValue(ctx.getParsedCommandLine(), true);

    ModelNode composite = new ModelNode();
    composite.get(Util.OPERATION).set(Util.COMPOSITE);
    composite.get(Util.ADDRESS).setEmptyList();
    ModelNode steps = composite.get(Util.STEPS);

    final ParsedCommandLine args = ctx.getParsedCommandLine();

    final String profile;
    if (isDependsOnProfile() && ctx.isDomainMode()) {
      profile = this.profile.getValue(args);
      if (profile == null) {
        throw new OperationFormatException("--profile argument value is missing.");
      }
    } else {
      profile = null;
    }

    final Map<String, CommandArgument> nodeProps = loadArguments(ctx, null);
    for (String argName : args.getPropertyNames()) {
      if (isDependsOnProfile() && argName.equals("--profile")
          || this.name.getFullName().equals(argName)) {
        continue;
      }

      final ArgumentWithValue arg = (ArgumentWithValue) nodeProps.get(argName);
      if (arg == null) {
        throw new CommandFormatException("Unrecognized argument name '" + argName + "'");
      }

      DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
      if (profile != null) {
        builder.addNode(Util.PROFILE, profile);
      }

      for (OperationRequestAddress.Node node : getRequiredAddress()) {
        builder.addNode(node.getType(), node.getName());
      }
      builder.addNode(getRequiredType(), name);
      builder.setOperationName(Util.WRITE_ATTRIBUTE);
      final String propName;
      if (argName.charAt(1) == '-') {
        propName = argName.substring(2);
      } else {
        propName = argName.substring(1);
      }
      builder.addProperty(Util.NAME, propName);

      final String valueString = args.getPropertyValue(argName);
      ModelNode nodeValue = arg.getValueConverter().fromString(valueString);
      builder.getModelNode().get(Util.VALUE).set(nodeValue);

      steps.add(builder.buildRequest());
    }

    return composite;
  }
  /* (non-Javadoc)
   * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
   */
  @Override
  protected void doHandle(CommandContext ctx) {

    ModelNode request;
    try {
      request = buildRequest(ctx);
    } catch (OperationFormatException e) {
      ctx.printLine(e.getLocalizedMessage());
      return;
    }

    ModelControllerClient client = ctx.getModelControllerClient();
    final ModelNode result;
    try {
      result = client.execute(request);
    } catch (Exception e) {
      ctx.printLine("Failed to perform operation: " + e.getLocalizedMessage());
      return;
    }

    if (!Util.isSuccess(result)) {
      ctx.printLine(Util.getFailureDescription(result));
      return;
    }

    ctx.printLine("Sucessfully created queue.");
  }
  @Test
  public void testUnDeployArchive() throws Exception {

    final CommandContext ctx = CommandContextFactory.getInstance().newCommandContext();
    try {
      ctx.connectController();
      ctx.handle("deploy " + cliArchiveFile.getAbsolutePath() + " --script=install.scr");

      // check that now both wars are deployed
      String response =
          HttpRequest.get(getBaseURL(url) + "deployment0/SimpleServlet", 10, TimeUnit.SECONDS);
      assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >= 0);
      response =
          HttpRequest.get(getBaseURL(url) + "deployment1/SimpleServlet", 10, TimeUnit.SECONDS);
      assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >= 0);

      ctx.handle(
          "undeploy " + "--path=" + cliArchiveFile.getAbsolutePath() + " --script=uninstall.scr");

      // check that both wars are undeployed
      assertTrue(checkUndeployed(getBaseURL(url) + "deployment0/SimpleServlet"));
      assertTrue(checkUndeployed(getBaseURL(url) + "deployment1/SimpleServlet"));
    } finally {
      ctx.terminateSession();
    }
  }
 /**
  * Prints a list of strings. If -l switch is present then the list is printed one item per line,
  * otherwise the list is printed in columns.
  *
  * @param ctx the context
  * @param list the list to print
  */
 protected void printList(CommandContext ctx, List<String> list, boolean l) {
   if (l) {
     for (String item : list) {
       ctx.printLine(item);
     }
   } else {
     ctx.printColumns(list);
   }
 }
 protected String runIf(CommandContext ctx, String comparison, String logical, String value)
     throws Exception {
   ctx.handle(getIfStatement(comparison, logical, value));
   ctx.handle(this.getWritePropertyReq("\"true\""));
   ctx.handle("end-if");
   cliOut.reset();
   ctx.handle(getReadPropertyReq());
   return getValue();
 }
Exemple #7
0
  private static void printHistory(CommandContext ctx) {

    CommandHistory history = ctx.getHistory();
    List<String> list = history.asList();
    for (String cmd : list) {
      ctx.printLine(cmd);
    }
    ctx.printLine(
        "(The history is currently " + (history.isUseHistory() ? "enabled)" : "disabled)"));
  }
 public static void reloadServer() throws Exception {
   final CommandContext ctx =
       CLITestUtil.getCommandContext(
           "remoting", TestSuiteEnvironment.getServerAddress(), MANAGEMENT_NATIVE_PORT);
   try {
     ctx.connectController();
     ctx.handle("reload");
   } finally {
     ctx.terminateSession();
   }
 }
 @Override
 protected void handleResponse(CommandContext ctx, ModelNode opResponse, boolean composite) {
   if (!Util.isSuccess(opResponse)) {
     ctx.printLine(Util.getFailureDescription(opResponse));
     return;
   }
   final StringBuilder buf = formatResponse(ctx, opResponse, composite, null);
   if (buf != null) {
     ctx.printLine(buf.toString());
   }
 }
  @Override
  public ModelNode buildRequest(CommandContext ctx) throws OperationFormatException {

    DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
    ParsedArguments args = ctx.getParsedArguments();

    if (ctx.isDomainMode()) {
      String profile = this.profile.getValue(args);
      if (profile == null) {
        throw new OperationFormatException("--profile argument value is missing.");
      }
      builder.addNode("profile", profile);
    }

    final String name;
    try {
      name = this.name.getValue(args);
    } catch (IllegalArgumentException e) {
      throw new OperationFormatException(e.getLocalizedMessage());
    }

    builder.addNode("subsystem", "jms");
    builder.addNode("queue", name);
    builder.setOperationName("add");

    ModelNode entriesNode = builder.getModelNode().get("entries");
    final String entriesStr = this.entries.getValue(args);
    if (entriesStr == null) {
      entriesNode.add(name);
    } else {
      String[] split = entriesStr.split(",");
      for (int i = 0; i < split.length; ++i) {
        String entry = split[i].trim();
        if (!entry.isEmpty()) {
          entriesNode.add(entry);
        }
      }
    }

    final String selector = this.selector.getValue(args);
    if (selector != null) {
      builder.addProperty("selector", selector);
    }

    final String durable = this.durable.getValue(args);
    if (durable != null) {
      builder.addProperty("durable", durable);
    }

    return builder.buildRequest();
  }
  @Before
  public void beforeTest() throws Exception {
    ctx = CLITestUtil.getCommandContext();
    ctx.connectController();

    ctx.handle("deploy --server-groups=" + sgOne + ' ' + cliTestApp1War.getAbsolutePath());
    ctx.handle("deploy --server-groups=" + sgOne + ' ' + cliTestAnotherWar.getAbsolutePath());

    ctx.handle("deploy --server-groups=" + sgTwo + ' ' + cliTestApp2War.getAbsolutePath());
    ctx.handle(
        "deploy --server-groups=" + sgTwo + ',' + sgOne + ' ' + cliTestAppEar.getAbsolutePath());

    afterTestDeployments = new HashSet<String>();
  }
 @Test
 public void testGreaterThan() throws Exception {
   final CommandContext ctx = CLITestUtil.getCommandContext(cliOut);
   try {
     ctx.connectController();
     ctx.handle(this.getAddPropertyReq("\"5\""));
     assertEquals("5", runIf(ctx, ">", "&&", "\"1\""));
     assertEquals("true", runIf(ctx, ">", "||", "\"1\""));
   } finally {
     ctx.handleSafe(this.getRemovePropertyReq());
     ctx.terminateSession();
     cliOut.reset();
   }
 }
  @Override
  protected void doHandle(CommandContext ctx) {

    ModelControllerClient client = ctx.getModelControllerClient();
    ParsedArguments args = ctx.getParsedArguments();
    boolean l = this.l.isPresent(args);
    if (!args.hasArguments() || l) {
      printList(ctx, Util.getDeployments(client), l);
      return;
    }

    final String name = this.name.getValue(ctx.getParsedArguments());

    if (name == null) {
      printList(ctx, Util.getDeployments(client), l);
      return;
    }

    DefaultOperationRequestBuilder builder;

    // undeploy
    builder = new DefaultOperationRequestBuilder();
    builder.setOperationName("undeploy");
    builder.addNode("deployment", name);

    ModelNode result;
    try {
      ModelNode request = builder.buildRequest();
      result = client.execute(request);
    } catch (Exception e) {
      ctx.printLine("Failed to undeploy: " + e.getLocalizedMessage());
      return;
    }

    // TODO undeploy may fail if the content failed to deploy but remove should still be executed
    if (!Util.isSuccess(result)) {
      ctx.printLine("Undeploy failed: " + Util.getFailureDescription(result));
      return;
    }

    // remove
    builder = new DefaultOperationRequestBuilder();
    builder.setOperationName("remove");
    builder.addNode("deployment", name);
    try {
      ModelNode request = builder.buildRequest();
      result = client.execute(request);
    } catch (Exception e) {
      ctx.printLine(
          "Failed to remove the deployment content from the repository: "
              + e.getLocalizedMessage());
      return;
    }
    if (!Util.isSuccess(result)) {
      ctx.printLine("Remove failed: " + Util.getFailureDescription(result));
      return;
    }

    ctx.printLine("Successfully undeployed " + name + ".");
  }
 protected StringBuilder undeploy(StringBuilder buf, String deployment, String sg) {
   ctx.handleSafe("undeploy --server-groups=" + sg + ' ' + deployment);
   if (ctx.getExitCode() == 0) {
     if (!afterTestDeployments.remove(deployment)) {
       if (buf == null) {
         buf = new StringBuilder();
         buf.append("Undeployed unexpected content: ");
         buf.append(deployment);
       } else {
         buf.append(", ").append(deployment);
       }
     }
   }
   return buf;
 }
 protected void recognizeArguments(CommandContext ctx) throws CommandFormatException {
   final Set<String> specifiedNames = ctx.getParsedCommandLine().getPropertyNames();
   if (!args.keySet().containsAll(specifiedNames)) {
     Collection<String> unrecognized = new HashSet<String>(specifiedNames);
     unrecognized.removeAll(args.keySet());
     throw new CommandFormatException("Unrecognized arguments: " + unrecognized);
   }
   if (ctx.getParsedCommandLine().getOtherProperties().size() - 1 > this.maxArgumentIndex) {
     throw new CommandFormatException(
         "The command accepts "
             + (this.maxArgumentIndex + 1)
             + " unnamed argument(s) but received: "
             + ctx.getParsedCommandLine().getOtherProperties());
   }
 }
 /* (non-Javadoc)
  * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
  */
 @Override
 protected void doHandle(CommandContext ctx) throws CommandLineException {
   boolean failed = false;
   try {
     super.doHandle(ctx);
     ctx.printLine("The batch executed successfully");
   } catch (CommandLineException e) {
     failed = true;
     throw e;
   } finally {
     if (!failed) {
       ctx.getBatchManager().discardActiveBatch();
     }
   }
 }
 protected boolean isAddressValid(CommandContext ctx) {
   final ModelNode request = new ModelNode();
   final ModelNode address = request.get(Util.ADDRESS);
   address.setEmptyList();
   request.get(Util.OPERATION).set(Util.VALIDATE_ADDRESS);
   final ModelNode addressValue = request.get(Util.VALUE);
   for (OperationRequestAddress.Node node : requiredAddress) {
     addressValue.add(node.getType(), node.getName());
   }
   final ModelNode response;
   try {
     response = ctx.getModelControllerClient().execute(request);
   } catch (IOException e) {
     return false;
   }
   final ModelNode result = response.get(Util.RESULT);
   if (!result.isDefined()) {
     return false;
   }
   final ModelNode valid = result.get(Util.VALID);
   if (!valid.isDefined()) {
     return false;
   }
   return valid.asBoolean();
 }
 @Override
 public boolean isAvailable(CommandContext ctx) {
   if (connectionRequired && ctx.getModelControllerClient() == null) {
     return false;
   }
   return true;
 }
  /* (non-Javadoc)
   * @see org.jboss.as.cli.CandidatesProvider#getNodeTypes(org.jboss.as.cli.Prefix)
   */
  @Override
  public List<String> getNodeTypes(OperationRequestAddress prefix) {

    ModelControllerClient client = ctx.getModelControllerClient();
    if (client == null) {
      return Collections.emptyList();
    }

    if (prefix.endsOnType()) {
      throw new IllegalArgumentException("The prefix isn't expected to end on a type.");
    }

    ModelNode request;
    DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(prefix);
    try {
      builder.operationName("read-children-types");
      request = builder.buildRequest();
    } catch (OperationFormatException e1) {
      throw new IllegalStateException("Failed to build operation", e1);
    }

    List<String> result;
    try {
      ModelNode outcome = client.execute(request);
      if (!Util.isSuccess(outcome)) {
        // TODO logging... exception?
        result = Collections.emptyList();
      } else {
        result = Util.getList(outcome);
      }
    } catch (Exception e) {
      result = Collections.emptyList();
    }
    return result;
  }
  /* (non-Javadoc)
   * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
   */
  @Override
  protected void doHandle(CommandContext ctx) throws CommandLineException {

    final ModelNode request = buildRequest(ctx);

    final ModelControllerClient client = ctx.getModelControllerClient();
    final OperationResponse operationResponse;
    try {
      operationResponse =
          client.executeOperation(
              Operation.Factory.create(request), OperationMessageHandler.DISCARD);
    } catch (Exception e) {
      throw new CommandLineException("Failed to perform operation", e);
    }
    try {
      final ModelNode response = operationResponse.getResponseNode();
      if (!Util.isSuccess(response)) {
        throw new CommandLineException(Util.getFailureDescription(response));
      }
      handleResponse(
          ctx, operationResponse, Util.COMPOSITE.equals(request.get(Util.OPERATION).asString()));
      operationResponse.close();
    } catch (IOException ex) {
      throw new CommandLineException("Failed to perform operation", ex);
    }
  }
  /* (non-Javadoc)
   * @see org.jboss.as.cli.CommandHandler#handle(org.jboss.as.cli.CommandContext)
   */
  @Override
  public void handle(CommandContext ctx) throws CommandFormatException {

    if (helpArg.isPresent(ctx.getParsedArguments())) {
      printHelp(ctx);
      return;
    }

    if (!isAvailable(ctx)) {
      ctx.printLine(
          "The command is not available in the current context (e.g. required subsystems or connection to the controller might be unavailable).");
      return;
    }

    doHandle(ctx);
  }
 @Override
 public boolean isAvailable(CommandContext ctx) {
   if (!super.isAvailable(ctx)) {
     return false;
   }
   return ctx.isBatchMode();
 }
 /**
  * User-initiated commands use this method.
  *
  * @param command The CLI command
  * @return A Response object containing the command line, DMR request, and DMR response
  * @throws CommandFormatException
  * @throws IOException
  */
 public synchronized Response doCommandFullResponse(String command)
     throws CommandFormatException, IOException {
   ModelNode request = cmdCtx.buildRequest(command);
   boolean replacedBytes = replaceFilePathsWithBytes(request);
   OperationResponse response = execute(request, isSlowCommand(command) || replacedBytes);
   return new Response(command, request, response);
 }
  @Override
  public ModelNode buildRequest(CommandContext ctx) throws OperationFormatException {

    ModelNode composite = new ModelNode();
    composite.get("operation").set("composite");
    composite.get("address").setEmptyList();
    ModelNode steps = composite.get("steps");

    final String name = this.name.getValue(ctx.getParsedArguments());
    if (name == null) {
      throw new OperationFormatException("Required argument name are missing.");
    }

    DefaultOperationRequestBuilder builder;

    // undeploy
    builder = new DefaultOperationRequestBuilder();
    builder.setOperationName("undeploy");
    builder.addNode("deployment", name);
    steps.add(builder.buildRequest());

    builder = new DefaultOperationRequestBuilder();
    builder.setOperationName("remove");
    builder.addNode("deployment", name);
    steps.add(builder.buildRequest());
    return composite;
  }
 protected StringBuilder formatResponse(
     CommandContext ctx, ModelNode opResponse, boolean composite, StringBuilder buf) {
   if (!opResponse.hasDefined(Util.RESULT)) {
     return null;
   }
   final ModelNode result = opResponse.get(Util.RESULT);
   if (composite) {
     final Set<String> keys;
     try {
       keys = result.keys();
     } catch (Exception e) {
       ctx.printLine(
           "Failed to get step results from a composite operation response " + opResponse);
       e.printStackTrace();
       return null;
     }
     for (String key : keys) {
       final ModelNode stepResponse = result.get(key);
       buf =
           formatResponse(
               ctx, stepResponse, false, buf); // TODO nested composite ops aren't expected for now
     }
   } else {
     final ModelNodeFormatter formatter = ModelNodeFormatter.Factory.forType(result.getType());
     if (buf == null) {
       buf = new StringBuilder();
     }
     formatter.format(buf, 0, result);
   }
   return buf;
 }
 public BaseOperationCommand(CommandContext ctx, String command, boolean connectionRequired) {
   super(command, connectionRequired);
   ctx.addEventListener(this);
   headers =
       new ArgumentWithValue(
           this, HeadersCompleter.INSTANCE, HeadersArgumentValueConverter.INSTANCE, "--headers");
   accessRequirement = setupAccessRequirement(ctx);
 }
 protected void addHeaders(CommandContext ctx, ModelNode request) throws CommandFormatException {
   if (!headers.isPresent(ctx.getParsedCommandLine())) {
     return;
   }
   final ModelNode headersNode = headers.toModelNode(ctx);
   final ModelNode opHeaders = request.get(Util.OPERATION_HEADERS);
   opHeaders.set(headersNode);
 }
 protected ModelNode initRequest(CommandContext ctx) {
   ModelNode request = new ModelNode();
   ModelNode address = request.get(Util.ADDRESS);
   if (ctx.isDomainMode()) {
     final String profileName = profile.getValue(ctx.getParsedCommandLine());
     if (profile == null) {
       ctx.printLine("--profile argument is required to get the node description.");
       return null;
     }
     address.add(Util.PROFILE, profileName);
   }
   for (OperationRequestAddress.Node node : nodePath) {
     address.add(node.getType(), node.getName());
   }
   address.add(type, "?");
   return request;
 }
Exemple #29
0
 public void execute() {
   log.info("execute cli command");
   try {
     ctx.handle(CMD_READ_MSG);
   } catch (CommandLineException e) {
     e.printStackTrace();
   }
 }
 @Override
 public ModelNode buildRequest(CommandContext ctx) throws CommandFormatException {
   final String operation = this.operation.getValue(ctx.getParsedCommandLine());
   if (operation == null) {
     return buildWritePropertyRequest(ctx);
   }
   return buildOperationRequest(ctx, operation);
 }