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

        boolean result = ctx.getBatchManager().discardActiveBatch();
        if(!result) {
            throw new CommandFormatException("There is no active batch to discard.");
        }
    }
497454
private SSLEngineResult doHandshake(boolean async) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "doHandshake");
        }

        SSLEngineResult sslResult;
        // Line up all the buffers needed for the SSL handshake. Temporary so
        // use indirect allocation for speed.
        int appSize = getConnLink().getAppBufferSize();
        int packetSize = getConnLink().getPacketBufferSize();
        WsByteBuffer localNetBuffer = SSLUtils.allocateByteBuffer(packetSize, true);
        WsByteBuffer decryptedNetBuffer = SSLUtils.allocateByteBuffer(appSize, false);
        WsByteBuffer encryptedAppBuffer = SSLUtils.allocateByteBuffer(packetSize, true);
        // Callback to be used if the request is async.
        MyHandshakeCompletedCallback handshakeCallback = null;
        if (async) {
            handshakeCallback = new MyHandshakeCompletedCallback(this, callback, localNetBuffer, decryptedNetBuffer, encryptedAppBuffer);
        }

        try {
            // Do the SSL handshake. Note, if synchronous the handshakeCallback is null.
            sslResult = SSLUtils.handleHandshake(
                                                 getConnLink(),
                                                 localNetBuffer,
                                                 decryptedNetBuffer,
                                                 encryptedAppBuffer,
                                                 null,
                                                 handshakeCallback,
                                                 false);
        } catch (IOException e) {
            // Release buffers used in the handshake.
            localNetBuffer.release();
            localNetBuffer = null;
            decryptedNetBuffer.release();
            decryptedNetBuffer = null;
            encryptedAppBuffer.release();
            encryptedAppBuffer = null;
            throw e;
        }
        if (sslResult != null) {
            // Handshake was done synchronously.
            // Release buffers used in the handshake.
            localNetBuffer.release();
            localNetBuffer = null;
            decryptedNetBuffer.release();
            decryptedNetBuffer = null;
            encryptedAppBuffer.release();
            encryptedAppBuffer = null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "doHandshake");
        }
        return sslResult;
    }
582481
function contextMenuOpenHandler() {
        var file = MainViewManager.getCurrentlyViewedFile(MainViewManager.ACTIVE_PANE);

        if (file) {
            var targetIndex  = MainViewManager.findInWorkingSet(MainViewManager.ACTIVE_PANE, file.fullPath),
                workingSetListSize = MainViewManager.getWorkingSetSize(MainViewManager.ACTIVE_PANE);

            if (targetIndex === workingSetListSize - 1) { // hide "Close Others Below" if the last file in Working Files is selected
                CommandManager.get(closeBelow).setEnabled(false);
            } else {
                CommandManager.get(closeBelow).setEnabled(true);
            }

            if (workingSetListSize === 1) { // hide "Close Others" if there is only one file in Working Files
                CommandManager.get(closeOthers).setEnabled(false);
            } else {
                CommandManager.get(closeOthers).setEnabled(true);
            }

            if (targetIndex === 0) { // hide "Close Others Above" if the first file in Working Files is selected
                CommandManager.get(closeAbove).setEnabled(false);
            } else {
                CommandManager.get(closeAbove).setEnabled(true);
            }
        }
    }
745668
@Override
    public void handle(CommandContext ctx, String commandLine) {
        // TODO Validate command

        if (commandLine.contains("--help")) {
            this.printHelp(commandLine, ctx);
            return;
        }

        String[] commands = commandLine.split(" ");

        if (commands.length == 1) {
            ctx.connectController(null, -1);
        } else if (commands.length == 2) {
            if (commandLine.contains("--help")) {
                this.printHelp("help/connect.txt", ctx);
                return;
            }
        } else if (commands.length == 3) {
            String host = commands[1];
            try {
                int port = Integer.parseInt(commands[2]);
                ctx.connectController(host, port);
            } catch (NumberFormatException ne) {
                ctx.printLine("Port must be from 1 to 65535");
            }

        } else {
            ctx.printLine("Invalid command.");
        }

    }
