/* (non-Javadoc)
@see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
19219
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {
        ParsedCommandLine parsedArgs = ctx.getParsedCommandLine();
        final List<String> vars = parsedArgs.getOtherProperties();
        if(vars.isEmpty()) {
            final Collection<String> defined = ctx.getVariables();
            if(defined.isEmpty()) {
                return;
            }
            final List<String> pairs = new ArrayList<String>(defined.size());
            for(String var : defined) {
                pairs.add(var + '=' + ctx.getVariable(var));
            }
            Collections.sort(pairs);
            for(String pair : pairs) {
                ctx.printLine(pair);
            }
            return;
        }
        for(String arg : vars) {
            arg = ArgumentWithValue.resolveValue(arg);
            if(arg.charAt(0) == '$') {
                arg = arg.substring(1);
                if(arg.isEmpty()) {
                    throw new CommandFormatException("Variable name is missing after '$'");
                }
            }
            final int equals = arg.indexOf('=');
            if(equals < 1) {
                throw new CommandFormatException("'=' is missing for variable '" + arg + "'");
            }
            final String name = arg.substring(0, equals);
            if(name.isEmpty()) {
                throw new CommandFormatException("The name is missing in '" + arg + "'");
            }
            if(equals == arg.length() - 1) {
                ctx.setVariable(name, null);
            } else {
                String value = arg.substring(equals + 1);
                if(value.length() > 2 && value.charAt(0) == '`' && value.charAt(value.length() - 1) == '`') {
                    value = Util.getResult(ctx, value.substring(1, value.length() - 1));
                }
                ctx.setVariable(name, value);
            }
        }
    }
676414
@Override
    public void registerCommandHandler(String key, CommandHandler handler)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "registerCommandHandler",
                        new Object[] { key, handler });

        // Table of keys and non-tx handlers is managed at ME level
        _messageProcessor.registerCommandHandler(key, handler);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "registerCommandHandler");
    }
855607
protected I_CmsContextMenuEntry createToggleEditSmallElementsMenuEntry() {

        final CmsSmallElementsHandler smallElementsHandler = m_controller.getSmallElementsHandler();
        final boolean isActive = smallElementsHandler.areSmallElementsEditable();
        CmsContextMenuEntryBean entryBean = new CmsContextMenuEntryBean();
        String baseMessage = Messages.get().key(Messages.GUI_EDIT_SMALL_ELEMENTS_0);
        String msgEdit = baseMessage;
        String msgDisable = baseMessage;
        String label = isActive ? msgDisable : msgEdit;
        entryBean.setLabel(label);
        entryBean.setActive(smallElementsHandler.hasSmallElements());
        entryBean.setVisible(true);
        I_CmsInputCss inputCss = I_CmsInputLayoutBundle.INSTANCE.inputCss();
        entryBean.setIconClass(isActive ? inputCss.checkBoxImageChecked() : inputCss.checkBoxImageUnchecked());
        I_CmsContextMenuCommand command = new I_CmsContextMenuCommand() {

            public void execute(CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) {

                smallElementsHandler.setEditSmallElements(!isActive, true);
            }

            public A_CmsContextMenuItem getItemWidget(
                CmsUUID structureId,
                I_CmsContextMenuHandler handler,
                CmsContextMenuEntryBean bean) {

                return null;
            }

            public boolean hasItemWidget() {

                return false;
            }
        };
        CmsContextMenuEntry entry = new CmsContextMenuEntry(this, null, command);
        entry.setBean(entryBean);
        return entry;
    }
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;
    }
825340
public void openStandAloneFormEditor(final CmsEditorContext context) {

        initEventPreviewHandler();
        final CmsContentDefinition definition;
        try {
            definition = (CmsContentDefinition)CmsRpcPrefetcher.getSerializedObjectFromDictionary(
                getService(),
                I_CmsContentService.DICT_CONTENT_DEFINITION);
        } catch (SerializationException e) {
            RootPanel.get().add(new Label(e.getMessage()));
            return;
        }
        m_isStandAlone = true;
        if (definition.isModelInfo()) {
            openModelSelectDialog(context, definition);
        } else {
            CmsCoreProvider.get().lock(
                CmsContentDefinition.entityIdToUuid(definition.getEntityId()),
                new I_CmsSimpleCallback<Boolean>() {

                    public void execute(Boolean arg) {

                        if (arg.booleanValue()) {

                            registerContentDefinition(definition);
                            // register all external widgets
                            WidgetRegistry.getInstance().registerExternalWidgets(
                                definition.getExternalWidgetConfigurations(),
                                new Command() {

                                    public void execute() {

                                        initEditor(context, definition, null, false, null);
                                    }
                                });

                        } else {
                            showLockedResourceMessage();
                        }
                    }
                });
        }
    }
1137542
static CliReceivedCommand consumeCommandLineInput(ParseResult providedCommand, @SuppressWarnings("SameParameterValue") Iterable<CliDeclaredOptionSpec> declaredOptions) {
        assumeTrue(providedCommand.hasSubcommand(), "Command was empty, expected one of: " + Arrays.toString(CliCommandType.values()));
        
        final ParseResult mailCommand = providedCommand.subcommand();
        final CliCommandType matchedCommand = CliCommandType.valueOf(mailCommand.commandSpec().name());
        final Map<CliDeclaredOptionSpec, OptionSpec> matchedOptionsInOrderProvision = matchProvidedOptions(declaredOptions, mailCommand.matchedOptions());
    
        logParsedInput(matchedCommand, matchedOptionsInOrderProvision);
		
        List<CliReceivedOptionData> receivedOptions = new ArrayList<>();
        for (Entry<CliDeclaredOptionSpec, OptionSpec> cliOption : matchedOptionsInOrderProvision.entrySet()) {
			final Method sourceMethod = cliOption.getKey().getSourceMethod();
			final int mandatoryParameters = MiscUtil.countMandatoryParameters(sourceMethod);
			final List<String> providedStringValues = cliOption.getValue().getValue();
            assumeTrue(providedStringValues.size() >= mandatoryParameters,
                    format("provided %s arguments, but need at least %s", providedStringValues.size(), mandatoryParameters));
            assumeTrue(providedStringValues.size() <= sourceMethod.getParameterTypes().length,
                    format("provided %s arguments, but need at most %s", providedStringValues.size(), sourceMethod.getParameterTypes().length));
			receivedOptions.add(new CliReceivedOptionData(cliOption.getKey(), convertProvidedOptionValues(providedStringValues, sourceMethod)));
			LOGGER.debug("\tconverted option values: {}", getLast(receivedOptions).getProvidedOptionValues());
        }
        
        return new CliReceivedCommand(matchedCommand, receivedOptions);
    }
1006935
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {

        final ModelNode request = buildRequest(ctx);
        Attachments attachments = getAttachments(ctx);
        OperationBuilder builder = new OperationBuilder(request, true);
        for (String path : attachments.getAttachedFiles()) {
            builder.addFileAsAttachment(new File(path));
        }
        final ModelControllerClient client = ctx.getModelControllerClient();
        final OperationResponse operationResponse;
        try {
            operationResponse = client.executeOperation(builder.build(), 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);
        }
    }
100351
@Override
    protected void doHandle(CommandContext ctx) throws CommandFormatException {
        BatchManager batchManager = ctx.getBatchManager();
        if(!batchManager.isBatchActive()) {
            throw new CommandFormatException("No active batch.");
        }
        Batch activeBatch = batchManager.getActiveBatch();
        List<BatchedCommand> commands = activeBatch.getCommands();
        if (!commands.isEmpty()) {
            for (int i = 0; i < commands.size(); ++i) {
                BatchedCommand cmd = commands.get(i);
                ctx.printLine("#" + (i + 1) + ' ' + cmd.getCommand());
            }
        } else {
            ctx.printLine("The batch is empty.");
        }
    }
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;
	}
128249
public static I_CmsContextMenuCommand getContextMenuCommand() {

        return new I_CmsContextMenuCommand() {

            public void execute(
                CmsUUID structureId,
                final I_CmsContextMenuHandler handler,
                CmsContextMenuEntryBean bean) {

                CmsConfirmDialog dialog = new CmsConfirmDialog(
                    Messages.get().key(Messages.GUI_DIALOG_LOGOUT_TITLE_0),
                    Messages.get().key(Messages.GUI_DIALOG_LOGOUT_TEXT_0));
                dialog.setOkText(Messages.get().key(Messages.GUI_YES_0));
                dialog.setCloseText(Messages.get().key(Messages.GUI_NO_0));
                dialog.setHandler(new I_CmsConfirmDialogHandler() {

                    public void onClose() {

                        // nothing to do
                    }

                    public void onOk() {

                        String logoutTarget = CmsCoreProvider.get().link(CmsCoreProvider.get().getLoginURL())
                            + "?logout=true";
                        handler.leavePage(logoutTarget);
                    }
                });
                dialog.center();
            }

            public A_CmsContextMenuItem getItemWidget(
                CmsUUID structureId,
                I_CmsContextMenuHandler handler,
                CmsContextMenuEntryBean bean) {

                return null;
            }

            public boolean hasItemWidget() {

                return false;
            }
        };
    }
751456
@Override
    public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) {

        int nextCharIndex = 0;
        while(nextCharIndex < buffer.length()) {
            if(!Character.isWhitespace(buffer.charAt(nextCharIndex))) {
                break;
            }
            ++nextCharIndex;
        }

        if(nextCharIndex == buffer.length()) {
            candidates.addAll(all);
            return nextCharIndex;
        }

        String[] split = buffer.split("\\s+");
        int result;
        final String chunk;
        if(Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
            chunk = null;
            result = buffer.length();
        } else {
            chunk = split[split.length - 1];
            result = buffer.length() - 1;
            while(result >= 0 && !Character.isWhitespace(buffer.charAt(result))) {
                --result;
            }
            ++result;
        }

        final List<String> remainingArgs = new ArrayList<String>(all);
        int maxI = chunk == null ? split.length : split.length - 1;
        for(int i = 0; i < maxI; ++i) {
            String arg = split[i];
            int equalsIndex = arg.indexOf('=');
            if(equalsIndex >= 0) {
                arg = arg.substring(0, equalsIndex + 1);
            }
            remainingArgs.remove(arg);
        }

        if (chunk == null) {
            candidates.addAll(remainingArgs);
        } else {
            for(String name : remainingArgs) {
                if(name.startsWith(chunk)) {
                    candidates.add(name);
                }
            }
        }
        return result;
    }
349584
private CmsListItem createListItem(CmsResourceInfoBean resourceInfo, CmsDNDHandler dndHandler) {

        CmsListInfoBean infoBean = new CmsListInfoBean();
        infoBean.setTitle(
            CmsStringUtil.isNotEmptyOrWhitespaceOnly(resourceInfo.getProperties().get(CmsClientProperty.PROPERTY_TITLE))
            ? resourceInfo.getProperties().get(CmsClientProperty.PROPERTY_TITLE)
            : resourceInfo.getTitle());
        infoBean.setSubTitle(resourceInfo.getResourcePath());
        infoBean.setResourceType(resourceInfo.getResourceType());
        infoBean.setBigIconClasses(resourceInfo.getBigIconClasses());
        infoBean.setSmallIconClasses(resourceInfo.getSmallIconClasses());
        infoBean.addAdditionalInfo(Messages.get().key(Messages.GUI_PREVIEW_LABEL_SIZE_0), resourceInfo.getSize());
        if (resourceInfo.getDescription() != null) {
            infoBean.addAdditionalInfo(
                Messages.get().key(Messages.GUI_PREVIEW_LABEL_DESCRIPTION_0),
                resourceInfo.getDescription());
        }
        if (resourceInfo.getLastModified() != null) {
            infoBean.addAdditionalInfo(
                Messages.get().key(Messages.GUI_PREVIEW_LABEL_DATEMODIFIED_0),
                CmsDateTimeUtil.getDate(resourceInfo.getLastModified(), Format.MEDIUM));
        }
        CmsListItemWidget itemWidget = new CmsListItemWidget(infoBean);
        itemWidget.addOpenHandler(new OpenHandler<CmsListItemWidget>() {

            public void onOpen(OpenEvent<CmsListItemWidget> event) {

                int widgetHeight = event.getTarget().getOffsetHeight();
                m_previewContent.getElement().getStyle().setTop(12 + widgetHeight, Unit.PX);
            }
        });
        itemWidget.addCloseHandler(new CloseHandler<CmsListItemWidget>() {

            public void onClose(CloseEvent<CmsListItemWidget> event) {

                m_previewContent.getElement().getStyle().clearTop();
            }
        });
        CmsListItem result = new CmsListItem(itemWidget);

        CmsPushButton button = CmsResultListItem.createDeleteButton();
        if (dndHandler != null) {
            result.initMoveHandle(dndHandler);
        }
        CmsResultsTab resultsTab = m_binaryPreviewHandler.getGalleryDialog().getResultsTab();
        final DeleteHandler deleteHandler = resultsTab.makeDeleteHandler(resourceInfo.getResourcePath());
        ClickHandler handler = new ClickHandler() {

            public void onClick(ClickEvent event) {

                deleteHandler.onClick(event);
                m_binaryPreviewHandler.closePreview();
            }
        };
        button.addClickHandler(handler);
        itemWidget.addButton(button);
        return result;
    }
853417
protected void doHandleTargetedRequest(final Request request) {

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

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

		// Check if thumb nail requested
		boolean thumbNail = request.getParameter(FILE_UPLOAD_THUMB_NAIL_KEY) != null;
		if (thumbNail) {
			doHandleThumbnailRequest(file);
		} else {
			doHandleFileContentRequest(file);
		}
	}
983502
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {
        final IfElseControlFlow ifElse = IfElseControlFlow.get(ctx);
        if(ifElse == null) {
            throw new CommandLineException("else is not available outside the if-else control flow");
        }
        if(ifElse.isInIf()) {
            ifElse.moveToElse();
        } else {
            throw new CommandLineException("only one else block is supported after the if");
        }
    }
983986
@Override
    public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) {
        if(!ctx.isDomainMode()) {
            return -1;
        }
        if(buffer.isEmpty()) {
            candidates.add("{rollout");
            return 0;
        }

        try {
            parsedOp.parseOperation(null, buffer, ctx);
        } catch (CommandFormatException e) {
            return -1;
        }
        if(parsedOp.isRequestComplete()) {
            return -1;
        }

        if(parsedOp.endsOnHeaderListStart() || parsedOp.endsOnHeaderSeparator()) {
            candidates.add("rollout");
            return parsedOp.getLastSeparatorIndex() + 1;
        }
        if(parsedOp.getLastHeader() == null) {
            if(ctx.getParsedCommandLine().getOriginalLine().endsWith(" ") /* '{rollout ' */) {
                final String originalLine = ctx.getParsedCommandLine().getOriginalLine();
                int bufferIndex = originalLine.lastIndexOf(buffer);
                if(bufferIndex == -1) { // that's illegal state
                    return -1;
                }
                candidates.add("name=");
                candidates.addAll(Util.getServerGroups(ctx.getModelControllerClient()));
                return originalLine.length() - bufferIndex;
            } else if (ctx.getParsedCommandLine().getOriginalLine().endsWith("rollout")) {
                // In order to have the completion to be allowed to continue
                candidates.add(" ");
            }
            return buffer.length();
        }
        final ParsedOperationRequestHeader lastHeader = parsedOp.getLastHeader();
        if(!(lastHeader instanceof ParsedRolloutPlanHeader)) {
            throw new IllegalStateException("Expected " + ParsedRolloutPlanHeader.class + " but got " + lastHeader.getName() + " of " + lastHeader);
        }
        final ParsedRolloutPlanHeader rollout = (ParsedRolloutPlanHeader) lastHeader;

        if(rollout.endsOnPlanIdValueSeparator()) {
            candidates.addAll(Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN));
            return rollout.getLastSeparatorIndex() + 1;
        }

        final String planRef = rollout.getPlanRef();
        if(planRef != null) {
            final List<String> nodeNames = Util.getNodeNames(ctx.getModelControllerClient(), address, Util.ROLLOUT_PLAN);
            for(String name : nodeNames) {
                if(name.startsWith(planRef)) {
                    candidates.add(name);
                }
            }
            return rollout.getLastChunkIndex();
        }

        if(rollout.hasProperties()) {
            final String lastName = rollout.getLastPropertyName();
            if (Util.ROLLBACK_ACROSS_GROUPS.equals(lastName)) {
                if (rollout.getLastPropertyValue() != null) {
                    return -1;
                }
                candidates.add("}");
                candidates.add(";");
                return rollout.getLastChunkIndex() + lastName.length();
            }
            if (Util.ROLLBACK_ACROSS_GROUPS.startsWith(lastName)) {
                candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
            }
            return rollout.getLastChunkIndex();
        }

        final List<String> serverGroups = Util.getServerGroups(ctx.getModelControllerClient());
        boolean containsAllGroups = true;
        for (String group : serverGroups) {
            if (!rollout.containsGroup(group)) {
                containsAllGroups = false;
                break;
            }
        }

        if(rollout.endsOnGroupSeparator()) {
            if (containsAllGroups) {
                return -1;
            }
            for(String group : serverGroups) {
                if(!rollout.containsGroup(group)) {
                    candidates.add(group);
                }
            }
            return buffer.length();
        }

        final SingleRolloutPlanGroup lastGroup = rollout.getLastGroup();
        if(lastGroup == null) {
            return -1;
        }

        if (lastGroup.endsOnPropertyListEnd()) {
            if (!containsAllGroups) {
                candidates.add("^");
                candidates.add(",");
            } else if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
                candidates.add(Util.ROLLBACK_ACROSS_GROUPS);

            } else {
                candidates.add(" ");
            }
            return buffer.length();
        }

        if(lastGroup.endsOnPropertyListStart()) {
            candidates.add(Util.MAX_FAILED_SERVERS);
            candidates.add(Util.MAX_FAILURE_PERCENTAGE);
            candidates.add(Util.ROLLING_TO_SERVERS);
            candidates.add(Util.NOT_OPERATOR);
            return buffer.length();
        }

        // Only return the set of boolean properties
        if (lastGroup.endsOnNotOperator()) {
            candidates.add(Util.ROLLING_TO_SERVERS);
            return buffer.length();
        }

        if (lastGroup.hasProperties()) {
            // To propose the right end character
            boolean containsAll = lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)
                    && lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)
                    && lastGroup.hasProperty(Util.ROLLING_TO_SERVERS);

            final String propValue = lastGroup.getLastPropertyValue();
            if(propValue != null) {
                if(Util.TRUE.startsWith(propValue)) {
                    candidates.add(Util.TRUE);
                } else if(Util.FALSE.startsWith(propValue)) {
                    candidates.add(Util.FALSE);
                } else {
                    candidates.add(containsAll ? ")" : ",");
                    return buffer.length();
                }
            } else if(lastGroup.endsOnPropertyValueSeparator()) {
                if(Util.ROLLING_TO_SERVERS.equals(lastGroup.getLastPropertyName())) {
                    candidates.add(Util.FALSE);
                    candidates.add(containsAll ? ")" : ",");
                }
                return buffer.length();
            } else if(lastGroup.endsOnPropertySeparator()) {
                if(!lastGroup.hasProperty(Util.MAX_FAILED_SERVERS)) {
                    candidates.add(Util.MAX_FAILED_SERVERS);
                }
                if(!lastGroup.hasProperty(Util.MAX_FAILURE_PERCENTAGE)) {
                    candidates.add(Util.MAX_FAILURE_PERCENTAGE);
                }
                if(!lastGroup.hasProperty(Util.ROLLING_TO_SERVERS)) {
                    candidates.add(Util.ROLLING_TO_SERVERS);
                    candidates.add(Util.NOT_OPERATOR);
                }
                return lastGroup.getLastSeparatorIndex() + 1;
            } else {
                final String propName = lastGroup.getLastPropertyName();
                if(Util.MAX_FAILED_SERVERS.startsWith(propName)) {
                    candidates.add(Util.MAX_FAILED_SERVERS + '=');
                }
                if(Util.MAX_FAILURE_PERCENTAGE.startsWith(propName)) {
                    candidates.add(Util.MAX_FAILURE_PERCENTAGE + '=');
                } else if (Util.ROLLING_TO_SERVERS.equals(propName)) {
                    if (lastGroup.isLastPropertyNegated() && !containsAll) {
                        candidates.add(Util.ROLLING_TO_SERVERS + ",");
                    } else {
                        candidates.add("=" + Util.FALSE);
                        if (!containsAll) {
                            candidates.add(",");
                        } else {
                            candidates.add(")");
                        }
                    }

                } else if (Util.ROLLING_TO_SERVERS.startsWith(propName)) {
                    candidates.add(Util.ROLLING_TO_SERVERS);
                }
            }
            if (candidates.isEmpty() && containsAll) {
                candidates.add(")");
            }
            return lastGroup.getLastChunkIndex();
        }

        if (Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
            candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
            return buffer.length();
        }

        int result = lastGroup.getLastChunkIndex();

        final String groupName = lastGroup.getGroupName();

        boolean isLastGroup = false;
        for (String group : serverGroups) {
            if (group.equals(groupName)) {
                isLastGroup = true;
            }
            if (!isLastGroup && group.startsWith(groupName)) {
                candidates.add(group);
            }
        }

        if(Util.NAME.startsWith(groupName)) {
            candidates.add("name=");
        } else {
            if (candidates.isEmpty()) {
                if (isLastGroup) {
                    candidates.add("(");
                    if (containsAllGroups) {
                        candidates.add(Util.ROLLBACK_ACROSS_GROUPS);
                    } else {
                        candidates.add(",");
                        candidates.add("^");
                    }
                }
            }
        }

        return result;
    }
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()));
        }
    }
826534
@Override
    protected void doHandle(CommandContext ctx) throws CommandLineException {

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