<commit_before>/*
 * jPOS Project [http://jpos.org]
 * Copyright (C) 2000-2011 <NAME>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jpos.ee.pm.core.operations;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.jpos.ee.Constants;
import org.jpos.ee.pm.converter.Converter;
import org.jpos.ee.pm.converter.ConverterException;
import org.jpos.ee.pm.converter.IgnoreConvertionException;
import org.jpos.ee.pm.core.*;
import org.jpos.ee.pm.validator.ValidationResult;
import org.jpos.ee.pm.validator.Validator;
import org.jpos.util.DisplacedList;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;

/**
 *
 * @author jpaoletti
 */
public class OperationCommandSupport implements OperationCommand {

    public static final String FINISH = "finish";
    public static final String PM_ENTITY_INSTANCE = "PM_ENTITY_INSTANCE";
    public static final String LAST_PM_ID = "LAST_PM_ID";
    public static final String PM_ID = "PM_ID";
    public static final String OPERATIONS = "operations";
    public static final String PM_ITEM = "item";
    private String operationId;
    private Operation operation;

    public OperationCommandSupport(String operationId) {
        this.operationId = operationId;
    }

    protected boolean prepare(PMContext ctx) throws PMException {
        //No session or no user when user is required.
        if (ctx.getPMSession() == null || (checkUser() && ctx.getUser() == null)) {
            throw new PMUnauthorizedException();
        }
        configureEntityContainer(ctx);
        configureSelected(ctx);
        operation = configureOperations(ctx);
        //Try to refresh selected object, if there is one
        refreshSelectedObject(ctx, null);
        return true;
    }

    @Override
    public boolean execute(PMContext ctx) throws PMException {
        boolean step = prepare(ctx);
        if (step) {
            internalExecute(ctx);
        }
        return step;
    }

    protected void internalExecute(PMContext ctx) throws PMException {
        ctx.getPresentationManager().debug(this, "Executing operation " + getOperationId());
        /* Validate de operation*/
        if (ctx.getSelected() != null) {
            validate(ctx);
        }

        Object tx = null;
        try {
            if (openTransaction()) {
                tx = ctx.getPresentationManager().getPersistenceManager().startTransaction(ctx);
                ctx.getPresentationManager().debug(this, "Started Transaction " + tx);
            }
            if (operation != null && operation.getContext() != null) {
                operation.getContext().preExecute(ctx);
            }

            /** EXCECUTES THE OPERATION **/
            doExecute(ctx);

            if (operation != null && operation.getContext() != null) {
                operation.getContext().postExecute(ctx);
            }

            /*if(isAuditable(ctx)){
            logRevision (ctx.getDB(), (ctx.getEntity()!=null)?ctx.getEntity().getId():null, ctx.getOper_id(), ctx.getUser());
            }*/
            try {
                if (tx != null) {
                    ctx.getPresentationManager().debug(this, "Commiting Transaction " + tx);
                    ctx.getPresentationManager().getPersistenceManager().commit(ctx, tx);
                }
            } catch (Exception e) {
                ctx.getPresentationManager().error(e);
                throw new PMException("pm_core.cannot.commit.txn");
            }
            tx = null;
        } catch (PMException e) {
            throw e;
        } catch (Exception e) {
            ctx.getPresentationManager().error(e);
            throw new PMException(e);
        } finally {
            if (tx != null) {
                ctx.getPresentationManager().debug(this, "Rolling Back Transaction " + tx);
                try {
                    ctx.getPresentationManager().getPersistenceManager().rollback(ctx, tx);
                } catch (Exception e) {
                    ctx.getPresentationManager().error(e);
                }
            }
        }
    }

    /**
     *
     */
    private void validate(PMContext ctx) throws PMException {
        if (ctx.getBoolean("validate", true)) {
            if (ctx.getOperation() != null && ctx.getOperation().getValidators() != null && ctx.getSelected() != null) {
                for (Validator ev : ctx.getOperation().getValidators()) {
                    ctx.put(PM_ENTITY_INSTANCE, ctx.getSelected().getInstance());
                    ValidationResult vr = ev.validate(ctx);

                    ctx.getErrors().addAll(vr.getMessages());
                    if (!vr.isSuccessful()) {
                        throw new PMException();
                    }
                }
            }
        }
    }

