<commit_before>package org.intermine.web.struts;

/*
 * Copyright (C) 2002-2007 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.actions.TilesAction;
import org.intermine.objectstore.query.ObjectStoreBag;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.WebUtil;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.profile.Profile;
import org.intermine.web.logic.profile.ProfileManager;
import org.intermine.web.logic.search.Scope;
import org.intermine.web.logic.search.SearchRepository;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.template.TemplateHelper;
import org.stringtree.json.JSONWriter;

/**
 * Controller for webSearchableList.tile
 * @author <NAME>
 */

public class WebSearchableListController extends TilesAction
{
      
    /**
     * Set up the attributes for webSearchableList.tile
     * {@inheritDoc}
     */
    @Override
    public ActionForward execute(ComponentContext context,
                                 @SuppressWarnings("unused") ActionMapping mapping,
                                 @SuppressWarnings("unused") ActionForm form,
                                 HttpServletRequest request,
                                 @SuppressWarnings("unused") HttpServletResponse response)
    throws Exception {
        String type = (String) context.getAttribute("type");
        String scope = (String) context.getAttribute("scope");
        String tags = (String) context.getAttribute("tags");
        String list = (String) context.getAttribute("list");
        String limit = (String) context.getAttribute("limit");
        Map filteredWebSearchables;
        
        
        HttpSession session = request.getSession();
     
        if (session.getAttribute("IS_SUPERUSER") != null 
                        && session.getAttribute("IS_SUPERUSER").equals(Boolean.TRUE)) {
            filteredWebSearchables = filterWebSearchables(request, type, 
                                                          TemplateHelper.USER_TEMPLATE, tags);
        
        } else if (scope.equals(TemplateHelper.ALL_TEMPLATE)) {
            Map globalWebSearchables =
                filterWebSearchables(request, type, TemplateHelper.GLOBAL_TEMPLATE, tags); 
            Map userWebSearchables =
                filterWebSearchables(request, type, TemplateHelper.USER_TEMPLATE, tags);
            filteredWebSearchables = new HashMap<String, WebSearchable>(userWebSearchables);
            filteredWebSearchables.putAll(globalWebSearchables);

        } else {
            filteredWebSearchables = filterWebSearchables(request, type, scope, tags);
       }

        if (list != null) {
            filteredWebSearchables = filterByList(filteredWebSearchables, list);
        }
        
        // shorten list to be < limit
        int limitInt = 0;
        if (limit != null) {
            try {
                limitInt = new Integer(limit.trim()).intValue();
            } catch (NumberFormatException e) {
                // ignore - don't shuffle 
            }
        }
        
        
        if (limitInt > 0) {
            filteredWebSearchables = WebUtil.shuffle(filteredWebSearchables, limitInt);
        } else {
            filteredWebSearchables = sortList(filteredWebSearchables);
        }
        
        Map<String, Object> wsMapForJS = new HashMap<String, Object>();
        
        for (String wsName: (Set<String>) filteredWebSearchables.keySet()) {
            wsMapForJS.put(wsName, new Integer(1));
        }
        
        Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
        request.setAttribute("userWebSearchables", profile.getWebSearchablesByType(type));
        
        request.setAttribute("filteredWebSearchables", filteredWebSearchables);
        
        JSONWriter jsonWriter = new JSONWriter();
        request.setAttribute("wsNames", jsonWriter.write(wsMapForJS));
        return null;
    }
    

    /**
     * Return a copy of the given Map sorted by creation date, then by name. 
     */
    private Map sortList(final Map filteredWebSearchables) {
        Map sortedMap = new TreeMap<String, WebSearchable>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                WebSearchable ws1 = (WebSearchable) filteredWebSearchables.get(o1);
                WebSearchable ws2 = (WebSearchable) filteredWebSearchables.get(o2);
                if (ws1 instanceof InterMineBag) {
                    InterMineBag bag1 = (InterMineBag) ws1;
                    if (ws2 instanceof InterMineBag) {
                        InterMineBag bag2 = (InterMineBag) ws2;
                        if (bag1.getDateCreated() != null && bag2.getDateCreated() != null) {
                            return bag2.getDateCreated().compareTo(bag1.getDateCreated());
                        } else {
                            return bag2.getName().compareTo(bag1.getName());
                        }
                    }
                } else if (!ws1.getTitle().equals(ws2.getTitle())) {
                    return ws1.getTitle().compareTo(ws2.getTitle());              
                } else {
                    return ws1.getName().compareTo(ws2.getName());              
                }
                
                return ((Comparable) o1).compareTo(o2);
            }
            
        });
        sortedMap.putAll(filteredWebSearchables);
        return sortedMap;
    }

    /**
     * Get all the WebSearchables in the given scope and of the given type. 
     */<commit_msg>fixed bugs with templates having the same title<commit_after>package org.intermine.web.struts;

