<commit_before>/*
 * Copyright 2003 - 2013 The eFaps Team
 *
 * 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.
 *
 * Revision:        $Rev$
 * Last Changed:    $Date$
 * Last Changed By: $Author$
 */

package org.efaps.esjp.common.uiform;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.AttributeSet;
import org.efaps.admin.datamodel.Classification;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.attributetype.AbstractFileType;
import org.efaps.admin.datamodel.attributetype.RateType;
import org.efaps.admin.datamodel.ui.BitEnumUI;
import org.efaps.admin.datamodel.ui.RateUI;
import org.efaps.admin.event.EventDefinition;
import org.efaps.admin.event.EventExecution;
import org.efaps.admin.event.EventType;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.admin.ui.AbstractCommand;
import org.efaps.admin.ui.AbstractUserInterfaceObject.TargetMode;
import org.efaps.admin.ui.Form;
import org.efaps.admin.ui.field.Field;
import org.efaps.admin.ui.field.FieldClassification;
import org.efaps.admin.ui.field.FieldSet;
import org.efaps.admin.ui.field.FieldTable;
import org.efaps.db.Checkin;
import org.efaps.db.Context;
import org.efaps.db.Delete;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.Update;
import org.efaps.util.EFapsException;
import org.efaps.util.cache.CacheReloadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 * @version $Id$
 */