    public void configureSelected(PMContext ctx) throws NumberFormatException, PMException {
        if (ctx.getBoolean("clean_selected", false)) {
            ctx.getEntityContainer().setSelected(null);
        }
        //If we get item param, we change the selected item on the container
        String item = ctx.getString(PM_ITEM);
        if (item != null && !item.trim().equals("")) {
            Integer index = Integer.parseInt(item);
            ctx.getPresentationManager().debug(this, "Getting row index: " + index);
            if (index != null) {
                DisplacedList<Object> al = new DisplacedList<Object>();
                al.addAll(ctx.getList().getContents());
                al.setDisplacement(ctx.getList().getContents().getDisplacement());
                ctx.getEntityContainer().setSelected(new EntityInstanceWrapper(al.get(index)));
            }
        } else {
            String identified = (String) ctx.getParameter("identified");
            if (identified != null && identified.trim().compareTo("") != 0) {
                ctx.getPresentationManager().debug(this, "Getting row identified by: " + identified);
                String[] ss = identified.split(":");
                //TODO Throw exception when the size of this is not 2
                if (ss.length != 2) {
                    ctx.getPresentationManager().error("Ivalid row identifier!");
                } else {
                    String prop = ss[0];
                    String value = ss[1];
                    EntityInstanceWrapper wrapper = new EntityInstanceWrapper(ctx.getEntity().getDataAccess().getItem(ctx, prop, value));
                    ctx.getEntityContainer().setSelected(wrapper);
                }
            } else {
                ctx.getPresentationManager().debug(this, "Row Selection ignored");
            }
        }
        refreshSelectedObject(ctx, null);
        if (ctx.getOperation() != null && ctx.getOperation().getContext() != null) {
            ctx.getOperation().getContext().preConversion(ctx);
        }
        if (checkSelected() && ctx.getEntityContainer().getSelected() == null) {
            throw new PMException("unknow.item");
        }
    }

