<commit_before>/*
 * Copyright (C) 2011 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package nl.b3p.viewer.admin.stripes;

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.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.components.ComponentRegistry;
import nl.b3p.viewer.config.app.ConfiguredComponent;
import nl.b3p.viewer.config.security.Group;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;

/**
 *
 * @author <NAME>
 */
@UrlBinding("/action/layoutmanager/{$event}")
@StrictBinding
@RolesAllowed("ApplicationAdmin")
public class LayoutManagerActionBean extends ApplicationActionBean {

    private JSONObject metadata;
    private JSONArray components;
    private List<Group> allGroups;
    @Validate(on = {"config", "removeComponent"})
    private String name;
    @Validate(on = "config")
    private String className;
    @Validate(on = "saveComponentConfig")
    private ConfiguredComponent component;
    @Validate(on = "saveComponentConfig")
    private String configObject;
    @Validate(on = "saveComponentConfig")
    private List<String> groups = new ArrayList<String>();
    @Validate(on = "saveApplicationLayout")
    private String layout;
    
    @Validate(on="saveComponentConfig")
    private String componentLayout;

    private Boolean loadCustomConfig=false;
    // <editor-fold defaultstate="collapsed" desc="getters and setters">
    public JSONArray getComponents() {
        return components;
    }

    public void setComponents(JSONArray components) {
        this.components = components;
    }

    public String getConfigObject() {
        return configObject;
    }