120841
function handleCharBinding(cm, e, ch) {
  return dispatchKey(cm, "'" + ch + "'", e, b => doHandleBinding(cm, b, true))
}
149934
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {
        final List<String> names = ctx.getParsedCommandLine().getOtherProperties();
        if(names.isEmpty()) {
            throw new CommandFormatException("Variable name is missing");
        }

        for (String name : names) {
            if (name.charAt(0) == '$') {
                name = name.substring(1);
                if (name.isEmpty()) {
                    throw new CommandFormatException("Variable name is missing after '$'");
                }
            }
            ctx.setVariable(name, null);
        }
    }
1258922
private void doHandleAs(Subject subject, final HttpExchange pHttpExchange) {
        try {
            Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
            public Void run() throws IOException {
                doHandle(pHttpExchange);
                return null;
            }
            });
        } catch (PrivilegedActionException e) {
            throw new SecurityException("Security exception: " + e.getCause(),e.getCause());
        }
    }
1228685
public CmsListItem createDeletedItem(final CmsClientSitemapEntry entry) {

        CmsListInfoBean infoBean = new CmsListInfoBean();
        infoBean.setTitle(entry.getTitle());
        infoBean.setSubTitle(entry.getSitePath());
        infoBean.setResourceType(
            CmsStringUtil.isNotEmptyOrWhitespaceOnly(entry.getDefaultFileType())
            ? entry.getDefaultFileType()
            : entry.getResourceTypeName());
        infoBean.addAdditionalInfo(Messages.get().key(Messages.GUI_NAME_0), entry.getName());
        infoBean.addAdditionalInfo(Messages.get().key(Messages.GUI_VFS_PATH_0), entry.getVfsPath());
        infoBean.setBigIconClasses(entry.getNavModeIcon());
        final CmsListItemWidget itemWidget = new CmsListItemWidget(infoBean);
        CmsListItem listItem = new CmsClipboardDeletedItem(itemWidget, entry);
        CmsPushButton button = new CmsPushButton();
        button.setImageClass(I_CmsButton.RESET);
        button.setTitle(Messages.get().key(Messages.GUI_HOVERBAR_UNDELETE_0));
        button.setButtonStyle(ButtonStyle.FONT_ICON, null);
        button.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {

                CmsDomUtil.ensureMouseOut(itemWidget.getElement());
                m_clipboardButton.closeMenu();
                CmsSitemapView.getInstance().getController().undelete(entry.getId(), entry.getSitePath());
            }

        });
        itemWidget.addButton(button);
        itemWidget.setStateIcon(StateIcon.standard);
        listItem.setId(entry.getId().toString());
        return listItem;
    }
378651
@Override
    public ClientResponse doHandle(ClientRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("Request should not be null");
        }

        URI originalURI = request.getURI();
        request.setURI(locationManager.getRedirectedURI(originalURI));

        ClientResponse response = getNext().handle(request);
        while (response.getClientResponseStatus() == ClientResponse.Status.MOVED_PERMANENTLY) {
            try {
                locationManager.setRedirectedURI(response.getHeaders()
                        .getFirst("Location"));
            } catch (NullPointerException e) {
                throw new ClientHandlerException(
                        "HTTP Redirect did not include Location header");
            } catch (URISyntaxException e) {
                throw new ClientHandlerException(
                        "HTTP Redirect location is not a valid URI");
            }

            request.setURI(locationManager.getRedirectedURI(originalURI));
            response = getNext().handle(request);
        }
        return response;
    }
170978
protected void doHandleFileAjaxActionRequest(final Request request) {
		// Protect against client-side tampering of disabled components
		if (isDisabled()) {
			throw new SystemException("File widget is disabled.");
		}

		// Check for file id
		String fileId = request.getParameter(FILE_UPLOAD_ID_KEY);
		if (fileId == null) {
			throw new SystemException("No file id provided for ajax action.");
		}

		// Check valid file id
		FileWidgetUpload file = getFile(fileId);
		if (file == null) {
			throw new SystemException("Invalid file id [" + fileId + "].");
		}

		// Run the action
		final Action action = getFileAjaxAction();
		if (action == null) {
			throw new SystemException("No action set for file ajax action request.");
		}

		// Set the selected file id as the action object
		final ActionEvent event = new ActionEvent(this, "fileajax", fileId);
		Runnable later = new Runnable() {
			@Override
			public void run() {
				action.execute(event);
			}
		};

		invokeLater(later);
	}
