<commit_before>/*
 * Copyright (c) 2008-2016 Haulmont.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.haulmont.cuba.gui.app.security.constraint.edit;

import com.google.common.base.Strings;
import com.haulmont.bali.util.Dom4j;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.entity.BaseGenericIdEntity;
import com.haulmont.cuba.core.entity.annotation.UnavailableInSecurityConstraints;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.core.global.filter.GroovyGenerator;
import com.haulmont.cuba.core.global.filter.SecurityJpqlGenerator;
import com.haulmont.cuba.core.sys.jpql.ErrorRec;
import com.haulmont.cuba.core.sys.jpql.JpqlSyntaxException;
import com.haulmont.cuba.gui.AppConfig;
import com.haulmont.cuba.gui.WindowManagerProvider;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.autocomplete.JpqlSuggestionFactory;
import com.haulmont.cuba.gui.components.autocomplete.Suggestion;
import com.haulmont.cuba.gui.components.filter.ConditionsTree;
import com.haulmont.cuba.gui.components.filter.FakeFilterSupport;
import com.haulmont.cuba.gui.components.filter.FilterParser;
import com.haulmont.cuba.gui.components.filter.Param;
import com.haulmont.cuba.gui.components.filter.edit.FilterEditor;
import com.haulmont.cuba.gui.config.WindowConfig;
import com.haulmont.cuba.gui.config.WindowInfo;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.data.DsBuilder;
import com.haulmont.cuba.security.app.UserManagementService;
import com.haulmont.cuba.security.entity.Constraint;
import com.haulmont.cuba.security.entity.ConstraintCheckType;
import com.haulmont.cuba.security.entity.ConstraintOperationType;
import com.haulmont.cuba.security.entity.FilterEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.text.TextStringBuilder;
import org.codehaus.groovy.control.CompilationFailedException;
import org.dom4j.Element;

import javax.inject.Inject;
import java.util.*;

import static com.haulmont.cuba.gui.WindowManager.OpenType;
import static java.util.Arrays.asList;

public class ConstraintEditor extends AbstractEditor<Constraint> {

    @Inject
    protected LookupField<String> entityName;

    @Inject
    protected SourceCodeEditor joinClause;

    @Inject
    protected SourceCodeEditor whereClause;

    @Inject
    protected SourceCodeEditor groovyScript;

    @Inject
    protected Label groovyScriptLabel;

    @Inject
    protected Label joinClauseLabel;

    @Inject
    protected Label whereClauseLabel;

    @Inject
    protected TextField code;

    @Inject
    protected Label codeLabel;

    @Inject
    protected LookupField operationType;

    @Inject
    protected Datasource<Constraint> constraint;

    @Inject
    protected Metadata metadata;

    @Inject
    protected ExtendedEntities extendedEntities;

    @Inject
    protected WindowManagerProvider windowManagerProvider;

    @Inject
    protected Button testConstraint;

    @Inject
    protected WindowConfig windowConfig;

    @Inject
    protected LookupField type;

    @Inject
    protected UserManagementService userManagementService;

    @Inject
    protected Security security;

    protected Map<Object, String> entities;

    protected static final String SESSION_PREFIX = "session$";

    @Override
    public void postInit() {
        Map<String, String> options = new TreeMap<>();
        MessageTools messageTools = AppBeans.get(MessageTools.NAME);
        entities = new HashMap<>();
        for (MetaClass metaClass : metadata.getSession().getClasses()) {
            if (extendedEntities.getExtendedClass(metaClass) == null && BaseGenericIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                if (!isUnavailableInSecurityConstraints(metaClass)) {
                    MetaClass mainMetaClass = extendedEntities.getOriginalOrThisMetaClass(metaClass);
                    String originalName = mainMetaClass.getName();
                    options.put(messageTools.getEntityCaption(metaClass) + " (" + metaClass.getName() + ")", originalName);
                    entities.put(originalName, metaClass.getName());
                }
            }
        }
        entityName.setOptionsMap(options);

        joinClause.setSuggester((source, text, cursorPosition) -> requestHint(joinClause, text, cursorPosition));
        whereClause.setSuggester((source, text, cursorPosition) -> requestHint(whereClause, text, cursorPosition));

        setupVisibility();
        constraint.addItemPropertyChangeListener(e -> {
            if ("checkType".equals(e.getProperty()) || "operationType".equals(e.getProperty())) {
                setupVisibility();
            }
        });

        // temporary hide for desktop #1218
        if (AppConfig.getClientType() == ClientType.WEB) {
            joinClause.setContextHelpIconClickHandler(event ->
                    getJoinClauseHelp());
            whereClause.setContextHelpIconClickHandler(event ->
                    getWhereClauseHelp());
            groovyScript.setContextHelpIconClickHandler(event ->
                    getGroovyScriptHelp());
        }

        String groupInstanceName = metadata.getTools().getInstanceName(getItem().getGroup());
        setCaption(formatMessage("caption", groupInstanceName));
    }

    protected void setupVisibility() {
        Constraint item = getItem();
        asList(groovyScript, groovyScriptLabel)
                .forEach(component -> component.setVisible(item.getCheckType().memory()));
        asList(joinClause, joinClauseLabel, whereClause, whereClauseLabel)
                .forEach(component -> component.setVisible(item.getCheckType().database() &&
                        item.getOperationType() != ConstraintOperationType.CREATE &&
                        item.getOperationType() != ConstraintOperationType.DELETE &&
                        item.getOperationType() != ConstraintOperationType.UPDATE));
        asList(code, codeLabel)
                .forEach(component -> component.setVisible(item.getOperationType() == ConstraintOperationType.CUSTOM));

        if (item.getOperationType() != ConstraintOperationType.ALL &&
                item.getOperationType() != ConstraintOperationType.CUSTOM &&
                item.getOperationType() != ConstraintOperationType.READ) {
            item.setCheckType(ConstraintCheckType.MEMORY);
            type.setEnabled(false);
        } else {
            type.setEnabled(true);
        }
    }
<commit_msg>Group ConstraintEditor screen 'testConstraint' method validates unused fields #1630<commit_after>/*
 * Copyright (c) 2008-2016 Haulmont.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.haulmont.cuba.gui.app.security.constraint.edit;

import com.google.common.base.Strings;
import com.haulmont.bali.util.Dom4j;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.entity.BaseGenericIdEntity;
import com.haulmont.cuba.core.entity.annotation.UnavailableInSecurityConstraints;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.core.global.filter.GroovyGenerator;
import com.haulmont.cuba.core.global.filter.SecurityJpqlGenerator;
import com.haulmont.cuba.core.sys.jpql.ErrorRec;
import com.haulmont.cuba.core.sys.jpql.JpqlSyntaxException;
import com.haulmont.cuba.gui.AppConfig;
import com.haulmont.cuba.gui.WindowManagerProvider;
import com.haulmont.cuba.gui.components.*;
import com.haulmont.cuba.gui.components.autocomplete.JpqlSuggestionFactory;
import com.haulmont.cuba.gui.components.autocomplete.Suggestion;
import com.haulmont.cuba.gui.components.filter.ConditionsTree;
import com.haulmont.cuba.gui.components.filter.FakeFilterSupport;
import com.haulmont.cuba.gui.components.filter.FilterParser;
import com.haulmont.cuba.gui.components.filter.Param;
import com.haulmont.cuba.gui.components.filter.edit.FilterEditor;
import com.haulmont.cuba.gui.config.WindowConfig;
import com.haulmont.cuba.gui.config.WindowInfo;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.data.DsBuilder;
import com.haulmont.cuba.security.app.UserManagementService;
import com.haulmont.cuba.security.entity.Constraint;
import com.haulmont.cuba.security.entity.ConstraintCheckType;
import com.haulmont.cuba.security.entity.ConstraintOperationType;
import com.haulmont.cuba.security.entity.FilterEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.text.TextStringBuilder;
import org.codehaus.groovy.control.CompilationFailedException;
import org.dom4j.Element;

import javax.inject.Inject;
import java.util.*;

import static com.haulmont.cuba.gui.WindowManager.OpenType;
import static java.util.Arrays.asList;

public class ConstraintEditor extends AbstractEditor<Constraint> {

    @Inject
    protected LookupField<String> entityName;

    @Inject
    protected SourceCodeEditor joinClause;

    @Inject
    protected SourceCodeEditor whereClause;

    @Inject
    protected SourceCodeEditor groovyScript;

    @Inject
    protected Label groovyScriptLabel;

    @Inject
    protected Label joinClauseLabel;

    @Inject
    protected Label whereClauseLabel;

    @Inject
    protected TextField code;

    @Inject
    protected Label codeLabel;

    @Inject
    protected LookupField operationType;

    @Inject
    protected Datasource<Constraint> constraint;

    @Inject
    protected Metadata metadata;

    @Inject
    protected ExtendedEntities extendedEntities;

    @Inject
    protected WindowManagerProvider windowManagerProvider;

    @Inject
    protected Button testConstraint;

    @Inject
    protected WindowConfig windowConfig;

    @Inject
    protected LookupField type;

    @Inject
    protected UserManagementService userManagementService;

    @Inject
    protected Security security;

    protected Map<Object, String> entities;

    protected static final String SESSION_PREFIX = "session$";

    @Override
    public void postInit() {
        Map<String, String> options = new TreeMap<>();
        MessageTools messageTools = AppBeans.get(MessageTools.NAME);
        entities = new HashMap<>();
        for (MetaClass metaClass : metadata.getSession().getClasses()) {
            if (extendedEntities.getExtendedClass(metaClass) == null && BaseGenericIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                if (!isUnavailableInSecurityConstraints(metaClass)) {
                    MetaClass mainMetaClass = extendedEntities.getOriginalOrThisMetaClass(metaClass);
                    String originalName = mainMetaClass.getName();
                    options.put(messageTools.getEntityCaption(metaClass) + " (" + metaClass.getName() + ")", originalName);
                    entities.put(originalName, metaClass.getName());
                }
            }
        }
        entityName.setOptionsMap(options);

        joinClause.setSuggester((source, text, cursorPosition) -> requestHint(joinClause, text, cursorPosition));
        whereClause.setSuggester((source, text, cursorPosition) -> requestHint(whereClause, text, cursorPosition));

        setupVisibility();
        constraint.addItemPropertyChangeListener(e -> {
            if ("checkType".equals(e.getProperty()) || "operationType".equals(e.getProperty())) {
                setupVisibility();
            }
        });

        // temporary hide for desktop #1218
        if (AppConfig.getClientType() == ClientType.WEB) {
            joinClause.setContextHelpIconClickHandler(event ->
                    getJoinClauseHelp());
            whereClause.setContextHelpIconClickHandler(event ->
                    getWhereClauseHelp());
            groovyScript.setContextHelpIconClickHandler(event ->
                    getGroovyScriptHelp());
        }

        String groupInstanceName = metadata.getTools().getInstanceName(getItem().getGroup());
        setCaption(formatMessage("caption", groupInstanceName));
    }

    protected void setupVisibility() {
        Constraint item = getItem();
        asList(groovyScript, groovyScriptLabel)
                .forEach(component -> component.setVisible(item.getCheckType().memory()));
        asList(joinClause, joinClauseLabel, whereClause, whereClauseLabel)
                .forEach(component -> component.setVisible(item.getCheckType().database() &&
                        item.getOperationType() != ConstraintOperationType.CREATE &&
                        item.getOperationType() != ConstraintOperationType.DELETE &&
                        item.getOperationType() != ConstraintOperationType.UPDATE));
        asList(code, codeLabel)
                .forEach(component -> component.setVisible(item.getOperationType() == ConstraintOperationType.CUSTOM));

        if (item.getOperationType() != ConstraintOperationType.ALL &&
                item.getOperationType() != ConstraintOperationType.CUSTOM &&
                item.getOperationType() != ConstraintOperationType.READ) {
            item.setCheckType(ConstraintCheckType.MEMORY);
            type.setEnabled(false);
        } else {
            type.setEnabled(true);
        }

        if (!item.getCheckType().database()) {
            item.setJoinClause(null);
            item.setWhereClause(null);
        }
    }

{'fraction_non_alphanumeric': 0.09770550540894371, 'fraction_numerical': 0.0030317646248191276, 'mean_word_length': 3.44124847001224, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3441042', 'n_tokens_mistral': 4004, 'n_tokens_neox': 3874, 'n_words': 748}