@EFapsUUID("3a99a177-8b5c-4dd4-b876-dcba28ea3138")
@EFapsRevision("$Rev$")
public abstract class Edit_Base
    implements EventExecution
{

    /**
     * Logging instance used in this class.
     */
    protected static final Logger LOG = LoggerFactory.getLogger(Edit.class);

    /**
     * String used as a temp key.
     */
    protected static final String FAKEROW = "NoMoreRowsExisting";

    /**
     * @param _parameter Parameter as provided by eFaps for a esjp
     * @throws EFapsException on error
     * @return empty Return
     */
    public Return execute(final Parameter _parameter)
        throws EFapsException
    {

        final Instance instance = _parameter.getInstance();
        final AbstractCommand command = (AbstractCommand) _parameter.get(ParameterValues.UIOBJECT);

        final Context context = Context.getThreadContext();
        // update the Values for the general form
        final String classifcationName = updateMainElements(_parameter, command.getTargetForm(), instance);

        // ************************************
        // check if we have a fileupload field
        if (context.getFileParameters().size() > 0) {
            for (final Field field : command.getTargetForm().getFields()) {
                final String attrName = field.getAttribute();
                if (attrName == null && field.isEditableDisplay(TargetMode.EDIT)) {
                    final Context.FileParameter fileItem = context.getFileParameters().get(field.getName());
                    if (fileItem != null) {
                        final Checkin checkin = new Checkin(instance);
                        try {
                            checkin.execute(fileItem.getName(), fileItem.getInputStream(), (int) fileItem.getSize());
                        } catch (final IOException e) {
                            throw new EFapsException(this.getClass(), "execute", e, _parameter);
                        }
                    }
                }
            }
        }
        if (classifcationName != null) {
            updateClassifcation(_parameter, instance, classifcationName);
        }
        return new Return();
    }

    /**
     * Method updates the main elements from the form.
     *
     * @param _parameter _parameter Parameter as provided by eFaps for a esjp
     * @param _form from used for the update
     * @param _instance instance that must be updated
     * @return the name of a classification if found in the form, else null
     * @throws EFapsException on error
     */
    public String updateMainElements(final Parameter _parameter,
                                     final Form _form,
                                     final Instance _instance)
        throws EFapsException
    {
        String ret = null;
        final List<FieldSet> fieldsets = new ArrayList<FieldSet>();
        final List<FieldTable> fieldTables = new ArrayList<FieldTable>();
        final List<Field> fields = new ArrayList<Field>();

        final PrintQuery print = new PrintQuery(_instance);
        for (final Field field : _form.getFields()) {
            if (field instanceof FieldSet) {
                fieldsets.add((FieldSet) field);
            } else if (field instanceof FieldTable && field.isEditableDisplay(TargetMode.EDIT)) {
                fieldTables.add((FieldTable) field);
            } else if (field instanceof FieldClassification) {
                ret = ((FieldClassification) field).getClassificationName();
            } else {
                final String attrName = field.getAttribute();
                if (attrName != null && field.isEditableDisplay(TargetMode.EDIT)) {
                    final Attribute attr = _instance.getType().getAttribute(attrName);
                    // check if not a fileupload
                    if (attr != null && !AbstractFileType.class.isAssignableFrom(
                                    attr.getAttributeType().getClassRepr())) {
                        print.addAttribute(attrName);
                        fields.add(field);
                    }
                }
            }
        }
        final Context context = Context.getThreadContext();
        if (print.execute()) {
            final Update update = new Update(_instance);
            for (final Field field : fields) {
                final String attrName = field.getAttribute();
                final Attribute attr = _instance.getType().getAttribute(attrName);
                if (attr != null && (context.getParameters().containsKey(field.getName())
                                || attr.getAttributeType().getUIProvider() instanceof BitEnumUI)) {
                    final String[] newValue = _parameter.getParameterValues(field.getName());
                    final Object object = print.getAttribute(attrName);
                    final String oldValue = object != null ? object.toString() : null;
                    if ((newValue == null && oldValue != null)
                                    || (newValue != null && !newValue.equals(oldValue))) {
                        add2Update(_parameter, update, attr, field.getName());
                    }
                }
            }
            update.execute();
        }
        updateFieldSets(_parameter, _instance, fieldsets);
        updateFieldTable(_parameter, _instance, fieldTables);
        return ret;
    }

    /**
     * Add to the given update.
     * @param _parameter Parameter as passed by the eFaps API
     * @param _update Update
     * @param _attr Attribute
     * @param _fieldName name of the Field
     * @throws EFapsException on error
     */
    protected void add2Update(final Parameter _parameter,
                              final Update _update,
                              final Attribute _attr,
                              final String _fieldName)
        throws EFapsException
    {
        final Context context = Context.getThreadContext();
        if (_attr.hasUoM()) {
            _update.add(_attr, new Object[] { _parameter.getParameterValue(_fieldName),
                            _parameter.getParameterValue(_fieldName + "UoM") });
        } else if (_attr.getAttributeType().getDbAttrType() instanceof RateType) {
            final String value =  _parameter.getParameterValue(_fieldName);
            final boolean inverted = "true".equalsIgnoreCase(context.getParameter(_fieldName
                            + RateUI.INVERTEDSUFFIX));
            _update.add(_attr, new Object[] { inverted ? 1 : value, inverted ? value : 1 });
        } else if (_attr.getAttributeType().getUIProvider() instanceof BitEnumUI) {
            _update.add(_attr, (Object[]) _parameter.getParameterValues(_fieldName));
        } else {
            _update.add(_attr,  _parameter.getParameterValue(_fieldName));<commit_msg>- kernel-install: adding method to basic edit esjp<commit_after>/*
 * Copyright 2003 - 2013 The eFaps Team
 *
 * 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.
 *
 * Revision:        $Rev$
 * Last Changed:    $Date$
 * Last Changed By: $Author$
 */

package org.efaps.esjp.common.uiform;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.AttributeSet;
import org.efaps.admin.datamodel.Classification;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.attributetype.AbstractFileType;
import org.efaps.admin.datamodel.attributetype.RateType;
import org.efaps.admin.datamodel.ui.BitEnumUI;
import org.efaps.admin.datamodel.ui.RateUI;
import org.efaps.admin.event.EventDefinition;
import org.efaps.admin.event.EventExecution;
import org.efaps.admin.event.EventType;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.program.esjp.EFapsRevision;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.admin.ui.AbstractCommand;
import org.efaps.admin.ui.AbstractUserInterfaceObject.TargetMode;
import org.efaps.admin.ui.Form;
import org.efaps.admin.ui.field.Field;
import org.efaps.admin.ui.field.FieldClassification;
import org.efaps.admin.ui.field.FieldSet;
import org.efaps.admin.ui.field.FieldTable;
import org.efaps.db.Checkin;
import org.efaps.db.Context;
import org.efaps.db.Delete;
import org.efaps.db.Insert;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.db.Update;
import org.efaps.util.EFapsException;
import org.efaps.util.cache.CacheReloadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 * @version $Id$
 */
@EFapsUUID("3a99a177-8b5c-4dd4-b876-dcba28ea3138")
@EFapsRevision("$Rev$")
public abstract class Edit_Base
    implements EventExecution
{

    /**
     * Logging instance used in this class.
     */
    protected static final Logger LOG = LoggerFactory.getLogger(Edit.class);

    /**
     * String used as a temp key.
     */
    protected static final String FAKEROW = "NoMoreRowsExisting";

    /**
     * @param _parameter Parameter as provided by eFaps for a esjp
     * @throws EFapsException on error
     * @return empty Return
     */
    public Return execute(final Parameter _parameter)
        throws EFapsException
    {

        final Instance instance = _parameter.getInstance();
        final AbstractCommand command = (AbstractCommand) _parameter.get(ParameterValues.UIOBJECT);

        final Context context = Context.getThreadContext();
        // update the Values for the general form
        final String classifcationName = updateMainElements(_parameter, command.getTargetForm(), instance);

        // ************************************
        // check if we have a fileupload field
        if (context.getFileParameters().size() > 0) {
            for (final Field field : command.getTargetForm().getFields()) {
                final String attrName = field.getAttribute();
                if (attrName == null && field.isEditableDisplay(TargetMode.EDIT)) {
                    final Context.FileParameter fileItem = context.getFileParameters().get(field.getName());
                    if (fileItem != null) {
                        final Checkin checkin = new Checkin(instance);
                        try {
                            checkin.execute(fileItem.getName(), fileItem.getInputStream(), (int) fileItem.getSize());
                        } catch (final IOException e) {
                            throw new EFapsException(this.getClass(), "execute", e, _parameter);
                        }
                    }
                }
            }
        }
        if (classifcationName != null) {
            updateClassifcation(_parameter, instance, classifcationName);
        }
        return new Return();
    }

    /**
     * Method updates the main elements from the form.
     *
     * @param _parameter _parameter Parameter as provided by eFaps for a esjp
     * @param _form from used for the update
     * @param _instance instance that must be updated
     * @return the name of a classification if found in the form, else null
     * @throws EFapsException on error
     */
    public String updateMainElements(final Parameter _parameter,
                                     final Form _form,
                                     final Instance _instance)
        throws EFapsException
    {
        String ret = null;
        final List<FieldSet> fieldsets = new ArrayList<FieldSet>();
        final List<FieldTable> fieldTables = new ArrayList<FieldTable>();
        final List<Field> fields = new ArrayList<Field>();

        final PrintQuery print = new PrintQuery(_instance);
        for (final Field field : _form.getFields()) {
            if (field instanceof FieldSet) {
                fieldsets.add((FieldSet) field);
            } else if (field instanceof FieldTable && field.isEditableDisplay(TargetMode.EDIT)) {
                fieldTables.add((FieldTable) field);
            } else if (field instanceof FieldClassification) {
                ret = ((FieldClassification) field).getClassificationName();
            } else {
                final String attrName = field.getAttribute();
                if (attrName != null && field.isEditableDisplay(TargetMode.EDIT)) {
                    final Attribute attr = _instance.getType().getAttribute(attrName);
                    // check if not a fileupload
                    if (attr != null && !AbstractFileType.class.isAssignableFrom(
                                    attr.getAttributeType().getClassRepr())) {
                        print.addAttribute(attrName);
                        fields.add(field);
                    }
                }
            }
        }
        final Context context = Context.getThreadContext();
        if (print.execute()) {
            final Update update = new Update(_instance);
            for (final Field field : fields) {
                final String attrName = field.getAttribute();
                final Attribute attr = _instance.getType().getAttribute(attrName);
                if (attr != null && (context.getParameters().containsKey(field.getName())
                                || attr.getAttributeType().getUIProvider() instanceof BitEnumUI)) {
                    final String[] newValue = _parameter.getParameterValues(field.getName());
                    final Object object = print.getAttribute(attrName);
                    final String oldValue = object != null ? object.toString() : null;
                    if ((newValue == null && oldValue != null)
                                    || (newValue != null && !newValue.equals(oldValue))) {
                        add2Update(_parameter, update, attr, field.getName());
                    }
                }
            }
            add2MainUpdate(_parameter, update);
            update.execute();
        }
        updateFieldSets(_parameter, _instance, fieldsets);
        updateFieldTable(_parameter, _instance, fieldTables);
        return ret;
    }

    /**
     * @param _parameter Parameter as passed by the eFaps API
     * @param _update Update
     * @param _update Update
     */
    protected void add2MainUpdate(final Parameter _parameter,
                                  final Update _update)
        throws EFapsException
    {
        // to be used form implementations
    }

    /**
     * Add to the given update.
     * @param _parameter Parameter as passed by the eFaps API
     * @param _update Update
     * @param _attr Attribute
     * @param _fieldName name of the Field
     * @throws EFapsException on error
     */
    protected void add2Update(final Parameter _parameter,
                              final Update _update,
                              final Attribute _attr,
                              final String _fieldName)
        throws EFapsException
    {
        final Context context = Context.getThreadContext();
        if (_attr.hasUoM()) {
            _update.add(_attr, new Object[] { _parameter.getParameterValue(_fieldName),
                            _parameter.getParameterValue(_fieldName + "UoM") });
        } else if (_attr.getAttributeType().getDbAttrType() instanceof RateType) {
            final String value =  _parameter.getParameterValue(_fieldName);
            final boolean inverted = "true".equalsIgnoreCase(context.getParameter(_fieldName
                            + RateUI.INVERTEDSUFFIX));
            _update.add(_attr, new Object[] { inverted ? 1 : value, inverted ? value : 1 });
        } else if (_attr.getAttributeType().getUIProvider() instanceof BitEnumUI) {
            _update.add(_attr, (Object[]) _parameter.getParameterValues(_fieldName));
        } else {
            _update.add(_attr,  _parameter.getParameterValue(_fieldName));
{'fraction_non_alphanumeric': 0.09912157596548678, 'fraction_numerical': 0.004054264774676439, 'mean_word_length': 2.3455051295426883, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 11, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4554647', 'n_tokens_mistral': 5110, 'n_tokens_neox': 4943, 'n_words': 1310}