801764
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {

        String argsStr = ctx.getArgumentsString();
        if(argsStr == null) {
            throw new CommandFormatException("The command is missing arguments.");
        }

        final BatchManager batchManager = ctx.getBatchManager();
        if(batchManager.isBatchActive()) {
            throw new CommandFormatException("if is not allowed while in batch mode.");
        }

        final ParsedCommandLine args = ctx.getParsedCommandLine();
        final String conditionStr = this.condition.getOriginalValue(args, true);
        int i = argsStr.indexOf(conditionStr);
        if(i < 0) {
            throw new CommandFormatException("Failed to locate '" + conditionStr + "' in '" + argsStr + "'");
        }
        i = argsStr.indexOf("of", i + conditionStr.length());
        if(i < 0) {
            throw new CommandFormatException("Failed to locate 'of' in '" + argsStr + "'");
        }

        final String requestStr = argsStr.substring(i + 2);
        ctx.registerRedirection(new IfElseControlFlow(ctx, condition.resolveOperation(args), requestStr));
    }
1159728
private void registerAdminTool(CmsObject cms, CmsToolRootHandler toolRoot, I_CmsToolHandler handler) {

        String link = handler.getLink();
        if (link.indexOf("?") > 0) {
            link = link.substring(0, link.indexOf("?"));
        }
        // check visibility
        if (!cms.existsResource(link)) {
            return;
        }

        //validate path
        if (!validatePath(toolRoot.getKey(), handler.getPath(), false)) {
            // log failure
            if (CmsLog.INIT.isWarnEnabled()) {
                CmsLog.INIT.warn(
                    Messages.get().getBundle().key(
                        Messages.INIT_TOOLMANAGER_INCONSISTENT_PATH_2,
                        handler.getPath(),
                        handler.getLink()));
            }
            return;
        }

        String id = "tool" + m_tools.elementList().size();
        CmsTool tool = new CmsTool(id, handler);

        try {
            // try to find problems in custom tools
            handler.isEnabled(cms);
            handler.isVisible(cms);
        } catch (Throwable ex) {
            String message = Messages.get().getBundle().key(
                Messages.INIT_TOOLMANAGER_INSTALL_ERROR_2,
                handler.getPath(),
                handler.getLink());
            if (CmsLog.INIT.isWarnEnabled()) {
                CmsLog.INIT.warn(message);
            } else if (CmsLog.INIT.isDebugEnabled()) {
                CmsLog.INIT.debug(message, ex);
            }
            return;
        }

        try {
            // try to register, can fail if path is already used by another tool
            m_tools.addIdentifiableObject(toolRoot.getKey() + ROOT_SEPARATOR + handler.getPath(), tool);
            // just for fast association of links with tools
            m_urls.addIdentifiableObject(link, handler.getPath());
        } catch (Throwable ex) {
            CmsLog.INIT.warn(
                Messages.get().getBundle().key(
                    Messages.INIT_TOOLMANAGER_DUPLICATED_ERROR_3,
                    handler.getPath(),
                    handler.getLink(),
                    resolveAdminTool(toolRoot.getKey(), handler.getPath()).getHandler().getLink()));
        }
    }
1091504
@Override
    public ClientResponse doHandle(ClientRequest cr) {
        MultivaluedMap<String, Object> headers = cr.getHeaders();
        headers.add("DataServiceVersion", "3.0");
        headers.add("MaxDataServiceVersion", "3.0");
        headers.add("x-ms-version", "2.17");
        return getNext().handle(cr);
    }