/*
 * Copyright (C) 2002-2007 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.actions.TilesAction;
import org.intermine.objectstore.query.ObjectStoreBag;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.WebUtil;
import org.intermine.web.logic.bag.InterMineBag;
import org.intermine.web.logic.profile.Profile;
import org.intermine.web.logic.profile.ProfileManager;
import org.intermine.web.logic.search.Scope;
import org.intermine.web.logic.search.SearchRepository;
import org.intermine.web.logic.search.WebSearchable;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.logic.template.TemplateHelper;
import org.stringtree.json.JSONWriter;

/**
 * Controller for webSearchableList.tile
 * @author <NAME>
 */

public class WebSearchableListController extends TilesAction
{
      
    /**
     * Set up the attributes for webSearchableList.tile
     * {@inheritDoc}
     */
    @Override
    public ActionForward execute(ComponentContext context,
                                 @SuppressWarnings("unused") ActionMapping mapping,
                                 @SuppressWarnings("unused") ActionForm form,
                                 HttpServletRequest request,
                                 @SuppressWarnings("unused") HttpServletResponse response)
    throws Exception {
        String type = (String) context.getAttribute("type");
        String scope = (String) context.getAttribute("scope");
        String tags = (String) context.getAttribute("tags");
        String list = (String) context.getAttribute("list");
        String limit = (String) context.getAttribute("limit");
        Map filteredWebSearchables;
        
        
        HttpSession session = request.getSession();
     
        if (session.getAttribute("IS_SUPERUSER") != null 
                        && session.getAttribute("IS_SUPERUSER").equals(Boolean.TRUE)) {
            filteredWebSearchables = filterWebSearchables(request, type, 
                                                          TemplateHelper.USER_TEMPLATE, tags);
        
        } else if (scope.equals(TemplateHelper.ALL_TEMPLATE)) {
            Map globalWebSearchables =
                filterWebSearchables(request, type, TemplateHelper.GLOBAL_TEMPLATE, tags); 
            Map userWebSearchables =
                filterWebSearchables(request, type, TemplateHelper.USER_TEMPLATE, tags);
            filteredWebSearchables = new HashMap<String, WebSearchable>(userWebSearchables);
            filteredWebSearchables.putAll(globalWebSearchables);

        } else {
            filteredWebSearchables = filterWebSearchables(request, type, scope, tags);
       }

        if (list != null) {
            filteredWebSearchables = filterByList(filteredWebSearchables, list);
        }
        
        // shorten list to be < limit
        int limitInt = 0;
        if (limit != null) {
            try {
                limitInt = new Integer(limit.trim()).intValue();
            } catch (NumberFormatException e) {
                // ignore - don't shuffle 
            }
        }
        
        
        if (limitInt > 0) {
            filteredWebSearchables = WebUtil.shuffle(filteredWebSearchables, limitInt);
        } else {
            filteredWebSearchables = sortList(filteredWebSearchables);
        }
        
        Map<String, Object> wsMapForJS = new HashMap<String, Object>();
        
        for (String wsName: (Set<String>) filteredWebSearchables.keySet()) {
            wsMapForJS.put(wsName, new Integer(1));
        }
        
        Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
        request.setAttribute("userWebSearchables", profile.getWebSearchablesByType(type));
        
        request.setAttribute("filteredWebSearchables", filteredWebSearchables);
        
        JSONWriter jsonWriter = new JSONWriter();
        request.setAttribute("wsNames", jsonWriter.write(wsMapForJS));
        return null;
    }
    

    /**
     * Return a copy of the given Map sorted by creation date, then by name. 
     */
    private Map sortList(final Map filteredWebSearchables) {
        Map sortedMap = new TreeMap<String, WebSearchable>(new Comparator<String>() {
            public int compare(String o1, String o2) {
                WebSearchable ws1 = (WebSearchable) filteredWebSearchables.get(o1);
                WebSearchable ws2 = (WebSearchable) filteredWebSearchables.get(o2);
                if (ws1 instanceof InterMineBag) {
                    InterMineBag bag1 = (InterMineBag) ws1;
                    if (ws2 instanceof InterMineBag) {
                        InterMineBag bag2 = (InterMineBag) ws2;
                        if (bag1.getDateCreated() != null && bag2.getDateCreated() != null) {
                            return bag2.getDateCreated().compareTo(bag1.getDateCreated());
                        } else {
                            return bag2.getName().compareTo(bag1.getName());
                        }
                    }
                } else if (ws1.getTitle().equals(ws2.getTitle())) {
                    return ws1.getName().compareTo(ws2.getName());              
                } else {
                    return ws1.getTitle().compareTo(ws2.getTitle());              
                }
                
                return ((Comparable) o1).compareTo(o2);
            }
            
        });
        sortedMap.putAll(filteredWebSearchables);
        return sortedMap;
    }

    /**
     * Get all the WebSearchables in the given scope and of the given type. 
     */
{'fraction_non_alphanumeric': 0.09551986475063398, 'fraction_numerical': 0.005686621071236456, 'mean_word_length': 2.247005988023952, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7153902', 'n_tokens_mistral': 3440, 'n_tokens_neox': 3357, 'n_words': 713}