    public void setConfigObject(String configObject) {
        this.configObject = configObject;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ConfiguredComponent getComponent() {
        return component;
    }

    public void setComponent(ConfiguredComponent component) {
        this.component = component;
    }

    public JSONObject getMetadata() {
        return metadata;
    }

    public void setMetadata(JSONObject metadata) {
        this.metadata = metadata;
    }

    public List<Group> getAllGroups() {
        return allGroups;
    }

    public void setAllGroups(List<Group> allGroups) {
        this.allGroups = allGroups;
    }

    public List<String> getGroups() {
        return groups;
    }

    public void setGroups(List<String> groups) {
        this.groups = groups;
    }

    public String getLayout() {
        return layout;
    }

    public void setLayout(String layout) {
        this.layout = layout;
    }

    public String getComponentLayout() {
        return componentLayout;
    }

    public void setComponentLayout(String componentLayout) {
        this.componentLayout = componentLayout;
    }
    
    public Boolean getLoadCustomConfig() {
        return loadCustomConfig;
    }

    public void setLoadCustomConfig(Boolean loadCustomConfig) {
        this.loadCustomConfig = loadCustomConfig;
    }
    //</editor-fold>

    @DefaultHandler
    public Resolution view() throws JSONException {
        if (application == null) {
            getContext().getMessages().add(new SimpleError("Er moet eerst een bestaande applicatie geactiveerd of een nieuwe applicatie gemaakt worden."));
            return new ForwardResolution("/WEB-INF/jsp/application/chooseApplication.jsp");
        }
        Stripersist.getEntityManager().getTransaction().commit();

        return new ForwardResolution("/WEB-INF/jsp/application/layoutmanager.jsp");
    }

    public Resolution config() {
        EntityManager em = Stripersist.getEntityManager();

        allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList();

        try {
            component = (ConfiguredComponent) em.createQuery(
                    "from ConfiguredComponent where application = :application and name = :name").setParameter("application", application).setParameter("name", name).getSingleResult();
            groups = new ArrayList<String>(component.getReaders());
        } catch (NoResultException ex) {
            getContext().getValidationErrors().addGlobalError(new SimpleError(ex.getClass().getName() + ": " + ex.getMessage()));
        }
        metadata = ComponentRegistry.getInstance().getViewerComponent(className).getMetadata();
        
        if (metadata.has("configSource")){
            loadCustomConfig= true;
        }
        return new ForwardResolution("/WEB-INF/jsp/application/configPage.jsp");
    }

    public Resolution saveComponentConfig() {
        EntityManager em = Stripersist.getEntityManager();
        if (component == null) {
            component = new ConfiguredComponent();
        }
        component.setConfig(configObject);
        component.setName(name);
        component.setClassName(className);
        component.setApplication(application);
        Map<String,String> details = new HashMap<String,String>();
        details.put("layout",componentLayout);
        component.setDetails(details);

        component.getReaders().clear();
        component.setReaders(new HashSet<String>(groups));

        em.persist(component);
        em.getTransaction().commit();

        return config();
    }

    public Resolution removeComponent() {
<commit_msg>if there is a configXML and no Ext Property Grid settings. The settings in the xml is used. commented console.log<commit_after>/*
 * Copyright (C) 2011 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package nl.b3p.viewer.admin.stripes;

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.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import nl.b3p.viewer.components.ComponentRegistry;
import nl.b3p.viewer.config.app.ConfiguredComponent;
import nl.b3p.viewer.config.security.Group;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;

/**
 *
 * @author <NAME>
 */
@UrlBinding("/action/layoutmanager/{$event}")
@StrictBinding
@RolesAllowed("ApplicationAdmin")
public class LayoutManagerActionBean extends ApplicationActionBean {
    private static final Log log = LogFactory.getLog(LayoutManagerActionBean.class);
    
    private JSONObject metadata;
    private JSONArray components;
    private List<Group> allGroups;
    @Validate(on = {"config", "removeComponent"})
    private String name;
    @Validate(on = "config")
    private String className;
    @Validate(on = "saveComponentConfig")
    private ConfiguredComponent component;
    @Validate(on = "saveComponentConfig")
    private String configObject;
    @Validate(on = "saveComponentConfig")
    private List<String> groups = new ArrayList<String>();
    @Validate(on = "saveApplicationLayout")
    private String layout;
    
    @Validate(on="saveComponentConfig")
    private String componentLayout;

    private Boolean loadCustomConfig=false;
    // <editor-fold defaultstate="collapsed" desc="getters and setters">
    public JSONArray getComponents() {
        return components;
    }

    public void setComponents(JSONArray components) {
        this.components = components;
    }

    public String getConfigObject() {
        return configObject;
    }

    public void setConfigObject(String configObject) {
        this.configObject = configObject;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ConfiguredComponent getComponent() {
        return component;
    }

    public void setComponent(ConfiguredComponent component) {
        this.component = component;
    }

    public JSONObject getMetadata() {
        return metadata;
    }

    public void setMetadata(JSONObject metadata) {
        this.metadata = metadata;
    }

    public List<Group> getAllGroups() {
        return allGroups;
    }

    public void setAllGroups(List<Group> allGroups) {
        this.allGroups = allGroups;
    }

    public List<String> getGroups() {
        return groups;
    }

    public void setGroups(List<String> groups) {
        this.groups = groups;
    }

    public String getLayout() {
        return layout;
    }

    public void setLayout(String layout) {
        this.layout = layout;
    }

    public String getComponentLayout() {
        return componentLayout;
    }

    public void setComponentLayout(String componentLayout) {
        this.componentLayout = componentLayout;
    }
    
    public Boolean getLoadCustomConfig() {
        return loadCustomConfig;
    }

    public void setLoadCustomConfig(Boolean loadCustomConfig) {
        this.loadCustomConfig = loadCustomConfig;
    }
    //</editor-fold>

    @DefaultHandler
    public Resolution view() throws JSONException {    
        if (application == null) {
            getContext().getMessages().add(new SimpleError("Er moet eerst een bestaande applicatie geactiveerd of een nieuwe applicatie gemaakt worden."));
            return new ForwardResolution("/WEB-INF/jsp/application/chooseApplication.jsp");
        }
        Stripersist.getEntityManager().getTransaction().commit();

        return new ForwardResolution("/WEB-INF/jsp/application/layoutmanager.jsp");
    }

    public Resolution config() {
        EntityManager em = Stripersist.getEntityManager();

        allGroups = Stripersist.getEntityManager().createQuery("from Group").getResultList();

        try {
            component = (ConfiguredComponent) em.createQuery(
                    "from ConfiguredComponent where application = :application and name = :name").setParameter("application", application).setParameter("name", name).getSingleResult();
            groups = new ArrayList<String>(component.getReaders());
        } catch (NoResultException ex) {
            getContext().getValidationErrors().addGlobalError(new SimpleError(ex.getClass().getName() + ": " + ex.getMessage()));
        }
        metadata = ComponentRegistry.getInstance().getViewerComponent(className).getMetadata();
        
        if (metadata.has("configSource")){
            loadCustomConfig= true;
        }
        /* if there is a configXML and no Ext Property Grid settings. Get the settings from the xml*/
        if (metadata.has("configXML") && !metadata.has("extPropertyGridConfigs")){
            try{
                String xml=metadata.getString("configXML");
                JSONObject properties=new JSONObject();
                int beginIndex=xml.indexOf("[");
                int endIndex=-1;
                while(beginIndex!=-1 && beginIndex<xml.length()){
                    endIndex=xml.indexOf("]",beginIndex);
                    if (endIndex==-1)
                        break;
                    String name=xml.substring(beginIndex+1, endIndex);
                    properties.put(name,"");
                    beginIndex=xml.indexOf("[",endIndex);
                }
                JSONObject pgConfig = new JSONObject();
                pgConfig.put("source", properties);
                metadata.put("extPropertyGridConfigs",pgConfig);                
            }catch(JSONException je){
                log.error("Error while making 'extPropertyGridConfigs' properties for xml object",je);
            }
        }
        return new ForwardResolution("/WEB-INF/jsp/application/configPage.jsp");
    }

    public Resolution saveComponentConfig() {
        EntityManager em = Stripersist.getEntityManager();
        if (component == null) {
            component = new ConfiguredComponent();
        }
        component.setConfig(configObject);
        component.setName(name);
        component.setClassName(className);
        component.setApplication(application);
        Map<String,String> details = new HashMap<String,String>();
        details.put("layout",componentLayout);
        component.setDetails(details);

        component.getReaders().clear();
        component.setReaders(new HashSet<String>(groups));

        em.persist(component);
        em.getTransaction().commit();

        return config();
    }

    public Resolution removeComponent() {

{'fraction_non_alphanumeric': 0.09907973399610398, 'fraction_numerical': 0.0016121448243433868, 'mean_word_length': 3.055570689185508, 'pattern_counts': {'":': 2, '<': 34, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 9}, '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': '2404212', 'n_tokens_mistral': 3894, 'n_tokens_neox': 3804, 'n_words': 971}