1083401
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {

        final boolean v = verbose.isPresent(ctx.getParsedCommandLine());

        final OperationResponse response;
        boolean failed = false;
        boolean hasFile = file.getValue(ctx.getParsedCommandLine()) != null;
        try {
            final ModelNode request = buildRequest(ctx);
            OperationBuilder builder = new OperationBuilder(request, true);
            for (String path : getAttachments(ctx).getAttachedFiles()) {
                builder.addFileAsAttachment(new File(path));
            }
            final ModelControllerClient client = ctx.getModelControllerClient();
            try {
                response = client.executeOperation(builder.build(), OperationMessageHandler.DISCARD);
            } catch(Exception e) {
                throw new CommandFormatException("Failed to perform operation: " + e.getLocalizedMessage());
            }
            if (!Util.isSuccess(response.getResponseNode())) {
                String msg = formatBatchError(ctx, response.getResponseNode());
                if (msg == null) {
                    msg = Util.getFailureDescription(response.getResponseNode());
                }
                throw new CommandFormatException(msg);
            }

            ModelNode steps = response.getResponseNode().get(Util.RESULT);
            if (steps.isDefined()) {
                // Dispatch to non null response handlers.
                final Batch batch = ctx.getBatchManager().getActiveBatch();
                int i = 1;
                for (BatchedCommand cmd : batch.getCommands()) {
                    ModelNode step = steps.get("step-" + i);
                    if (step.isDefined()) {
                        if (cmd.getResponseHandler() != null) {
                            cmd.getResponseHandler().handleResponse(step, response);
                        }
                        i += 1;
                    }
                }
            }

        } catch(CommandLineException e) {
            failed = true;
            if (hasFile) {
                throw new CommandLineException("The batch failed with the following error: ", e);
            } else {
                throw new CommandLineException("The batch failed with the following error "
                        + "(you are remaining in the batch editing mode to have a chance to correct the error)", e);
            }
        } finally {
            // There is a change in behavior between the file and the added command
            // With a file, the batch is discarded, whatever the result.
            if (hasFile) {
                ctx.getBatchManager().discardActiveBatch();
            } else if (!failed) {
                if (ctx.getBatchManager().isBatchActive()) {
                    ctx.getBatchManager().discardActiveBatch();
                }
            }
        }

        if(v) {
            ctx.printDMR(response.getResponseNode());
        } else {
            ctx.printLine("The batch executed successfully");
            super.handleResponse(ctx, response.getResponseNode(), true);
        }
    }
887370
@SuppressWarnings("rawtypes")
    private static void parseCommandLine(final PluginDefinition pluginDef, final Element xmlPluginElement) {
        Element commandLine = xmlPluginElement.element("command-line");

        if (commandLine != null) {
            // The plugin has a command line...
            Element options = commandLine.element("options");

            if (options == null) {
                // The command line is empty...
                return;
            }

            for (Iterator<Element> i = options.elementIterator(); i.hasNext();) {
                pluginDef.addOption(parsePluginOption(i.next()));
            }
        }
    }
715060
private Object executeAjaxCalls(FacesContext context, String command) {
		Object result = null;
		int pos = command.indexOf("ajax:");
		while (pos >= 0) { // the command may contain several AJAX and
							// JavaScript calls, in arbitrary order

			String el = command.substring(pos + "ajax:".length());
			if (el.contains("javascript:")) {
				int end = el.indexOf("javascript:");
				el = el.substring(0, end);
			}
			el = el.trim();
			while (el.endsWith(";")) {
				el = el.substring(0, el.length() - 1).trim();
			}

			if (context.isProjectStage(ProjectStage.Development)) {
				checkELSyntax(el, context.getELContext());
			}
			ValueExpression vex = evalAsValueExpression("#{" + el + "}");
			try {
				result = vex.getValue(context.getELContext());
			} catch (javax.el.PropertyNotFoundException ex) {
				MethodExpression mex = evalAsMethodExpression("#{" + el + "}");
				result = mex.invoke(context.getELContext(), null);
			}

			// look for the next AJAX call (if any)
			pos = command.indexOf("ajax:", pos + 1);
		}
		return result;
	}
334758
private <T extends CommandResultType> T getCommandResult() {
        if (commandResult == null) {
            if (getPayload() instanceof String) {
                this.commandResult = (T) marshaller.unmarshal(new StringSource(getPayload(String.class)));
            }
        }

        return (T) commandResult;
    }