    public Operation configureOperations(PMContext ctx) throws PMException {
        final Operation op = (ctx.hasEntity()) ? ctx.getEntity().getOperations().getOperation(operationId) : null;
        ctx.setOperation(op);
        if (ctx.hasEntity()) {
            ctx.getEntityContainer().setOperation(op);
            if (ctx.getEntity().isWeak()) {
                ctx.getEntityContainer().setOwner(getEntityContainer(ctx, ctx.getEntity().getOwner().getEntityId()));
                if (ctx.getEntityContainer().getOwner() == null) {<commit_msg>BugFix, we check that the object exists when we got it by identified property.<commit_after>/*
 * jPOS Project [http://jpos.org]
 * Copyright (C) 2000-2011 <NAME>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jpos.ee.pm.core.operations;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.jpos.ee.Constants;
import org.jpos.ee.pm.converter.Converter;
import org.jpos.ee.pm.converter.ConverterException;
import org.jpos.ee.pm.converter.IgnoreConvertionException;
import org.jpos.ee.pm.core.*;
import org.jpos.ee.pm.validator.ValidationResult;
import org.jpos.ee.pm.validator.Validator;
import org.jpos.util.DisplacedList;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;

/**
 *
 * @author jpaoletti
 */
public class OperationCommandSupport implements OperationCommand {

    public static final String FINISH = "finish";
    public static final String PM_ENTITY_INSTANCE = "PM_ENTITY_INSTANCE";
    public static final String LAST_PM_ID = "LAST_PM_ID";
    public static final String PM_ID = "PM_ID";
    public static final String OPERATIONS = "operations";
    public static final String PM_ITEM = "item";
    private String operationId;
    private Operation operation;

    public OperationCommandSupport(String operationId) {
        this.operationId = operationId;
    }

    protected boolean prepare(PMContext ctx) throws PMException {
        //No session or no user when user is required.
        if (ctx.getPMSession() == null || (checkUser() && ctx.getUser() == null)) {
            throw new PMUnauthorizedException();
        }
        configureEntityContainer(ctx);
        configureSelected(ctx);
        operation = configureOperations(ctx);
        //Try to refresh selected object, if there is one
        refreshSelectedObject(ctx, null);
        return true;
    }

    @Override
    public boolean execute(PMContext ctx) throws PMException {
        boolean step = prepare(ctx);
        if (step) {
            internalExecute(ctx);
        }
        return step;
    }

    protected void internalExecute(PMContext ctx) throws PMException {
        ctx.getPresentationManager().debug(this, "Executing operation " + getOperationId());
        /* Validate de operation*/
        if (ctx.getSelected() != null) {
            validate(ctx);
        }

        Object tx = null;
        try {
            if (openTransaction()) {
                tx = ctx.getPresentationManager().getPersistenceManager().startTransaction(ctx);
                ctx.getPresentationManager().debug(this, "Started Transaction " + tx);
            }
            if (operation != null && operation.getContext() != null) {
                operation.getContext().preExecute(ctx);
            }

            /** EXCECUTES THE OPERATION **/
            doExecute(ctx);

            if (operation != null && operation.getContext() != null) {
                operation.getContext().postExecute(ctx);
            }

            /*if(isAuditable(ctx)){
            logRevision (ctx.getDB(), (ctx.getEntity()!=null)?ctx.getEntity().getId():null, ctx.getOper_id(), ctx.getUser());
            }*/
            try {
                if (tx != null) {
                    ctx.getPresentationManager().debug(this, "Commiting Transaction " + tx);
                    ctx.getPresentationManager().getPersistenceManager().commit(ctx, tx);
                }
            } catch (Exception e) {
                ctx.getPresentationManager().error(e);
                throw new PMException("pm_core.cannot.commit.txn");
            }
            tx = null;
        } catch (PMException e) {
            throw e;
        } catch (Exception e) {
            ctx.getPresentationManager().error(e);
            throw new PMException(e);
        } finally {
            if (tx != null) {
                ctx.getPresentationManager().debug(this, "Rolling Back Transaction " + tx);
                try {
                    ctx.getPresentationManager().getPersistenceManager().rollback(ctx, tx);
                } catch (Exception e) {
                    ctx.getPresentationManager().error(e);
                }
            }
        }
    }

    /**
     *
     */
    private void validate(PMContext ctx) throws PMException {
        if (ctx.getBoolean("validate", true)) {
            if (ctx.getOperation() != null && ctx.getOperation().getValidators() != null && ctx.getSelected() != null) {
                for (Validator ev : ctx.getOperation().getValidators()) {
                    ctx.put(PM_ENTITY_INSTANCE, ctx.getSelected().getInstance());
                    ValidationResult vr = ev.validate(ctx);

                    ctx.getErrors().addAll(vr.getMessages());
                    if (!vr.isSuccessful()) {
                        throw new PMException();
                    }
                }
            }
        }
    }

    public void configureSelected(PMContext ctx) throws NumberFormatException, PMException {
        if (ctx.getBoolean("clean_selected", false)) {
            ctx.getEntityContainer().setSelected(null);
        }
        //If we get item param, we change the selected item on the container
        String item = ctx.getString(PM_ITEM);
        if (item != null && !item.trim().equals("")) {
            Integer index = Integer.parseInt(item);
            ctx.getPresentationManager().debug(this, "Getting row index: " + index);
            if (index != null) {
                DisplacedList<Object> al = new DisplacedList<Object>();
                al.addAll(ctx.getList().getContents());
                al.setDisplacement(ctx.getList().getContents().getDisplacement());
                ctx.getEntityContainer().setSelected(new EntityInstanceWrapper(al.get(index)));
            }
        } else {
            String identified = (String) ctx.getParameter("identified");
            if (identified != null && identified.trim().compareTo("") != 0) {
                ctx.getPresentationManager().debug(this, "Getting row identified by: " + identified);
                String[] ss = identified.split(":");
                //TODO Throw exception when the size of this is not 2
                if (ss.length != 2) {
                    throw new PMException("unknow.item");
                } else {
                    final String prop = ss[0];
                    final String value = ss[1];
                    final Object object = ctx.getEntity().getDataAccess().getItem(ctx, prop, value);
                    if(object==null)
                        throw new PMException("unknow.item");
                    final EntityInstanceWrapper wrapper = new EntityInstanceWrapper(object);
                    ctx.getEntityContainer().setSelected(wrapper);
                }
            } else {
                ctx.getPresentationManager().debug(this, "Row Selection ignored");
            }
        }
        refreshSelectedObject(ctx, null);
        if (ctx.getOperation() != null && ctx.getOperation().getContext() != null) {
            ctx.getOperation().getContext().preConversion(ctx);
        }
        if (checkSelected() && ctx.getEntityContainer().getSelected() == null) {
            throw new PMException("unknow.item");
        }
    }

    public Operation configureOperations(PMContext ctx) throws PMException {
        final Operation op = (ctx.hasEntity()) ? ctx.getEntity().getOperations().getOperation(operationId) : null;
        ctx.setOperation(op);
        if (ctx.hasEntity()) {
            ctx.getEntityContainer().setOperation(op);
            if (ctx.getEntity().isWeak()) {
                ctx.getEntityContainer().setOwner(getEntityContainer(ctx, ctx.getEntity().getOwner().getEntityId()));
                if (ctx.getEntityContainer().getOwner() == null) {
{'fraction_non_alphanumeric': 0.11570048309178745, 'fraction_numerical': 0.0016908212560386474, 'mean_word_length': 2.1817483189241114, 'pattern_counts': {'":': 2, '<': 11, '<?xml version=': 0, '>': 11, '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': '374050', 'n_tokens_mistral': 4295, 'n_tokens_neox': 4174, 'n_words': 1064}